Compare commits

..

1 Commits

8 changed files with 212 additions and 5 deletions
Generated
+4 -4
View File
@@ -139,7 +139,7 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fiscus-capture"
version = "0.2.1"
version = "0.3.0"
dependencies = [
"fiscus-ledger",
"proptest",
@@ -150,7 +150,7 @@ dependencies = [
[[package]]
name = "fiscus-insight"
version = "0.2.1"
version = "0.3.0"
dependencies = [
"fiscus-ledger",
"serde",
@@ -159,7 +159,7 @@ dependencies = [
[[package]]
name = "fiscus-ledger"
version = "0.2.1"
version = "0.3.0"
dependencies = [
"proptest",
"serde",
@@ -169,7 +169,7 @@ dependencies = [
[[package]]
name = "fiscus-statement"
version = "0.2.1"
version = "0.3.0"
dependencies = [
"encoding_rs",
"fiscus-ledger",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
[workspace.package]
version = "0.2.1"
version = "0.3.0"
edition = "2021"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
+15
View File
@@ -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()
}
+38
View File
@@ -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());
+13
View File
@@ -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> },
}
+46
View File
@@ -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(())
}
+86
View File
@@ -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);
}
}
+9
View File
@@ -19,6 +19,10 @@ is a log of its own (one MLS group): its members see exactly what was put into i
| `capture.token_added` / `capture.token_revoked` | personal | a phone's capture token: only its SHA-256 (`token`), a `name` and the `kind` (`iphone`, `android`). The token itself lives in Custos |
| `share.link_created` | personal | a share link for one person of one split: only the SHA-256 of the link token, `split`, `person`, `expires` |
| `account.set` | personal | the account for QR Platba (`iban`, `name`); the log is encrypted everywhere it is stored |
| `profile.named` | personal | the name you show to the members of your shared budgets (1–40 characters) *(v0.3.0)* |
| `household.sharing_set` | personal | `budget, on`: share your subscription names with this shared budget, or stop. Rejected for the default budget or an unknown one *(v0.3.0)* |
| `member.named` | shared budget | `budget, name`: what its author is called there. The latest per author counts *(v0.3.0)* |
| `subscriptions.shared` | shared budget | `budget, names`: the service keys of every subscription its author still pays (at most 100, each 1–40 characters, no repeats). The latest per author replaces the earlier; `[]` withdraws them *(v0.3.0)* |
`apply()` stays total: anything that does not fit is recorded in `state.rejected` with the reason.
@@ -73,3 +77,8 @@ synthetic templates that live only in the tests.
`household_duplicates(&[(member, names)])`: the subscription merchant keys two or more members share, each
with its members. It runs only on names members chose to share into the household group (opt-in, asked once).
Nobody's names are read without that.
`shared_names(state, today)` *(v0.3.0)* is what a member who opted in sends: the **service key** (the first word
of the merchant key, at least three letters) of every subscription they still pay (active, or charged after a
cancel), sorted, at most 100. Only the key leaves: `PAYPAL *SPOTIFY 4029357733` is shared as `spotify`, never
with its merchant text, reference or amount.