[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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user