Files
FiscusPublic/crates/fiscus-ledger/src/state.rs
T

860 lines
35 KiB
Rust

//! State = `apply()` folded over the log. Deterministic: every collection is ordered, nothing depends on a
//! clock or a hash seed, and `apply()` is total (an event that does not fit is recorded as rejected).
use crate::categories;
use crate::date::Date;
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
use crate::import::StatementLine;
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
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};
const MAX_TEXT: usize = 500;
/// Where a payment record came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Origin {
Captured,
Imported,
Added,
}
/// What the app shows next to a payment: ○ captured, ● on a statement, ◆ added by hand.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Glyph {
Captured,
Confirmed,
Hand,
}
impl Glyph {
pub fn symbol(self) -> char {
match self {
Glyph::Captured => '○',
Glyph::Confirmed => '●',
Glyph::Hand => '◆',
}
}
}
/// A value and the position in the log that set it: the later one wins.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Stamped<T> {
pub seq: u64,
pub value: T,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaymentRecord {
pub id: PaymentId,
pub origin: Origin,
pub seq: u64,
pub amount: Haler,
pub date: Date,
pub merchant: String,
pub merchant_key: String,
pub card: Option<String>,
pub note: Option<String>,
pub line: Option<StatementLine>,
pub category: Option<Stamped<Category>>,
pub budget: Option<Stamped<BudgetId>>,
pub trial_ends: Option<Stamped<Date>>,
/// The other half of a confirmed pair.
pub partner: Option<PaymentId>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Budget {
pub id: BudgetId,
pub name: String,
pub limit: Haler,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rule {
pub id: RuleId,
pub category: Category,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DecisionRecord {
pub decision: Decision,
pub amount: Haler,
pub on: Date,
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>,
}
/// An issued invoice, its totals, and what became of it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvoiceRecord {
pub invoice: Invoice,
/// The supplier as it was when the invoice was issued.
pub supplier: Supplier,
pub totals: Totals,
pub paid: Option<Paid>,
pub cancelled: bool,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Paid {
/// The statement line that paid it; `None` when marked paid by hand.
pub payment: Option<PaymentId>,
pub on: Date,
/// Set aside for tax: the VAT, and the reserve share of the rest.
pub reserve: Haler,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Withdrawal {
pub id: String,
pub amount: Haler,
pub on: Date,
pub note: String,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rejection {
pub event: EventId,
pub seq: u64,
pub reason: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct State {
/// Events seen, accepted or not.
pub seq: u64,
pub events: BTreeSet<EventId>,
pub payments: BTreeMap<PaymentId, PaymentRecord>,
pub line_keys: BTreeMap<String, PaymentId>,
pub budgets: BTreeMap<BudgetId, Budget>,
/// The first budget created (never a shared one): where a payment goes when nobody assigned it.
pub default_budget: Option<BudgetId>,
/// Merchant key → the latest rule for it.
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>,
/// 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 supplier: Option<Supplier>,
pub invoices: BTreeMap<InvoiceId, InvoiceRecord>,
/// Invoice number → invoice.
pub invoice_numbers: BTreeMap<String, InvoiceId>,
/// A statement line → the invoice it paid.
pub invoice_payments: BTreeMap<PaymentId, InvoiceId>,
pub withdrawals: Vec<Withdrawal>,
pub rejected: Vec<Rejection>,
}
/// Why a category is what it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CategorySource {
Explicit,
Rule,
None,
}
/// One payment as the user sees it: a confirmed pair is one payment.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EffectivePayment {
/// The captured or hand-added id when there is one (so a row keeps its id when confirmed), else the line's.
pub id: PaymentId,
pub captured: Option<PaymentId>,
pub line: Option<PaymentId>,
pub glyph: Glyph,
pub origin: Origin,
pub seq: u64,
pub amount: Haler,
pub date: Date,
pub merchant: String,
pub merchant_key: String,
pub card: Option<String>,
pub note: Option<String>,
pub counterparty: Option<String>,
pub variable_symbol: Option<String>,
pub message: Option<String>,
pub category: Option<Category>,
pub category_source: CategorySource,
pub budget: Option<BudgetId>,
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())
}
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) {
(Some(x), Some(y)) => Some(if x.seq >= y.seq { x.value.clone() } else { y.value.clone() }),
(Some(x), None) => Some(x.value.clone()),
(None, Some(y)) => Some(y.value.clone()),
(None, None) => None,
}
}
impl State {
pub fn replay<'a, I: IntoIterator<Item = &'a Event>>(log: I) -> State {
let mut s = State::default();
for e in log {
s.apply(e);
}
s
}
/// Applies one event. Never panics; an event that does not fit is recorded in `rejected`.
pub fn apply(&mut self, e: &Event) {
self.seq += 1;
let seq = self.seq;
if !self.events.insert(e.id.clone()) {
self.reject(e, "the same event twice");
return;
}
if let Err(reason) = self.try_apply(&e.body, seq) {
self.reject(e, reason);
}
}
fn reject(&mut self, e: &Event, reason: &str) {
self.rejected.push(Rejection { event: e.id.clone(), seq: self.seq, reason: reason.into() });
}
fn new_payment(&self, id: &PaymentId, amount: Haler) -> Result<(), &'static str> {
if id.is_empty() || id.len() > 100 {
return Err("a payment id must be 1-100 characters");
}
if self.payments.contains_key(id) {
return Err("a payment with this id exists");
}
if amount == Haler::ZERO {
return Err("a payment of zero");
}
Ok(())
}
fn payment_mut(&mut self, id: &PaymentId) -> Result<&mut PaymentRecord, &'static str> {
self.payments.get_mut(id).ok_or("no such payment")
}
fn try_apply(&mut self, body: &EventBody, seq: u64) -> Result<(), &'static str> {
match body {
EventBody::PaymentCaptured { payment, amount, date, merchant, card } => {
self.new_payment(payment, *amount)?;
if !text_ok(merchant) || !opt_text_ok(card) {
return Err("a text field is too long or has control characters");
}
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin: Origin::Captured,
seq,
amount: *amount,
date: *date,
merchant: merchant.clone(),
merchant_key: merchant_key(merchant),
card: card.clone(),
note: None,
line: None,
category: None,
budget: None,
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentImported { payment, line, line_key } => {
// A zero line (a card check) is still a line: allowed, unlike a zero capture.
self.new_payment(payment, Haler(1))?;
if line_key.is_empty() || self.line_keys.contains_key(line_key) {
return Err("this statement line was imported before");
}
if !line.is_clean() {
return Err("a text field is too long or has control characters");
}
self.line_keys.insert(line_key.clone(), payment.clone());
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin: Origin::Imported,
seq,
amount: line.amount,
date: line.booked,
merchant: line.merchant.clone(),
merchant_key: merchant_key(&line.merchant),
card: None,
note: None,
line: Some(line.clone()),
category: None,
budget: None,
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentAdded { payment, amount, date, merchant, category, note } => {
self.new_payment(payment, *amount)?;
if !text_ok(merchant) || !opt_text_ok(note) {
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");
}
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin: Origin::Added,
seq,
amount: *amount,
date: *date,
merchant: merchant.clone(),
merchant_key: merchant_key(merchant),
card: None,
note: note.clone(),
line: None,
category: category.clone().map(|value| Stamped { seq, value }),
budget: None,
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentConfirmed { payment, line } => {
let p = self.payments.get(payment).ok_or("no such payment")?;
let l = self.payments.get(line).ok_or("no such statement line")?;
if p.origin == Origin::Imported || l.origin != Origin::Imported {
return Err("a confirmation ties a captured or hand-added payment to a statement line");
}
if p.partner.is_some() || l.partner.is_some() {
return Err("already confirmed");
}
if p.amount != l.amount {
return Err("the amounts differ");
}
self.payment_mut(payment)?.partner = Some(line.clone());
self.payment_mut(line)?.partner = Some(payment.clone());
}
EventBody::PaymentCategorised { payment, category } => {
if !categories::is_valid(category) {
return Err("not a category id");
}
self.payment_mut(payment)?.category = Some(Stamped { seq, value: category.clone() });
}
EventBody::PaymentAssigned { payment, budget } => {
if !self.budgets.contains_key(budget) {
return Err("no such budget");
}
self.payment_mut(payment)?.budget = Some(Stamped { seq, value: budget.clone() });
}
EventBody::PaymentTrialMarked { payment, ends } => {
self.payment_mut(payment)?.trial_ends = Some(Stamped { seq, value: *ends });
}
EventBody::BudgetCreated { budget, name, limit } | EventBody::BudgetShared { budget, name, limit } => {
if budget.is_empty() || self.budgets.contains_key(budget) {
return Err("a budget with this id exists");
}
let name = name.trim();
if name.is_empty() || name.chars().count() > 60 || !text_ok(name) {
return Err("a budget name must be 1-60 characters");
}
if limit.0 < 0 {
return Err("a limit cannot be negative");
}
self.budgets.insert(budget.clone(), Budget { id: budget.clone(), name: name.into(), limit: *limit, seq });
if self.default_budget.is_none() && matches!(body, EventBody::BudgetCreated { .. }) {
self.default_budget = Some(budget.clone());
}
}
EventBody::BudgetLimitSet { budget, limit } => {
if limit.0 < 0 {
return Err("a limit cannot be negative");
}
self.budgets.get_mut(budget).ok_or("no such budget")?.limit = *limit;
}
EventBody::RuleCreated { rule, merchant_key: key, category } => {
if key.is_empty() || merchant_key(key) != *key {
return Err("not a merchant key");
}
if !categories::is_valid(category) {
return Err("not a category id");
}
self.rules.insert(key.clone(), Rule { id: rule.clone(), category: category.clone(), seq });
}
EventBody::SubscriptionDecided { subscription, decision, amount, on } => {
if subscription.is_empty() || !text_ok(subscription) {
return Err("not a subscription key");
}
if amount.0 < 0 {
return Err("a subscription's amount is a cost, not negative");
}
self.decisions
.entry(subscription.clone())
.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() });
}
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::SupplierSet { supplier } => {
supplier.check().map_err(|_| "not a valid supplier")?;
self.supplier = Some(supplier.clone());
}
EventBody::InvoiceIssued { invoice } => {
let supplier = self.supplier.clone().ok_or("set the supplier before issuing an invoice")?;
if !id_ok(&invoice.id) || self.invoices.contains_key(&invoice.id) {
return Err("an invoice with this id exists");
}
if self.invoice_numbers.contains_key(&invoice.number) {
return Err("an invoice with this number exists");
}
if invoice.budget.as_ref().is_some_and(|b| !self.budgets.contains_key(b)) {
return Err("no such budget");
}
let totals = invoice.check(&supplier).map_err(|_| "not a valid invoice")?;
self.invoice_numbers.insert(invoice.number.clone(), invoice.id.clone());
self.invoices.insert(invoice.id.clone(), InvoiceRecord { invoice: invoice.clone(), supplier, totals, paid: None, cancelled: false, seq });
}
EventBody::InvoicePaid { invoice, payment, on } => {
let rec = self.invoices.get(invoice).ok_or("no such invoice")?;
if rec.cancelled || rec.paid.is_some() {
return Err("the invoice is cancelled or paid already");
}
if *on < rec.invoice.issued {
return Err("paid before it was issued");
}
if let Some(p) = payment {
if self.invoice_payments.contains_key(p) {
return Err("this payment paid another invoice");
}
let e = self.effective_payment(p).ok_or("no such payment")?;
if e.line.is_none() || e.amount != rec.totals.total {
return Err("the payment is not a statement line of the invoice's amount");
}
}
let reserve = rec.supplier.reserve_for(&rec.totals);
if let Some(p) = payment {
self.invoice_payments.insert(p.clone(), invoice.clone());
}
let rec = self.invoices.get_mut(invoice).ok_or("no such invoice")?;
rec.paid = Some(Paid { payment: payment.clone(), on: *on, reserve, seq });
}
EventBody::InvoiceCancelled { invoice } => {
let rec = self.invoices.get_mut(invoice).ok_or("no such invoice")?;
if rec.paid.is_some() || rec.cancelled {
return Err("only an unpaid invoice can be cancelled");
}
rec.cancelled = true;
}
EventBody::ReserveWithdrawn { withdrawal, amount, on, note } => {
if !id_ok(withdrawal) || self.withdrawals.iter().any(|w| &w.id == withdrawal) {
return Err("a withdrawal with this id exists");
}
if amount.0 <= 0 || *amount > self.reserve_balance() {
return Err("more than the reserve holds");
}
if note.chars().count() > 200 || !text_ok(note) {
return Err("a note is at most 200 characters");
}
self.withdrawals.push(Withdrawal { id: withdrawal.clone(), amount: *amount, on: *on, note: note.clone(), seq });
}
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(())
}
/// What the tax reserve holds: everything set aside for paid invoices, less what was taken out.
pub fn reserve_balance(&self) -> Haler {
let set: i64 = self.invoices.values().filter_map(|r| r.paid.as_ref()).map(|p| p.reserve.0).fold(0, i64::saturating_add);
let out: i64 = self.withdrawals.iter().map(|w| w.amount.0).fold(0, i64::saturating_add);
Haler(set.saturating_sub(out))
}
/// The number the next invoice issued in `year` gets.
pub fn next_invoice_number(&self, year: i32) -> Option<String> {
let prefix = year.to_string();
let last = self.invoice_numbers.keys().filter(|n| n.starts_with(&prefix)).filter_map(|n| n[4..].parse::<u32>().ok()).max().unwrap_or(0);
crate::invoice::invoice_number(year, last + 1).ok()
}
/// QR Platba for an unpaid invoice: its total, its number as the variable symbol, to the account set.
pub fn invoice_spayd(&self, invoice: &str) -> Option<String> {
let r = self.invoices.get(invoice)?;
if r.paid.is_some() || r.cancelled {
return None;
}
let a = self.account.as_ref()?;
let iban = Iban::parse(&a.iban).ok()?;
spayd(&iban, r.totals.total, Some(&a.name), &format!("Faktura {}", r.invoice.number), Some(&r.invoice.number)).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
.payments
.values()
.filter(|p| !(p.origin == Origin::Imported && p.partner.is_some()))
.map(|p| self.effective(p))
.collect();
out.sort_by(|a, b| a.date.cmp(&b.date).then(a.seq.cmp(&b.seq)));
out
}
/// The effective payment that contains `id` (either half of a pair).
pub fn effective_payment(&self, id: &str) -> Option<EffectivePayment> {
let p = self.payments.get(id)?;
let primary = match (&p.origin, &p.partner) {
(Origin::Imported, Some(partner)) => self.payments.get(partner)?,
_ => p,
};
Some(self.effective(primary))
}
fn effective(&self, p: &PaymentRecord) -> EffectivePayment {
let partner = p.partner.as_ref().and_then(|id| self.payments.get(id));
let line_rec = if p.origin == Origin::Imported { Some(p) } else { partner };
let line = line_rec.and_then(|r| r.line.as_ref());
let merchant = match line {
Some(l) if !l.merchant.trim().is_empty() => l.merchant.clone(),
_ => p.merchant.clone(),
};
let key = merchant_key(&merchant);
let explicit = latest(&p.category, partner.map(|q| &q.category));
let (category, category_source) = match explicit {
Some(c) => (Some(c), CategorySource::Explicit),
None => match self.rules.get(&key) {
Some(r) => (Some(r.category.clone()), CategorySource::Rule),
None => (None, CategorySource::None),
},
};
let budget = latest(&p.budget, partner.map(|q| &q.budget)).or_else(|| self.default_budget.clone());
EffectivePayment {
id: p.id.clone(),
captured: if p.origin == Origin::Imported { None } else { Some(p.id.clone()) },
line: line_rec.map(|r| r.id.clone()),
glyph: match (line_rec.is_some(), p.origin) {
(true, _) => Glyph::Confirmed,
(false, Origin::Added) => Glyph::Hand,
(false, _) => Glyph::Captured,
},
origin: p.origin,
seq: p.seq,
amount: line_rec.map(|r| r.amount).unwrap_or(p.amount),
date: line_rec.map(|r| r.date).unwrap_or(p.date),
merchant,
merchant_key: key,
card: p.card.clone(),
note: p.note.clone(),
counterparty: line.and_then(|l| l.counterparty.clone()),
variable_symbol: line.and_then(|l| l.variable_symbol.clone()),
message: line.and_then(|l| l.message.clone()),
category,
category_source,
budget,
trial_ends: latest(&p.trial_ends, partner.map(|q| &q.trial_ends)),
}
}
}