[ledger] Sharing: payment.shared/unshared, splits that always add up, share links, capture tokens, account; QR Platba with checked IBAN

This commit is contained in:
2026-11-03 23:27:26 +01:00
parent b4474f288e
commit 241c924d26
6 changed files with 511 additions and 4 deletions
+51
View File
@@ -3,6 +3,8 @@
use crate::date::{Date, Timestamp};
use crate::import::StatementLine;
use crate::money::Haler;
use crate::split::Share;
use crate::state::Glyph;
use serde::{Deserialize, Serialize};
/// Ids are opaque strings the app generates (random, unguessable); the core never makes one up.
@@ -10,6 +12,7 @@ pub type EventId = String;
pub type PaymentId = String;
pub type BudgetId = String;
pub type RuleId = String;
pub type SplitId = String;
/// A category id, e.g. `groceries` (see [`crate::categories`]).
pub type Category = String;
@@ -35,6 +38,24 @@ pub enum Decision {
Cancel,
}
/// How a share of a split was settled.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Settlement {
/// Paid by QR Platba.
Qr,
/// Marked paid by hand (cash, another way).
Marked,
}
/// Which phone a capture token is for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CaptureKind {
Iphone,
Android,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum EventBody {
@@ -73,4 +94,34 @@ pub enum EventBody {
/// Keep or cancel a subscription (by its key), seen at `amount` (a positive cost) on `on`.
#[serde(rename = "subscription.decided")]
SubscriptionDecided { subscription: String, decision: Decision, amount: Haler, on: Date },
/// A shared budget's log: a member put this payment (as they see it) into the budget.
#[serde(rename = "payment.shared")]
PaymentShared {
payment: PaymentId,
budget: BudgetId,
amount: Haler,
date: Date,
merchant: String,
category: Option<Category>,
glyph: Glyph,
},
/// A shared budget's log: the payment is taken out of the budget again.
#[serde(rename = "payment.unshared")]
PaymentUnshared { payment: PaymentId, budget: BudgetId },
/// The payment's amount, split among people (see [`crate::split::split_equal`]).
#[serde(rename = "split.created")]
SplitCreated { split: SplitId, payment: PaymentId, payer: String, shares: Vec<Share> },
#[serde(rename = "split.settled")]
SplitSettled { split: SplitId, person: String, how: Settlement },
/// A phone's capture token: only its SHA-256 in lowercase hex. The token itself lives in Custos.
#[serde(rename = "capture.token_added")]
CaptureTokenAdded { token: String, name: String, kind: CaptureKind },
#[serde(rename = "capture.token_revoked")]
CaptureTokenRevoked { token: String },
/// A share link for one person of a split: only the SHA-256 of the link's token, in lowercase hex.
#[serde(rename = "share.link_created")]
ShareLinkCreated { link: String, split: SplitId, person: String, expires: Date },
/// The account people pay back to by QR Platba.
#[serde(rename = "account.set")]
AccountSet { iban: String, name: String },
}
+7 -3
View File
@@ -1,5 +1,6 @@
//! Fiscus Domi's ledger: money in haléře, civil dates, the append-only event log and the state derived from
//! it, merchant keys and rules, and capture ↔ statement matching. Pure: no I/O, no clock, no randomness.
//! it, merchant keys and rules, capture ↔ statement matching, splits and QR Platba. Pure: no I/O, no clock, no
//! randomness.
pub mod categories;
pub mod date;
@@ -8,9 +9,12 @@ pub mod import;
pub mod matching;
pub mod merchant;
pub mod money;
pub mod pay;
pub mod share;
pub mod split;
pub mod state;
pub use date::{Date, Timestamp};
pub use event::{BudgetId, Category, Decision, Event, EventBody, EventId, PaymentId};
pub use event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, Settlement, SplitId};
pub use money::Haler;
pub use state::{EffectivePayment, Glyph, Origin, State};
pub use state::{EffectivePayment, Glyph, Origin, ShareView, State};
+148
View File
@@ -0,0 +1,148 @@
//! QR Platba: a checked Czech IBAN and the SPAYD 1.0 string a banking app scans.
use crate::money::Haler;
use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum PayError {
#[error("not a valid Czech account number or IBAN")]
Account,
#[error("the amount must be between 0,01 and 9 999 999,99 CZK")]
Amount,
#[error("a variable symbol is 1-10 digits")]
VariableSymbol,
#[error("a text has control characters")]
Text,
}
/// A Czech IBAN (`CZ` + 22 digits) whose check digits are right.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Iban(String);
/// The largest amount QR Platba carries: 9 999 999,99 CZK.
pub const MAX_AMOUNT: Haler = Haler(999_999_999);
/// The remainder mod 97 of a string of digits and letters (A = 10 … Z = 35), as IBAN check digits use.
fn mod97(s: &str) -> Option<u32> {
let mut r: u32 = 0;
for c in s.chars() {
let v = c.to_digit(36)?;
r = if v < 10 { (r * 10 + v) % 97 } else { (r * 100 + v) % 97 };
}
Some(r)
}
/// The Czech weighted mod-11 check of an account prefix or number, right-aligned to the weights.
fn mod11(digits: &str, weights: &[u32]) -> bool {
if digits.len() > weights.len() {
return false;
}
let pad = weights.len() - digits.len();
let sum: u32 = digits.bytes().enumerate().map(|(i, b)| u32::from(b - b'0') * weights[pad + i]).sum();
sum.is_multiple_of(11)
}
const PREFIX_WEIGHTS: [u32; 6] = [10, 5, 8, 4, 2, 1];
const NUMBER_WEIGHTS: [u32; 10] = [6, 3, 7, 9, 10, 5, 8, 4, 2, 1];
fn all_digits(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}
impl Iban {
/// `CZ65 0800 0000 1920 0014 5399` (spaces and case do not matter) or a Czech account
/// `[prefix-]number/bank` such as `19-2000145399/0800`.
pub fn parse(text: &str) -> Result<Iban, PayError> {
let t = text.trim();
if let Some((account, bank)) = t.split_once('/') {
return Iban::from_czech(account.trim(), bank.trim());
}
let compact: String = t.chars().filter(|c| *c != ' ').collect::<String>().to_ascii_uppercase();
if compact.len() != 24 || !compact.starts_with("CZ") || !all_digits(&compact[2..]) {
return Err(PayError::Account);
}
let rearranged = format!("{}{}", &compact[4..], &compact[..4]);
if mod97(&rearranged) != Some(1) {
return Err(PayError::Account);
}
// The BBAN inside must itself be a valid Czech account.
let (prefix, number) = (&compact[8..14], &compact[14..]);
if !mod11(prefix, &PREFIX_WEIGHTS) || !mod11(number, &NUMBER_WEIGHTS) {
return Err(PayError::Account);
}
Ok(Iban(compact))
}
fn from_czech(account: &str, bank: &str) -> Result<Iban, PayError> {
let (prefix, number) = account.split_once('-').unwrap_or(("", account));
let ok = (prefix.is_empty() || (all_digits(prefix) && prefix.len() <= 6))
&& all_digits(number)
&& (2..=10).contains(&number.len())
&& bank.len() == 4
&& all_digits(bank)
&& mod11(prefix, &PREFIX_WEIGHTS)
&& mod11(number, &NUMBER_WEIGHTS);
if !ok {
return Err(PayError::Account);
}
let bban = format!("{bank}{prefix:0>6}{number:0>10}");
let check = 98 - mod97(&format!("{bban}CZ00")).ok_or(PayError::Account)?;
Iban::parse(&format!("CZ{check:02}{bban}"))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for Iban {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
/// A SPAYD text value: `*` written as `%2A`, cut to `max` characters without splitting an escape.
fn text(value: &str, max: usize) -> Result<String, PayError> {
if value.chars().any(|c| c.is_control()) {
return Err(PayError::Text);
}
let mut out = String::new();
let mut count = 0;
for c in value.trim().chars() {
let piece = if c == '*' { "%2A".to_string() } else { c.to_string() };
let n = piece.chars().count();
if count + n > max {
break;
}
out.push_str(&piece);
count += n;
}
Ok(out)
}
/// `SPD*1.0*ACC:<IBAN>*AM:<amount>*CC:CZK[*RN:<name>]*MSG:<message>[*X-VS:<vs>]`.
/// The amount is positive and written from haléře (`450.00`); the name is cut to 35 characters and the
/// message to 60.
pub fn spayd(iban: &Iban, amount: Haler, name: Option<&str>, message: &str, vs: Option<&str>) -> Result<String, PayError> {
if amount.0 <= 0 || amount > MAX_AMOUNT {
return Err(PayError::Amount);
}
let mut s = format!("SPD*1.0*ACC:{}*AM:{}.{:02}*CC:CZK", iban.0, amount.0 / 100, amount.0 % 100);
if let Some(name) = name {
let rn = text(name, 35)?;
if !rn.is_empty() {
s.push_str(&format!("*RN:{rn}"));
}
}
let msg = text(message, 60)?;
if !msg.is_empty() {
s.push_str(&format!("*MSG:{msg}"));
}
if let Some(vs) = vs {
if !all_digits(vs) || vs.len() > 10 {
return Err(PayError::VariableSymbol);
}
s.push_str(&format!("*X-VS:{vs}"));
}
Ok(s)
}
+22
View File
@@ -0,0 +1,22 @@
//! What a shared budget may receive from a personal log: one payment, as its owner sees it, and only once it
//! is assigned to that budget. Its card, note, statement details, rules and origin events stay home.
use crate::event::EventBody;
use crate::state::State;
/// `payment.shared` for `payment` into `budget`, or `None` if that payment is not in that budget.
pub fn shared_payment(state: &State, payment: &str, budget: &str) -> Option<EventBody> {
let p = state.effective_payment(payment)?;
if p.budget.as_deref() != Some(budget) {
return None;
}
Some(EventBody::PaymentShared {
payment: p.id,
budget: budget.into(),
amount: p.amount,
date: p.date,
merchant: p.merchant,
category: p.category,
glyph: p.glyph,
})
}
+34
View File
@@ -0,0 +1,34 @@
//! 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())
}
+249 -1
View File
@@ -3,10 +3,12 @@
use crate::categories;
use crate::date::Date;
use crate::event::{BudgetId, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId};
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
use crate::import::StatementLine;
use crate::merchant::merchant_key;
use crate::money::Haler;
use crate::pay::{spayd, Iban};
use crate::split::Share;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
@@ -89,6 +91,57 @@ pub struct DecisionRecord {
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Settled {
pub how: Settlement,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Split {
pub id: SplitId,
pub payment: PaymentId,
pub payer: String,
pub shares: Vec<Share>,
/// Person → how they settled. The payer never appears here.
pub settled: BTreeMap<String, Settled>,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CaptureToken {
pub name: String,
pub kind: CaptureKind,
pub revoked: bool,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareLink {
pub split: SplitId,
pub person: String,
pub expires: Date,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Account {
pub iban: String,
pub name: String,
}
/// Everything a share-link page shows: one person's share of one payment, and how to pay it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareView {
pub name: String,
/// What they owe, positive.
pub amount: Haler,
pub merchant: String,
pub date: Date,
/// QR Platba, when an account is set.
pub spayd: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rejection {
pub event: EventId,
@@ -110,6 +163,14 @@ pub struct State {
pub rules: BTreeMap<String, Rule>,
/// Subscription key → its decisions, oldest first.
pub decisions: BTreeMap<String, Vec<DecisionRecord>>,
/// Payments that came into this log by `payment.shared` (a shared budget's log).
pub shared: BTreeSet<PaymentId>,
pub splits: BTreeMap<SplitId, Split>,
/// SHA-256 (hex) of a phone's capture token → the token's record.
pub capture_tokens: BTreeMap<String, CaptureToken>,
/// SHA-256 (hex) of a share link's token → the link.
pub share_links: BTreeMap<String, ShareLink>,
pub account: Option<Account>,
pub rejected: Vec<Rejection>,
}
@@ -155,6 +216,19 @@ fn opt_text_ok(s: &Option<String>) -> bool {
s.as_deref().is_none_or(text_ok)
}
fn name_ok(s: &str, max: usize) -> bool {
!s.trim().is_empty() && s.chars().count() <= max && text_ok(s)
}
fn id_ok(s: &str) -> bool {
!s.is_empty() && s.len() <= 100 && text_ok(s)
}
/// A SHA-256 in lowercase hex.
fn hash_ok(s: &str) -> bool {
s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
fn latest<T: Clone>(a: &Option<Stamped<T>>, b: Option<&Option<Stamped<T>>>) -> Option<T> {
let b = b.and_then(|b| b.as_ref());
match (a.as_ref(), b) {
@@ -366,10 +440,184 @@ impl State {
.or_default()
.push(DecisionRecord { decision: *decision, amount: *amount, on: *on, seq });
}
EventBody::PaymentShared { payment, budget, amount, date, merchant, category, glyph } => {
if !self.budgets.contains_key(budget) {
return Err("no such budget");
}
if self.payments.contains_key(payment) && !self.shared.contains(payment) {
return Err("a payment with this id exists");
}
if !id_ok(payment) || *amount == Haler::ZERO {
return Err("a payment needs an id and an amount");
}
if !text_ok(merchant) {
return Err("a text field is too long or has control characters");
}
if category.as_deref().is_some_and(|c| !categories::is_valid(c)) {
return Err("not a category id");
}
let origin = match glyph {
Glyph::Captured => Origin::Captured,
Glyph::Confirmed => Origin::Imported,
Glyph::Hand => Origin::Added,
};
self.shared.insert(payment.clone());
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin,
seq,
amount: *amount,
date: *date,
merchant: merchant.clone(),
merchant_key: merchant_key(merchant),
card: None,
note: None,
line: None,
category: category.clone().map(|value| Stamped { seq, value }),
budget: Some(Stamped { seq, value: budget.clone() }),
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentUnshared { payment, budget } => {
if !self.shared.contains(payment) {
return Err("this payment was not shared here");
}
if self.payments.get(payment).and_then(|p| p.budget.as_ref()).map(|b| &b.value) != Some(budget) {
return Err("this payment is not in that budget");
}
if self.splits.values().any(|sp| sp.payment == *payment) {
return Err("this payment is split; it stays shared");
}
self.shared.remove(payment);
self.payments.remove(payment);
}
EventBody::SplitCreated { split, payment, payer, shares } => {
if !id_ok(split) || self.splits.contains_key(split) {
return Err("a split needs a new id");
}
let total = self.effective_payment(payment).ok_or("no such payment")?.amount;
if !total.is_outflow() {
return Err("only a payment out can be split");
}
if shares.is_empty() || shares.len() > 50 {
return Err("a split is among 1-50 people");
}
let people: BTreeSet<&str> = shares.iter().map(|s| s.person.as_str()).collect();
if people.len() != shares.len() {
return Err("a person appears twice in the split");
}
if shares.iter().any(|s| !id_ok(&s.person) || !name_ok(&s.name, 60)) {
return Err("every share needs a person and a name");
}
if !people.contains(payer.as_str()) {
return Err("the payer must be one of the people");
}
if shares.iter().any(|s| s.amount.0 > 0) {
return Err("a share has the wrong sign");
}
if Haler::sum(shares.iter().map(|s| s.amount)) != Ok(total) {
return Err("the shares do not add up to the payment");
}
self.splits.insert(
split.clone(),
Split {
id: split.clone(),
payment: payment.clone(),
payer: payer.clone(),
shares: shares.clone(),
settled: BTreeMap::new(),
seq,
},
);
}
EventBody::SplitSettled { split, person, how } => {
let sp = self.splits.get_mut(split).ok_or("no such split")?;
if !sp.shares.iter().any(|s| s.person == *person) {
return Err("this person is not in the split");
}
if sp.payer == *person {
return Err("the payer owes nothing");
}
if sp.settled.contains_key(person) {
return Err("already settled");
}
sp.settled.insert(person.clone(), Settled { how: *how, seq });
}
EventBody::CaptureTokenAdded { token, name, kind } => {
if !hash_ok(token) {
return Err("a capture token is stored only as its SHA-256");
}
if self.capture_tokens.contains_key(token) {
return Err("this capture token exists");
}
if !name_ok(name, 60) {
return Err("a phone's name must be 1-60 characters");
}
self.capture_tokens.insert(token.clone(), CaptureToken { name: name.trim().into(), kind: *kind, revoked: false, seq });
}
EventBody::CaptureTokenRevoked { token } => {
let t = self.capture_tokens.get_mut(token).ok_or("no such capture token")?;
if t.revoked {
return Err("already revoked");
}
t.revoked = true;
}
EventBody::ShareLinkCreated { link, split, person, expires } => {
if !hash_ok(link) {
return Err("a share link is stored only as its SHA-256");
}
if self.share_links.contains_key(link) {
return Err("this share link exists");
}
let sp = self.splits.get(split).ok_or("no such split")?;
if sp.payer == *person || !sp.shares.iter().any(|s| s.person == *person) {
return Err("a share link is for someone who owes a share");
}
self.share_links.insert(link.clone(), ShareLink { split: split.clone(), person: person.clone(), expires: *expires, seq });
}
EventBody::AccountSet { iban, name } => {
let iban = Iban::parse(iban).map_err(|_| "not a valid Czech account")?;
if !name_ok(name, 70) {
return Err("an account name must be 1-70 characters");
}
self.account = Some(Account { iban: iban.as_str().into(), name: name.trim().into() });
}
}
Ok(())
}
/// Whether a phone's capture token (its SHA-256 in hex) may post captures.
pub fn capture_token_active(&self, token: &str) -> bool {
self.capture_tokens.get(token).is_some_and(|t| !t.revoked)
}
/// The page behind a share link (its token's SHA-256 in hex): one person's open share, or `None` for an
/// unknown, expired (after `expires`) or settled link.
pub fn share_view(&self, link: &str, today: Date) -> Option<ShareView> {
let l = self.share_links.get(link)?;
if today > l.expires {
return None;
}
let sp = self.splits.get(&l.split)?;
if sp.settled.contains_key(&l.person) {
return None;
}
let share = sp.shares.iter().find(|s| s.person == l.person)?;
let p = self.effective_payment(&sp.payment)?;
let amount = share.amount.checked_neg().ok()?;
let (y, m, d) = p.date.ymd();
let message = format!("{} {d}.{m}.{y}", p.merchant.trim());
let spayd = self.account.as_ref().and_then(|a| {
let iban = Iban::parse(&a.iban).ok()?;
spayd(&iban, amount, Some(&a.name), &message, None).ok()
});
Some(ShareView { name: share.name.clone(), amount, merchant: p.merchant, date: p.date, spayd })
}
/// Every payment as the user sees it, a confirmed pair as one, in date order (then log order).
pub fn effective_payments(&self) -> Vec<EffectivePayment> {
let mut out: Vec<EffectivePayment> = self