Compare commits
14 Commits
feature/core
...
v0.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 95a8a8965b | |||
| 0068d4b69a | |||
| deb31374ea | |||
| 235f290412 | |||
| 11a4070151 | |||
| 64917a9a89 | |||
| f21aef9859 | |||
| 101073f853 | |||
| 701f15840a | |||
| 2e07d37e86 | |||
| 241c924d26 | |||
| b4474f288e | |||
| 8e085bafc3 | |||
| 2bda5dbbec |
Generated
+14
-3
@@ -137,9 +137,20 @@ version = "2.5.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fiscus-capture"
|
||||||
|
version = "0.4.0"
|
||||||
|
dependencies = [
|
||||||
|
"fiscus-ledger",
|
||||||
|
"proptest",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"thiserror",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fiscus-insight"
|
name = "fiscus-insight"
|
||||||
version = "0.1.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"fiscus-ledger",
|
"fiscus-ledger",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -148,7 +159,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fiscus-ledger"
|
name = "fiscus-ledger"
|
||||||
version = "0.1.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proptest",
|
"proptest",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -158,7 +169,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fiscus-statement"
|
name = "fiscus-statement"
|
||||||
version = "0.1.0"
|
version = "0.4.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"encoding_rs",
|
"encoding_rs",
|
||||||
"fiscus-ledger",
|
"fiscus-ledger",
|
||||||
|
|||||||
+2
-2
@@ -1,9 +1,9 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight"]
|
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.0"
|
version = "0.4.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
|
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
name = "fiscus-capture"
|
||||||
|
description = "Fiscus Domi: what the phones send (the iPhone Shortcut post, Android bank notifications), parsed strictly"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
fiscus-ledger = { path = "../fiscus-ledger" }
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json = { workspace = true, features = ["raw_value"] }
|
||||||
|
thiserror.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
proptest.workspace = true
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
//! An amount as a phone writes it: `129`, `129,50`, `1 234,50 Kč`, `CZK 129.00`. Read from its text with
|
||||||
|
//! `Haler::parse_czk`, never through a float.
|
||||||
|
|
||||||
|
use fiscus_ledger::Haler;
|
||||||
|
|
||||||
|
/// The largest single card payment Fiscus believes: 10 000 000 CZK.
|
||||||
|
pub const MAX: Haler = Haler(1_000_000_000);
|
||||||
|
|
||||||
|
/// A positive amount in CZK, with an optional `Kč` or `CZK` before or after it. A no-break space (U+00A0) or
|
||||||
|
/// narrow no-break space (U+202F) between thousands counts as a space.
|
||||||
|
pub fn parse_positive(text: &str) -> Option<Haler> {
|
||||||
|
let t: String = text.chars().map(|c| if c == '\u{a0}' || c == '\u{202f}' { ' ' } else { c }).collect();
|
||||||
|
let mut t = t.trim();
|
||||||
|
for unit in ["Kč", "CZK"] {
|
||||||
|
if let Some(rest) = t.strip_suffix(unit) {
|
||||||
|
t = rest.trim_end();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some(rest) = t.strip_prefix(unit) {
|
||||||
|
t = rest.trim_start();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let h = Haler::parse_czk(t).ok()?;
|
||||||
|
(h.0 > 0 && h <= MAX).then_some(h)
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
//! Fiscus Domi's capture: what the phones send, parsed strictly. Both are hostile input: a post or a
|
||||||
|
//! notification becomes one [`Capture`] or nothing, never a partial payment. Pure: times are parameters.
|
||||||
|
|
||||||
|
pub mod amount;
|
||||||
|
pub mod notification;
|
||||||
|
pub mod shortcut;
|
||||||
|
|
||||||
|
use fiscus_ledger::{Date, Haler, Timestamp};
|
||||||
|
|
||||||
|
/// One card payment a phone saw: an outflow, so `amount` is negative.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Capture {
|
||||||
|
pub amount: Haler,
|
||||||
|
pub date: Date,
|
||||||
|
pub at: Timestamp,
|
||||||
|
pub merchant: String,
|
||||||
|
pub card: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 1–200 characters, no control characters.
|
||||||
|
pub(crate) fn merchant_ok(s: &str) -> bool {
|
||||||
|
!s.trim().is_empty() && s.chars().count() <= 200 && !s.chars().any(|c| c.is_control())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 0–60 characters, no control characters.
|
||||||
|
pub(crate) fn card_ok(s: &str) -> bool {
|
||||||
|
s.chars().count() <= 60 && !s.chars().any(|c| c.is_control())
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
//! Android bank notifications. A notification is read only if it comes from a bank app the person selected,
|
||||||
|
//! and becomes a payment only if a template **written from real samples** matches it exactly. Anything else
|
||||||
|
//! is `Unknown`: counted by the app, never guessed.
|
||||||
|
|
||||||
|
use crate::{amount, card_ok, merchant_ok, Capture};
|
||||||
|
use fiscus_ledger::{Date, Timestamp};
|
||||||
|
|
||||||
|
/// One notification format of one bank app. `text` (and `title`, if given) are literal text with holes:
|
||||||
|
/// `{amount}`, `{merchant}`, `{card}` and `{_}` (anything, ignored). Each hole matches at least one character.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct Template {
|
||||||
|
/// The Android package name of the bank app.
|
||||||
|
pub app: &'static str,
|
||||||
|
/// The bank, as `fixtures/notifications/<bank>/` names it.
|
||||||
|
pub bank: &'static str,
|
||||||
|
pub title: Option<&'static str>,
|
||||||
|
pub text: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The registry. Empty: no bank notification samples exist yet (`fixtures/notifications/README.md`).
|
||||||
|
pub const TEMPLATES: &[Template] = &[];
|
||||||
|
|
||||||
|
/// Notifications longer than this are not read.
|
||||||
|
pub const MAX_TEXT: usize = 1000;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Recognised {
|
||||||
|
/// From an app the person did not select: not read at all.
|
||||||
|
NotSelected,
|
||||||
|
/// From a selected app, but no template matches (or two readings disagree).
|
||||||
|
Unknown,
|
||||||
|
Payment(Capture),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`recognise_with`] over the registry.
|
||||||
|
pub fn recognise(app: &str, title: &str, text: &str, date: Date, at: Timestamp, selected: &[&str]) -> Recognised {
|
||||||
|
recognise_with(TEMPLATES, app, title, text, date, at, selected)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `date` and `at` are when the notification was posted (the phone's local date and the instant).
|
||||||
|
pub fn recognise_with(
|
||||||
|
templates: &[Template],
|
||||||
|
app: &str,
|
||||||
|
title: &str,
|
||||||
|
text: &str,
|
||||||
|
date: Date,
|
||||||
|
at: Timestamp,
|
||||||
|
selected: &[&str],
|
||||||
|
) -> Recognised {
|
||||||
|
if !selected.contains(&app) {
|
||||||
|
return Recognised::NotSelected;
|
||||||
|
}
|
||||||
|
if text.chars().count() > MAX_TEXT || title.chars().count() > MAX_TEXT {
|
||||||
|
return Recognised::Unknown;
|
||||||
|
}
|
||||||
|
let mut found: Option<Capture> = None;
|
||||||
|
for t in templates.iter().filter(|t| t.app == app) {
|
||||||
|
if t.title.is_some_and(|pat| matches(pat, title).is_empty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let all = matches(t.text, text);
|
||||||
|
if all.len() > MAX_READINGS {
|
||||||
|
return Recognised::Unknown;
|
||||||
|
}
|
||||||
|
for fields in all {
|
||||||
|
let Some(c) = capture(&fields, date, at) else { continue };
|
||||||
|
match &found {
|
||||||
|
None => found = Some(c),
|
||||||
|
Some(prev) if *prev == c => {}
|
||||||
|
Some(_) => return Recognised::Unknown,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
found.map(Recognised::Payment).unwrap_or(Recognised::Unknown)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
enum Hole {
|
||||||
|
Amount,
|
||||||
|
Merchant,
|
||||||
|
Card,
|
||||||
|
Any,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
enum Piece<'a> {
|
||||||
|
Lit(&'a str),
|
||||||
|
Hole(Hole),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pieces(pattern: &str) -> Vec<Piece<'_>> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut rest = pattern;
|
||||||
|
while let Some(i) = rest.find('{') {
|
||||||
|
let Some(j) = rest[i..].find('}') else { break };
|
||||||
|
let hole = match &rest[i + 1..i + j] {
|
||||||
|
"amount" => Some(Hole::Amount),
|
||||||
|
"merchant" => Some(Hole::Merchant),
|
||||||
|
"card" => Some(Hole::Card),
|
||||||
|
"_" => Some(Hole::Any),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
match hole {
|
||||||
|
Some(h) => {
|
||||||
|
if i > 0 {
|
||||||
|
out.push(Piece::Lit(&rest[..i]));
|
||||||
|
}
|
||||||
|
out.push(Piece::Hole(h));
|
||||||
|
}
|
||||||
|
None => out.push(Piece::Lit(&rest[..i + j + 1])),
|
||||||
|
}
|
||||||
|
rest = &rest[i + j + 1..];
|
||||||
|
}
|
||||||
|
if !rest.is_empty() {
|
||||||
|
out.push(Piece::Lit(rest));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
type Fields<'a> = Vec<(Hole, &'a str)>;
|
||||||
|
|
||||||
|
/// More readings than this of one notification is not a format, it is noise.
|
||||||
|
const MAX_READINGS: usize = 16;
|
||||||
|
|
||||||
|
/// Every way `text` matches `pattern` exactly, as the text of each hole.
|
||||||
|
fn matches<'a>(pattern: &str, text: &'a str) -> Vec<Fields<'a>> {
|
||||||
|
let ps = pieces(pattern);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
walk(&ps, text, Vec::new(), &mut out);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk<'a>(ps: &[Piece], text: &'a str, acc: Fields<'a>, out: &mut Vec<Fields<'a>>) {
|
||||||
|
if out.len() > MAX_READINGS {
|
||||||
|
return; // the caller treats this many readings as unknown
|
||||||
|
}
|
||||||
|
match ps.first() {
|
||||||
|
None => {
|
||||||
|
if text.is_empty() {
|
||||||
|
out.push(acc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(Piece::Lit(l)) => {
|
||||||
|
if let Some(rest) = text.strip_prefix(l) {
|
||||||
|
walk(&ps[1..], rest, acc, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(Piece::Hole(h)) => {
|
||||||
|
// The hole takes 1.. characters; with nothing after it, all the rest.
|
||||||
|
let ends: Vec<usize> = match ps.get(1) {
|
||||||
|
None => vec![text.len()],
|
||||||
|
Some(Piece::Lit(l)) => text.match_indices(l).map(|(i, _)| i).filter(|i| *i > 0).collect(),
|
||||||
|
Some(Piece::Hole(_)) => text.char_indices().map(|(i, _)| i).skip(1).chain([text.len()]).collect(),
|
||||||
|
};
|
||||||
|
for end in ends {
|
||||||
|
if end == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut next = acc.clone();
|
||||||
|
next.push((*h, &text[..end]));
|
||||||
|
walk(&ps[1..], &text[end..], next, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture(fields: &Fields, date: Date, at: Timestamp) -> Option<Capture> {
|
||||||
|
let get = |h: Hole| fields.iter().find(|(k, _)| *k == h).map(|(_, v)| v.trim());
|
||||||
|
let amount = amount::parse_positive(get(Hole::Amount)?)?.checked_neg().ok()?;
|
||||||
|
let merchant = get(Hole::Merchant)?;
|
||||||
|
if !merchant_ok(merchant) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let card = get(Hole::Card);
|
||||||
|
if card.is_some_and(|c| !card_ok(c)) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(Capture { amount, date, at, merchant: merchant.to_string(), card: card.filter(|c| !c.is_empty()).map(str::to_string) })
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
//! The iPhone Shortcut post (`POST /inbox`). We write the Shortcut, so the shape is ours:
|
||||||
|
//! `{"amount", "merchant", "card", "time"}` and an optional `"currency": "CZK"`, nothing else.
|
||||||
|
|
||||||
|
use crate::{amount, card_ok, merchant_ok, Capture};
|
||||||
|
use fiscus_ledger::{Date, Timestamp};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::value::RawValue;
|
||||||
|
|
||||||
|
/// The largest body the inbox reads.
|
||||||
|
pub const MAX_BODY: usize = 4096;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum CaptureError {
|
||||||
|
#[error("the post is larger than 4 KiB")]
|
||||||
|
TooLarge,
|
||||||
|
#[error("the post is not a JSON object with exactly amount, merchant, card and time")]
|
||||||
|
Malformed,
|
||||||
|
#[error("the amount is not a positive amount in CZK")]
|
||||||
|
Amount,
|
||||||
|
#[error("the currency is not CZK")]
|
||||||
|
Currency,
|
||||||
|
#[error("the merchant must be 1-200 characters without control characters")]
|
||||||
|
Merchant,
|
||||||
|
#[error("the card name must be at most 60 characters without control characters")]
|
||||||
|
Card,
|
||||||
|
#[error("the time is not ISO 8601 with an offset (2026-11-03T14:05:00+01:00)")]
|
||||||
|
Time,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Post<'a> {
|
||||||
|
#[serde(borrow)]
|
||||||
|
amount: &'a RawValue,
|
||||||
|
merchant: String,
|
||||||
|
card: String,
|
||||||
|
time: String,
|
||||||
|
currency: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One post → one capture, or the first thing wrong with it.
|
||||||
|
pub fn parse(body: &[u8]) -> Result<Capture, CaptureError> {
|
||||||
|
if body.len() > MAX_BODY {
|
||||||
|
return Err(CaptureError::TooLarge);
|
||||||
|
}
|
||||||
|
let post: Post = serde_json::from_slice(body).map_err(|_| CaptureError::Malformed)?;
|
||||||
|
let raw = post.amount.get();
|
||||||
|
let text: String = if raw.starts_with('"') {
|
||||||
|
serde_json::from_str(raw).map_err(|_| CaptureError::Amount)?
|
||||||
|
} else if raw.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
|
||||||
|
raw.to_string()
|
||||||
|
} else {
|
||||||
|
return Err(CaptureError::Amount);
|
||||||
|
};
|
||||||
|
let amount = amount::parse_positive(&text).ok_or(CaptureError::Amount)?;
|
||||||
|
if post.currency.as_deref().is_some_and(|c| c != "CZK") {
|
||||||
|
return Err(CaptureError::Currency);
|
||||||
|
}
|
||||||
|
if !merchant_ok(&post.merchant) {
|
||||||
|
return Err(CaptureError::Merchant);
|
||||||
|
}
|
||||||
|
if !card_ok(&post.card) {
|
||||||
|
return Err(CaptureError::Card);
|
||||||
|
}
|
||||||
|
let (date, at) = parse_time(&post.time).ok_or(CaptureError::Time)?;
|
||||||
|
let card = post.card.trim();
|
||||||
|
Ok(Capture {
|
||||||
|
amount: amount.checked_neg().map_err(|_| CaptureError::Amount)?,
|
||||||
|
date,
|
||||||
|
at,
|
||||||
|
merchant: post.merchant.trim().to_string(),
|
||||||
|
card: (!card.is_empty()).then(|| card.to_string()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn num(s: &str) -> Option<u32> {
|
||||||
|
(!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok()).flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `YYYY-MM-DDTHH:MM[:SS[.fff]](Z|±HH:MM)` → the local date written in it, and the instant.
|
||||||
|
pub fn parse_time(s: &str) -> Option<(Date, Timestamp)> {
|
||||||
|
let (date, rest) = s.split_once('T')?;
|
||||||
|
if date.len() != 10 || &date[4..5] != "-" || &date[7..8] != "-" {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let day = Date::from_ymd(num(&date[..4])? as i32, num(&date[5..7])?, num(&date[8..])?)?;
|
||||||
|
let (clock, offset_min) = if let Some(c) = rest.strip_suffix('Z') {
|
||||||
|
(c, 0i64)
|
||||||
|
} else {
|
||||||
|
let i = rest.rfind(['+', '-'])?;
|
||||||
|
let (c, off) = rest.split_at(i);
|
||||||
|
let sign = if off.starts_with('-') { -1 } else { 1 };
|
||||||
|
let off = &off[1..];
|
||||||
|
if off.len() != 5 || &off[2..3] != ":" {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let (h, m) = (num(&off[..2])?, num(&off[3..])?);
|
||||||
|
if h > 14 || m > 59 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
(c, sign * (h as i64 * 60 + m as i64))
|
||||||
|
};
|
||||||
|
let (hms, millis) = match clock.split_once('.') {
|
||||||
|
Some((hms, frac)) if (1..=3).contains(&frac.len()) => (hms, num(frac)? as i64 * 10i64.pow(3 - frac.len() as u32)),
|
||||||
|
Some(_) => return None,
|
||||||
|
None => (clock, 0),
|
||||||
|
};
|
||||||
|
let parts: Vec<&str> = hms.split(':').collect();
|
||||||
|
if !(2..=3).contains(&parts.len()) || parts.iter().any(|p| p.len() != 2) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let (h, m) = (num(parts[0])?, num(parts[1])?);
|
||||||
|
let sec = if parts.len() == 3 { num(parts[2])? } else { 0 };
|
||||||
|
if h > 23 || m > 59 || sec > 59 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let local_s = day.days() as i64 * 86_400 + h as i64 * 3600 + m as i64 * 60 + sec as i64;
|
||||||
|
let utc_ms = (local_s - offset_min * 60) * 1000 + millis;
|
||||||
|
Some((day, Timestamp(utc_ms)))
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
//! Day-2 mandatory test: Android bank notifications. Every real fixture parses; a notification from an app
|
||||||
|
//! the person did not select is never read; an unknown format is ignored, never guessed.
|
||||||
|
//!
|
||||||
|
//! The registry has no templates until real samples exist, so the engine is tested here with SYNTHETIC
|
||||||
|
//! templates that live only in this file. They are not any bank's format.
|
||||||
|
|
||||||
|
use fiscus_capture::notification::{recognise, recognise_with, Recognised, Template, TEMPLATES};
|
||||||
|
use fiscus_ledger::{Date, Haler, Timestamp};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
const APP: &str = "test.synthetic.bank";
|
||||||
|
|
||||||
|
const SYNTHETIC: &[Template] = &[
|
||||||
|
Template { app: APP, bank: "synthetic", title: Some("Card payment"), text: "Paid {amount} at {merchant} with card {card}." },
|
||||||
|
Template { app: APP, bank: "synthetic", title: None, text: "{_}: {amount} - {merchant}" },
|
||||||
|
];
|
||||||
|
|
||||||
|
fn day() -> Date {
|
||||||
|
"2026-11-03".parse().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn at() -> Timestamp {
|
||||||
|
Timestamp(1_793_711_100_000)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(app: &str, title: &str, text: &str, selected: &[&str]) -> Recognised {
|
||||||
|
recognise_with(SYNTHETIC, app, title, text, day(), at(), selected)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_notification_matching_a_template_is_a_payment() {
|
||||||
|
match run(APP, "Card payment", "Paid 129,50 Kč at Albert Praha with card *1234.", &[APP]) {
|
||||||
|
Recognised::Payment(c) => {
|
||||||
|
assert_eq!(c.amount, Haler(-12_950));
|
||||||
|
assert_eq!(c.merchant, "Albert Praha");
|
||||||
|
assert_eq!(c.card.as_deref(), Some("*1234"));
|
||||||
|
assert_eq!((c.date, c.at), (day(), at()));
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
assert!(matches!(run(APP, "anything", "Debit: 1 234,00 CZK - Shell", &[APP]), Recognised::Payment(c) if c.amount == Haler(-123_400) && c.merchant == "Shell"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_app_that_was_not_selected_is_never_read() {
|
||||||
|
// Even text that a template would match: the app decides first.
|
||||||
|
assert_eq!(run(APP, "Card payment", "Paid 129,50 Kč at Albert with card *1234.", &[]), Recognised::NotSelected);
|
||||||
|
assert_eq!(run(APP, "Card payment", "Paid 129,50 Kč at Albert with card *1234.", &["other.bank"]), Recognised::NotSelected);
|
||||||
|
assert_eq!(run("com.chat.app", "Card payment", "Paid 129,50 Kč at Albert with card *1234.", &[APP]), Recognised::NotSelected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unknown_format_is_ignored_never_guessed() {
|
||||||
|
for (title, text) in [
|
||||||
|
("Card payment", "Paid 129,50 Kč at Albert with card *1234"), // the final full stop is missing
|
||||||
|
("Card payment", "Paid around 129,50 Kč at Albert with card *1234."),
|
||||||
|
("Card payment", "Paid 129,50 EUR at Albert with card *1234."),
|
||||||
|
("Card payment", "Paid 0 Kč at Albert with card *1234."),
|
||||||
|
("Balance", "Your balance is 12 000 Kč"),
|
||||||
|
("Card payment", ""),
|
||||||
|
] {
|
||||||
|
assert_eq!(run(APP, title, text, &[APP]), Recognised::Unknown, "{text}");
|
||||||
|
}
|
||||||
|
let long = format!("Debit: {} - Shell", "1".repeat(5000));
|
||||||
|
assert_eq!(run(APP, "x", &long, &[APP]), Recognised::Unknown);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_ambiguous_match_is_unknown() {
|
||||||
|
// `{_}: {amount} - {merchant}` matches "A: 1 - B: 2 - C" two ways with different amounts.
|
||||||
|
assert_eq!(run(APP, "x", "A: 1 - B: 2 - C", &[APP]), Recognised::Unknown);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_real_registry_is_used_by_recognise() {
|
||||||
|
// With no templates for an app, a selected app's notification is unknown, never a payment.
|
||||||
|
for t in TEMPLATES {
|
||||||
|
assert!(!t.app.is_empty() && !t.bank.is_empty() && !t.text.is_empty());
|
||||||
|
}
|
||||||
|
assert_eq!(recognise(APP, "Card payment", "Paid 129,50 Kč at Albert with card *1234.", day(), at(), &[APP]), Recognised::Unknown);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A real, redacted notification and what it must become (`fixtures/notifications/<bank>/*.json`).
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Sample {
|
||||||
|
app: String,
|
||||||
|
title: String,
|
||||||
|
text: String,
|
||||||
|
/// `null` for a notification that is not a payment (a balance, a login) and must stay unknown.
|
||||||
|
expected: Option<Expected>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct Expected {
|
||||||
|
amount: i64,
|
||||||
|
merchant: String,
|
||||||
|
card: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn samples() -> Vec<PathBuf> {
|
||||||
|
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/notifications");
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let Ok(banks) = std::fs::read_dir(&root) else { return out };
|
||||||
|
for bank in banks.flatten().filter(|e| e.path().is_dir()) {
|
||||||
|
for f in std::fs::read_dir(bank.path()).unwrap().flatten() {
|
||||||
|
if f.path().extension().is_some_and(|e| e == "json") {
|
||||||
|
out.push(f.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.sort();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_real_fixture_parses_to_what_it_must() {
|
||||||
|
let all = samples();
|
||||||
|
eprintln!("notification fixtures: {}", all.len());
|
||||||
|
for path in all {
|
||||||
|
let s: Sample = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||||
|
let got = recognise(&s.app, &s.title, &s.text, day(), at(), &[s.app.as_str()]);
|
||||||
|
match (&s.expected, got) {
|
||||||
|
(None, Recognised::Unknown) => {}
|
||||||
|
(Some(e), Recognised::Payment(c)) => {
|
||||||
|
assert_eq!((c.amount, c.merchant.as_str(), c.card.as_deref()), (Haler(e.amount), e.merchant.as_str(), e.card.as_deref()), "{}", path.display());
|
||||||
|
}
|
||||||
|
(_, got) => panic!("{}: {got:?}", path.display()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
//! Day-2 mandatory test (the inbox's half in the core): the iPhone Shortcut post is hostile input. A malformed,
|
||||||
|
//! oversized or ambiguous body is an error with a reason, never a partial payment.
|
||||||
|
|
||||||
|
use fiscus_capture::shortcut::{parse, CaptureError, MAX_BODY};
|
||||||
|
use fiscus_ledger::{Date, Haler, Timestamp};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
/// 2026-11-03T13:05:00Z in milliseconds.
|
||||||
|
const AT: i64 = 1_793_711_100_000;
|
||||||
|
|
||||||
|
fn post(amount: &str) -> String {
|
||||||
|
format!(r#"{{"amount":{amount},"merchant":"ALBERT HYPERMARKET","card":"Apple Card","time":"2026-11-03T14:05:00+01:00"}}"#)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_good_post_becomes_one_outflow() {
|
||||||
|
let c = parse(post("129.5").as_bytes()).unwrap();
|
||||||
|
assert_eq!(c.amount, Haler(-12_950));
|
||||||
|
assert_eq!(c.merchant, "ALBERT HYPERMARKET");
|
||||||
|
assert_eq!(c.card.as_deref(), Some("Apple Card"));
|
||||||
|
assert_eq!(c.date, "2026-11-03".parse::<Date>().unwrap());
|
||||||
|
// 14:05 at +01:00 is 13:05 UTC.
|
||||||
|
assert_eq!(c.at, Timestamp(AT));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_amount_forms_shortcuts_writes_are_read_from_text_never_as_a_float() {
|
||||||
|
for (text, want) in [
|
||||||
|
("129", 12_900),
|
||||||
|
("129.00", 12_900),
|
||||||
|
("0.1", 10),
|
||||||
|
(r#""129,50""#, 12_950),
|
||||||
|
(r#""129,50 Kč""#, 12_950),
|
||||||
|
(r#""Kč 129,50""#, 12_950),
|
||||||
|
(r#""CZK 1 234,50""#, 123_450),
|
||||||
|
("\"1\u{a0}234,50\u{a0}Kč\"", 123_450),
|
||||||
|
("\"1\u{202f}234,50 CZK\"", 123_450),
|
||||||
|
] {
|
||||||
|
assert_eq!(parse(post(text).as_bytes()).map(|c| c.amount), Ok(Haler(-want)), "{text}");
|
||||||
|
}
|
||||||
|
for text in ["0", "-129", "1e3", "129.555", "\"\"", "\"abc\"", "\"$129\"", "\"129 EUR\"", "null", "true", "[129]", "99999999999"] {
|
||||||
|
assert_eq!(parse(post(text).as_bytes()).map(|c| c.amount), Err(CaptureError::Amount), "{text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_field_is_checked() {
|
||||||
|
let ok = r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z"}"#;
|
||||||
|
assert!(parse(ok.as_bytes()).is_ok());
|
||||||
|
let cases: &[(&str, CaptureError)] = &[
|
||||||
|
(r#"{"merchant":"M","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Malformed),
|
||||||
|
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z","extra":1}"#, CaptureError::Malformed),
|
||||||
|
(r#"{"amount":1,"amount":2,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Malformed),
|
||||||
|
(r#"{"amount":1,"merchant":"","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Merchant),
|
||||||
|
(r#"{"amount":1,"merchant":"a\u0000b","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Merchant),
|
||||||
|
(r#"{"amount":1,"merchant":"M","card":"a\nb","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Card),
|
||||||
|
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03 14:05"}"#, CaptureError::Time),
|
||||||
|
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-02-30T14:05:00Z"}"#, CaptureError::Time),
|
||||||
|
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T24:05:00Z"}"#, CaptureError::Time),
|
||||||
|
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00"}"#, CaptureError::Time),
|
||||||
|
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z","currency":"EUR"}"#, CaptureError::Currency),
|
||||||
|
(r#"[1,2]"#, CaptureError::Malformed),
|
||||||
|
("", CaptureError::Malformed),
|
||||||
|
];
|
||||||
|
for (body, want) in cases {
|
||||||
|
assert_eq!(parse(body.as_bytes()).err().as_ref(), Some(want), "{body}");
|
||||||
|
}
|
||||||
|
let long = format!(r#"{{"amount":1,"merchant":"{}","card":"","time":"2026-11-03T14:05:00Z"}}"#, "m".repeat(201));
|
||||||
|
assert_eq!(parse(long.as_bytes()).err(), Some(CaptureError::Merchant));
|
||||||
|
assert!(parse(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z","currency":"CZK"}"#.as_bytes()).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_oversized_body_is_refused_before_parsing() {
|
||||||
|
let mut big = post("1").into_bytes();
|
||||||
|
big.resize(MAX_BODY + 1, b' ');
|
||||||
|
assert_eq!(parse(&big).err(), Some(CaptureError::TooLarge));
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#[test]
|
||||||
|
fn random_bytes_never_panic_and_never_half_parse(bytes in proptest::collection::vec(any::<u8>(), 0..600)) {
|
||||||
|
let _ = parse(&bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_truncation_of_a_good_post_is_an_error(cut in 0usize..90) {
|
||||||
|
let full = post("\"129,50 Kč\"");
|
||||||
|
let cut = cut.min(full.len() - 1);
|
||||||
|
prop_assert!(parse(&full.as_bytes()[..cut]).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
//! 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};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Duplicate {
|
||||||
|
/// The service: the first word of the merchant key (`PAYPAL *SPOTIFY`, `Spotify AB` → `spotify`).
|
||||||
|
pub key: String,
|
||||||
|
/// Who pays it, sorted.
|
||||||
|
pub members: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first word of the merchant key, if it is at least three letters long.
|
||||||
|
pub fn service_key(name: &str) -> Option<String> {
|
||||||
|
let key = merchant_key(name);
|
||||||
|
let first = key.split(' ').next()?;
|
||||||
|
(first.chars().count() >= 3).then(|| first.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `(member, the subscription names they shared)` → every service two or more members pay, by key.
|
||||||
|
pub fn household_duplicates(shared: &[(String, Vec<String>)]) -> Vec<Duplicate> {
|
||||||
|
let mut by_key: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
|
||||||
|
for (member, names) in shared {
|
||||||
|
for key in names.iter().filter_map(|n| service_key(n)) {
|
||||||
|
by_key.entry(key).or_default().insert(member.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
by_key
|
||||||
|
.into_iter()
|
||||||
|
.filter(|(_, m)| m.len() >= 2)
|
||||||
|
.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()
|
||||||
|
}
|
||||||
@@ -3,4 +3,5 @@
|
|||||||
|
|
||||||
pub mod cancel;
|
pub mod cancel;
|
||||||
pub mod forecast;
|
pub mod forecast;
|
||||||
|
pub mod household;
|
||||||
pub mod subscriptions;
|
pub mod subscriptions;
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
//! Day 2: household duplicates ("you both pay Spotify"), only from names members chose to share.
|
||||||
|
|
||||||
|
use fiscus_insight::household::{household_duplicates, Duplicate};
|
||||||
|
|
||||||
|
fn names(v: &[&str]) -> Vec<String> {
|
||||||
|
v.iter().map(|s| s.to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_members_paying_the_same_service_is_a_duplicate() {
|
||||||
|
let shared = vec![
|
||||||
|
("mark".to_string(), names(&["PAYPAL *SPOTIFY", "Netflix.com", "O2 Czech"])),
|
||||||
|
("jana".to_string(), names(&["Spotify AB", "Netflix"])),
|
||||||
|
("kid".to_string(), names(&["Spotify"])),
|
||||||
|
];
|
||||||
|
let d = household_duplicates(&shared);
|
||||||
|
assert_eq!(
|
||||||
|
d,
|
||||||
|
vec![
|
||||||
|
Duplicate { key: "netflix".into(), members: vec!["jana".into(), "mark".into()] },
|
||||||
|
Duplicate { key: "spotify".into(), members: vec!["jana".into(), "kid".into(), "mark".into()] },
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
let one = vec![("mark".to_string(), names(&["Spotify", "spotify", "PAYPAL *SPOTIFY"]))];
|
||||||
|
assert!(household_duplicates(&one).is_empty(), "the same member twice is not a duplicate");
|
||||||
|
}
|
||||||
@@ -2,7 +2,10 @@
|
|||||||
|
|
||||||
use crate::date::{Date, Timestamp};
|
use crate::date::{Date, Timestamp};
|
||||||
use crate::import::StatementLine;
|
use crate::import::StatementLine;
|
||||||
|
use crate::invoice::{Invoice, InvoiceId, Supplier};
|
||||||
use crate::money::Haler;
|
use crate::money::Haler;
|
||||||
|
use crate::split::Share;
|
||||||
|
use crate::state::Glyph;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
/// Ids are opaque strings the app generates (random, unguessable); the core never makes one up.
|
/// Ids are opaque strings the app generates (random, unguessable); the core never makes one up.
|
||||||
@@ -10,6 +13,7 @@ pub type EventId = String;
|
|||||||
pub type PaymentId = String;
|
pub type PaymentId = String;
|
||||||
pub type BudgetId = String;
|
pub type BudgetId = String;
|
||||||
pub type RuleId = String;
|
pub type RuleId = String;
|
||||||
|
pub type SplitId = String;
|
||||||
/// A category id, e.g. `groceries` (see [`crate::categories`]).
|
/// A category id, e.g. `groceries` (see [`crate::categories`]).
|
||||||
pub type Category = String;
|
pub type Category = String;
|
||||||
|
|
||||||
@@ -35,6 +39,24 @@ pub enum Decision {
|
|||||||
Cancel,
|
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)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(tag = "type")]
|
#[serde(tag = "type")]
|
||||||
pub enum EventBody {
|
pub enum EventBody {
|
||||||
@@ -65,6 +87,10 @@ pub enum EventBody {
|
|||||||
PaymentTrialMarked { payment: PaymentId, ends: Date },
|
PaymentTrialMarked { payment: PaymentId, ends: Date },
|
||||||
#[serde(rename = "budget.created")]
|
#[serde(rename = "budget.created")]
|
||||||
BudgetCreated { budget: BudgetId, name: String, limit: Haler },
|
BudgetCreated { budget: BudgetId, name: String, limit: Haler },
|
||||||
|
/// A shared budget in a personal log (created here or joined): like `budget.created`, but never the
|
||||||
|
/// default budget, so unassigned payments never fall into a budget other people see.
|
||||||
|
#[serde(rename = "budget.shared")]
|
||||||
|
BudgetShared { budget: BudgetId, name: String, limit: Haler },
|
||||||
#[serde(rename = "budget.limit_set")]
|
#[serde(rename = "budget.limit_set")]
|
||||||
BudgetLimitSet { budget: BudgetId, limit: Haler },
|
BudgetLimitSet { budget: BudgetId, limit: Haler },
|
||||||
/// "Always <merchant key> → <category>".
|
/// "Always <merchant key> → <category>".
|
||||||
@@ -73,4 +99,63 @@ pub enum EventBody {
|
|||||||
/// Keep or cancel a subscription (by its key), seen at `amount` (a positive cost) on `on`.
|
/// Keep or cancel a subscription (by its key), seen at `amount` (a positive cost) on `on`.
|
||||||
#[serde(rename = "subscription.decided")]
|
#[serde(rename = "subscription.decided")]
|
||||||
SubscriptionDecided { subscription: String, decision: Decision, amount: Haler, on: Date },
|
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 },
|
||||||
|
/// 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> },
|
||||||
|
/// Who issues invoices from this ledger, and what share of each paid one is set aside for tax. The latest
|
||||||
|
/// counts from then on; an invoice keeps the supplier it was issued under.
|
||||||
|
#[serde(rename = "supplier.set")]
|
||||||
|
SupplierSet { supplier: Supplier },
|
||||||
|
#[serde(rename = "invoice.issued")]
|
||||||
|
InvoiceIssued { invoice: Invoice },
|
||||||
|
/// Paid: by `payment` (a statement line whose amount and variable symbol match), or marked paid by hand
|
||||||
|
/// (`None`: cash, another account). The reserve is set aside then.
|
||||||
|
#[serde(rename = "invoice.paid")]
|
||||||
|
InvoicePaid { invoice: InvoiceId, payment: Option<PaymentId>, on: Date },
|
||||||
|
/// Cancelled before it was paid.
|
||||||
|
#[serde(rename = "invoice.cancelled")]
|
||||||
|
InvoiceCancelled { invoice: InvoiceId },
|
||||||
|
/// Money taken out of the tax reserve (the tax or insurance paid from it).
|
||||||
|
#[serde(rename = "reserve.withdrawn")]
|
||||||
|
ReserveWithdrawn { withdrawal: String, amount: Haler, on: Date, note: String },
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,331 @@
|
|||||||
|
//! Invoices (faktury): the supplier, the customer, the lines and their totals, the number that is also the
|
||||||
|
//! variable symbol, and the tax reserve set aside when one is paid. Money in haléře; quantities in thousandths.
|
||||||
|
//!
|
||||||
|
//! - A line's amount is `quantity × unit price`, rounded half away from zero to the haléř.
|
||||||
|
//! - A VAT invoice (the supplier is a VAT payer): the base of each rate is the sum of its lines; the VAT of a rate
|
||||||
|
//! is `base × rate / 100`, rounded the same way, once per rate (§ 37 ZDPH: from the base, per rate).
|
||||||
|
//! - A non-VAT invoice has no rates, no taxable-supply date, and says the supplier is not a VAT payer.
|
||||||
|
//! - The number is `YYYYNNNN`: the year it was issued and the invoice's place in that year. The same digits are
|
||||||
|
//! the variable symbol, so a payment is matched by them.
|
||||||
|
|
||||||
|
use crate::date::{Date, Timestamp};
|
||||||
|
use crate::event::{Event, EventBody};
|
||||||
|
use crate::money::Haler;
|
||||||
|
use crate::pay::MAX_AMOUNT;
|
||||||
|
use crate::state::{CategorySource, EffectivePayment, InvoiceRecord, State};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
pub type InvoiceId = String;
|
||||||
|
|
||||||
|
/// The VAT rates in force in Czechia (from 2024): 21 %, 12 %, and 0 % for exempt supplies.
|
||||||
|
pub const VAT_RATES: [u8; 3] = [21, 12, 0];
|
||||||
|
/// At most this many lines on one invoice.
|
||||||
|
pub const MAX_LINES: usize = 50;
|
||||||
|
/// A quantity, in thousandths: from 0,001 to 1 000 000.
|
||||||
|
pub const MAX_QUANTITY: i64 = 1_000_000_000;
|
||||||
|
/// The share of a paid invoice set aside for tax, in thousandths: at most 60 %.
|
||||||
|
pub const MAX_RESERVE_PERMILLE: u16 = 600;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum InvoiceError {
|
||||||
|
#[error("a name must be 1-100 characters")]
|
||||||
|
Name,
|
||||||
|
#[error("an address has 1-4 lines of at most 100 characters")]
|
||||||
|
Address,
|
||||||
|
#[error("not a valid IČO (8 digits with a check digit)")]
|
||||||
|
Ico,
|
||||||
|
#[error("not a valid DIČ (CZ and 8-10 digits)")]
|
||||||
|
Dic,
|
||||||
|
#[error("an invoice has 1-50 lines")]
|
||||||
|
Lines,
|
||||||
|
#[error("a line's text must be 1-200 characters, its unit at most 10")]
|
||||||
|
LineText,
|
||||||
|
#[error("a quantity is between 0,001 and 1 000 000")]
|
||||||
|
Quantity,
|
||||||
|
#[error("a unit price is between 0,01 and 9 999 999,99 CZK")]
|
||||||
|
Price,
|
||||||
|
#[error("a VAT rate is 21, 12 or 0 %")]
|
||||||
|
Rate,
|
||||||
|
#[error("a VAT invoice gives every line a rate; an invoice without VAT gives none")]
|
||||||
|
RateUse,
|
||||||
|
#[error("the total must be between 0,01 and 9 999 999,99 CZK")]
|
||||||
|
Total,
|
||||||
|
#[error("an invoice number is the year and 4 digits, e.g. 20260001")]
|
||||||
|
Number,
|
||||||
|
#[error("the due date is before the issue date")]
|
||||||
|
Due,
|
||||||
|
#[error("a VAT invoice needs the date of the taxable supply; one without VAT has none")]
|
||||||
|
Taxable,
|
||||||
|
#[error("a VAT payer has a DIČ")]
|
||||||
|
PayerDic,
|
||||||
|
#[error("the reserve is 0-60 %")]
|
||||||
|
Reserve,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Someone on an invoice: the supplier or the customer.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Party {
|
||||||
|
pub name: String,
|
||||||
|
/// Street, town and postcode, country: 1-4 lines.
|
||||||
|
pub address: Vec<String>,
|
||||||
|
pub ico: Option<String>,
|
||||||
|
pub dic: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The person issuing invoices from this ledger.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Supplier {
|
||||||
|
pub party: Party,
|
||||||
|
pub vat_payer: bool,
|
||||||
|
/// Of each paid invoice's amount without VAT, this many thousandths are set aside for income tax and
|
||||||
|
/// insurance (a VAT payer's VAT is always set aside in full, on top).
|
||||||
|
pub reserve_permille: u16,
|
||||||
|
/// A line printed on the invoice, such as the trade register entry. Optional.
|
||||||
|
pub registration: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct InvoiceLine {
|
||||||
|
pub text: String,
|
||||||
|
/// Thousandths: 1 500 is 1,5.
|
||||||
|
pub quantity: i64,
|
||||||
|
/// `ks`, `h`, …; may be empty.
|
||||||
|
pub unit: String,
|
||||||
|
/// Per unit, without VAT on a VAT invoice.
|
||||||
|
pub unit_price: Haler,
|
||||||
|
/// The VAT rate in percent on a VAT invoice; `None` on an invoice without VAT.
|
||||||
|
pub vat: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Invoice {
|
||||||
|
pub id: InvoiceId,
|
||||||
|
/// `YYYYNNNN`, also the variable symbol.
|
||||||
|
pub number: String,
|
||||||
|
pub issued: Date,
|
||||||
|
pub due: Date,
|
||||||
|
/// The date of the taxable supply (DUZP), on a VAT invoice only.
|
||||||
|
pub taxable: Option<Date>,
|
||||||
|
pub customer: Party,
|
||||||
|
pub lines: Vec<InvoiceLine>,
|
||||||
|
/// The budget the payment goes into when it arrives; `None`: the default budget.
|
||||||
|
pub budget: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What an invoice adds up to.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Totals {
|
||||||
|
/// Each line's amount, in order.
|
||||||
|
pub lines: Vec<Haler>,
|
||||||
|
/// Rate → (base, VAT), highest rate first. Empty on an invoice without VAT.
|
||||||
|
pub rates: Vec<(u8, Haler, Haler)>,
|
||||||
|
/// Without VAT.
|
||||||
|
pub net: Haler,
|
||||||
|
pub vat: Haler,
|
||||||
|
/// What the customer pays.
|
||||||
|
pub total: Haler,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `a × b / d`, rounded half away from zero, or `None` when it does not fit an `i64`.
|
||||||
|
fn mul_div_round(a: i64, b: i64, d: i64) -> Option<i64> {
|
||||||
|
let n = i128::from(a) * i128::from(b);
|
||||||
|
let d = i128::from(d);
|
||||||
|
let q = n / d;
|
||||||
|
let r = n % d;
|
||||||
|
let q = if 2 * r.abs() >= d { q + n.signum() } else { q };
|
||||||
|
i64::try_from(q).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text_ok(s: &str, min: usize, max: usize) -> bool {
|
||||||
|
let n = s.trim().chars().count();
|
||||||
|
(min..=max).contains(&n) && s.chars().count() <= max + 20 && !s.chars().any(|c| c.is_control())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An IČO: 8 digits whose last is the weighted mod-11 check of the first seven.
|
||||||
|
pub fn ico_ok(s: &str) -> bool {
|
||||||
|
if s.len() != 8 || !s.bytes().all(|b| b.is_ascii_digit()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let d: Vec<u32> = s.bytes().map(|b| u32::from(b - b'0')).collect();
|
||||||
|
let sum: u32 = (0..7).map(|i| d[i] * (8 - i as u32)).sum();
|
||||||
|
let check = (11 - sum % 11) % 10;
|
||||||
|
d[7] == check
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Czech DIČ: `CZ` and 8-10 digits.
|
||||||
|
pub fn dic_ok(s: &str) -> bool {
|
||||||
|
s.len() >= 10 && s.len() <= 12 && s.starts_with("CZ") && s[2..].bytes().all(|b| b.is_ascii_digit())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Party {
|
||||||
|
pub fn check(&self) -> Result<(), InvoiceError> {
|
||||||
|
if !text_ok(&self.name, 1, 100) {
|
||||||
|
return Err(InvoiceError::Name);
|
||||||
|
}
|
||||||
|
if self.address.is_empty() || self.address.len() > 4 || !self.address.iter().all(|l| text_ok(l, 1, 100)) {
|
||||||
|
return Err(InvoiceError::Address);
|
||||||
|
}
|
||||||
|
if self.ico.as_deref().is_some_and(|i| !ico_ok(i)) {
|
||||||
|
return Err(InvoiceError::Ico);
|
||||||
|
}
|
||||||
|
if self.dic.as_deref().is_some_and(|d| !dic_ok(d)) {
|
||||||
|
return Err(InvoiceError::Dic);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Supplier {
|
||||||
|
pub fn check(&self) -> Result<(), InvoiceError> {
|
||||||
|
self.party.check()?;
|
||||||
|
if self.vat_payer && self.party.dic.is_none() {
|
||||||
|
return Err(InvoiceError::PayerDic);
|
||||||
|
}
|
||||||
|
if self.reserve_permille > MAX_RESERVE_PERMILLE {
|
||||||
|
return Err(InvoiceError::Reserve);
|
||||||
|
}
|
||||||
|
if self.registration.as_deref().is_some_and(|r| !text_ok(r, 1, 200)) {
|
||||||
|
return Err(InvoiceError::Name);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What is set aside when an invoice with these totals is paid: all of its VAT, and the reserve share of
|
||||||
|
/// the rest.
|
||||||
|
pub fn reserve_for(&self, t: &Totals) -> Haler {
|
||||||
|
let share = mul_div_round(t.net.0, i64::from(self.reserve_permille), 1000).unwrap_or(0);
|
||||||
|
Haler(t.vat.0.saturating_add(share))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The amount of one line.
|
||||||
|
pub fn line_amount(quantity: i64, unit_price: Haler) -> Result<Haler, InvoiceError> {
|
||||||
|
if !(1..=MAX_QUANTITY).contains(&quantity) {
|
||||||
|
return Err(InvoiceError::Quantity);
|
||||||
|
}
|
||||||
|
if unit_price.0 <= 0 || unit_price > MAX_AMOUNT {
|
||||||
|
return Err(InvoiceError::Price);
|
||||||
|
}
|
||||||
|
mul_div_round(quantity, unit_price.0, 1000).map(Haler).ok_or(InvoiceError::Total)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The totals of `lines`, for a VAT payer or not. Checks every line.
|
||||||
|
pub fn totals(lines: &[InvoiceLine], vat_payer: bool) -> Result<Totals, InvoiceError> {
|
||||||
|
if lines.is_empty() || lines.len() > MAX_LINES {
|
||||||
|
return Err(InvoiceError::Lines);
|
||||||
|
}
|
||||||
|
let mut amounts = Vec::with_capacity(lines.len());
|
||||||
|
let mut bases: BTreeMap<u8, i64> = BTreeMap::new();
|
||||||
|
let mut net: i64 = 0;
|
||||||
|
for l in lines {
|
||||||
|
if !text_ok(&l.text, 1, 200) || !text_ok(&l.unit, 0, 10) {
|
||||||
|
return Err(InvoiceError::LineText);
|
||||||
|
}
|
||||||
|
match (vat_payer, l.vat) {
|
||||||
|
(true, Some(r)) if VAT_RATES.contains(&r) => {}
|
||||||
|
(true, Some(_)) => return Err(InvoiceError::Rate),
|
||||||
|
(false, None) => {}
|
||||||
|
_ => return Err(InvoiceError::RateUse),
|
||||||
|
}
|
||||||
|
let a = line_amount(l.quantity, l.unit_price)?;
|
||||||
|
amounts.push(a);
|
||||||
|
net = net.checked_add(a.0).ok_or(InvoiceError::Total)?;
|
||||||
|
if let Some(r) = l.vat {
|
||||||
|
let b = bases.entry(r).or_default();
|
||||||
|
*b = b.checked_add(a.0).ok_or(InvoiceError::Total)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut rates = Vec::new();
|
||||||
|
let mut vat: i64 = 0;
|
||||||
|
for (r, base) in bases.into_iter().rev() {
|
||||||
|
let v = mul_div_round(base, i64::from(r), 100).ok_or(InvoiceError::Total)?;
|
||||||
|
vat = vat.checked_add(v).ok_or(InvoiceError::Total)?;
|
||||||
|
rates.push((r, Haler(base), Haler(v)));
|
||||||
|
}
|
||||||
|
let total = net.checked_add(vat).ok_or(InvoiceError::Total)?;
|
||||||
|
if total <= 0 || Haler(total) > MAX_AMOUNT {
|
||||||
|
return Err(InvoiceError::Total);
|
||||||
|
}
|
||||||
|
Ok(Totals { lines: amounts, rates, net: Haler(net), vat: Haler(vat), total: Haler(total) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The number of the `seq`-th invoice of `year`: `20260001`.
|
||||||
|
pub fn invoice_number(year: i32, seq: u32) -> Result<String, InvoiceError> {
|
||||||
|
if !(2000..=9999).contains(&year) || !(1..=9999).contains(&seq) {
|
||||||
|
return Err(InvoiceError::Number);
|
||||||
|
}
|
||||||
|
Ok(format!("{year}{seq:04}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Invoice {
|
||||||
|
/// Everything about the invoice that does not depend on the ledger; the totals when it is sound.
|
||||||
|
pub fn check(&self, supplier: &Supplier) -> Result<Totals, InvoiceError> {
|
||||||
|
let (year, _, _) = self.issued.ymd();
|
||||||
|
let n = &self.number;
|
||||||
|
if n.len() != 8 || !n.bytes().all(|b| b.is_ascii_digit()) || n[..4] != year.to_string() || &n[4..] == "0000" {
|
||||||
|
return Err(InvoiceError::Number);
|
||||||
|
}
|
||||||
|
if self.due < self.issued {
|
||||||
|
return Err(InvoiceError::Due);
|
||||||
|
}
|
||||||
|
if supplier.vat_payer != self.taxable.is_some() {
|
||||||
|
return Err(InvoiceError::Taxable);
|
||||||
|
}
|
||||||
|
self.customer.check()?;
|
||||||
|
totals(&self.lines, supplier.vat_payer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A variable symbol as banks write it, compared without leading zeros (`0020260001` is `20260001`).
|
||||||
|
pub fn same_vs(a: &str, b: &str) -> bool {
|
||||||
|
let t = |s: &str| s.trim().trim_start_matches('0').to_string();
|
||||||
|
!t(a).is_empty() && t(a) == t(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The events that record invoices paid by statement lines. A line pays an unpaid invoice when its amount is the
|
||||||
|
/// invoice's total and its variable symbol is the invoice's number; the earliest such line wins, and a line pays
|
||||||
|
/// one invoice only. The line becomes income, in the invoice's budget. Nothing is guessed: a line of another
|
||||||
|
/// amount, or without the symbol, stays for the person to look at.
|
||||||
|
pub fn plan_invoice_payments(state: &State, ids: &mut dyn FnMut() -> String, at: Timestamp) -> Vec<Event> {
|
||||||
|
let mut open: Vec<&InvoiceRecord> = state.invoices.values().filter(|r| r.paid.is_none() && !r.cancelled).collect();
|
||||||
|
open.sort_by_key(|r| r.seq);
|
||||||
|
let lines: Vec<EffectivePayment> = state.effective_payments().into_iter().filter(|p| p.line.is_some() && p.amount.0 > 0).collect();
|
||||||
|
let mut taken: BTreeSet<String> = state.invoice_payments.keys().cloned().collect();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for r in open {
|
||||||
|
let found = lines.iter().find(|p| {
|
||||||
|
let line = p.line.as_deref().unwrap_or_default();
|
||||||
|
p.amount == r.totals.total
|
||||||
|
&& p.date >= r.invoice.issued
|
||||||
|
&& p.variable_symbol.as_deref().is_some_and(|vs| same_vs(vs, &r.invoice.number))
|
||||||
|
&& !taken.contains(line)
|
||||||
|
&& !taken.contains(&p.id)
|
||||||
|
});
|
||||||
|
let Some(p) = found else { continue };
|
||||||
|
let line = p.line.clone().unwrap_or_default();
|
||||||
|
taken.insert(line.clone());
|
||||||
|
taken.insert(p.id.clone());
|
||||||
|
out.push(Event::new(ids(), at, EventBody::InvoicePaid { invoice: r.invoice.id.clone(), payment: Some(line.clone()), on: p.date }));
|
||||||
|
if p.category_source != CategorySource::Explicit {
|
||||||
|
out.push(Event::new(ids(), at, EventBody::PaymentCategorised { payment: line.clone(), category: "income".into() }));
|
||||||
|
}
|
||||||
|
if let Some(b) = &r.invoice.budget {
|
||||||
|
out.push(Event::new(ids(), at, EventBody::PaymentAssigned { payment: line, budget: b.clone() }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rounding_is_half_away_from_zero() {
|
||||||
|
assert_eq!(mul_div_round(1, 5, 10), Some(1));
|
||||||
|
assert_eq!(mul_div_round(1, 4, 10), Some(0));
|
||||||
|
assert_eq!(mul_div_round(-1, 5, 10), Some(-1));
|
||||||
|
assert_eq!(mul_div_round(i64::MAX, i64::MAX, 1), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,16 +1,21 @@
|
|||||||
//! Fiscus Domi's ledger: money in haléře, civil dates, the append-only event log and the state derived from
|
//! 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 categories;
|
||||||
pub mod date;
|
pub mod date;
|
||||||
pub mod event;
|
pub mod event;
|
||||||
pub mod import;
|
pub mod import;
|
||||||
|
pub mod invoice;
|
||||||
pub mod matching;
|
pub mod matching;
|
||||||
pub mod merchant;
|
pub mod merchant;
|
||||||
pub mod money;
|
pub mod money;
|
||||||
|
pub mod pay;
|
||||||
|
pub mod share;
|
||||||
|
pub mod split;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
|
|
||||||
pub use date::{Date, Timestamp};
|
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 money::Haler;
|
||||||
pub use state::{EffectivePayment, Glyph, Origin, State};
|
pub use state::{EffectivePayment, Glyph, Origin, ShareView, State};
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
//! 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` unless that payment was **explicitly** assigned to
|
||||||
|
/// that budget (`payment.assigned`, the latest on either half of a confirmed pair). Falling into a budget as
|
||||||
|
/// the default never shares a payment.
|
||||||
|
pub fn shared_payment(state: &State, payment: &str, budget: &str) -> Option<EventBody> {
|
||||||
|
let p = state.effective_payment(payment)?;
|
||||||
|
let explicit = [p.captured.as_deref(), p.line.as_deref()]
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|id| state.payments.get(id).and_then(|r| r.budget.as_ref()))
|
||||||
|
.max_by_key(|stamp| stamp.seq)
|
||||||
|
.map(|stamp| stamp.value.as_str());
|
||||||
|
if explicit != 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,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -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())
|
||||||
|
}
|
||||||
@@ -3,10 +3,13 @@
|
|||||||
|
|
||||||
use crate::categories;
|
use crate::categories;
|
||||||
use crate::date::Date;
|
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::import::StatementLine;
|
||||||
|
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
|
||||||
use crate::merchant::merchant_key;
|
use crate::merchant::merchant_key;
|
||||||
use crate::money::Haler;
|
use crate::money::Haler;
|
||||||
|
use crate::pay::{spayd, Iban};
|
||||||
|
use crate::split::Share;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
@@ -89,6 +92,88 @@ pub struct DecisionRecord {
|
|||||||
pub seq: u64,
|
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)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct Rejection {
|
pub struct Rejection {
|
||||||
pub event: EventId,
|
pub event: EventId,
|
||||||
@@ -104,12 +189,31 @@ pub struct State {
|
|||||||
pub payments: BTreeMap<PaymentId, PaymentRecord>,
|
pub payments: BTreeMap<PaymentId, PaymentRecord>,
|
||||||
pub line_keys: BTreeMap<String, PaymentId>,
|
pub line_keys: BTreeMap<String, PaymentId>,
|
||||||
pub budgets: BTreeMap<BudgetId, Budget>,
|
pub budgets: BTreeMap<BudgetId, Budget>,
|
||||||
/// The first budget created: where a payment goes when nobody assigned it.
|
/// The first budget created (never a shared one): where a payment goes when nobody assigned it.
|
||||||
pub default_budget: Option<BudgetId>,
|
pub default_budget: Option<BudgetId>,
|
||||||
/// Merchant key → the latest rule for it.
|
/// Merchant key → the latest rule for it.
|
||||||
pub rules: BTreeMap<String, Rule>,
|
pub rules: BTreeMap<String, Rule>,
|
||||||
/// Subscription key → its decisions, oldest first.
|
/// Subscription key → its decisions, oldest first.
|
||||||
pub decisions: BTreeMap<String, Vec<DecisionRecord>>,
|
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>,
|
pub rejected: Vec<Rejection>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,6 +251,10 @@ pub struct EffectivePayment {
|
|||||||
pub trial_ends: Option<Date>,
|
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 {
|
fn text_ok(s: &str) -> bool {
|
||||||
s.chars().count() <= MAX_TEXT && !s.chars().any(|c| c.is_control())
|
s.chars().count() <= MAX_TEXT && !s.chars().any(|c| c.is_control())
|
||||||
}
|
}
|
||||||
@@ -155,6 +263,19 @@ fn opt_text_ok(s: &Option<String>) -> bool {
|
|||||||
s.as_deref().is_none_or(text_ok)
|
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> {
|
fn latest<T: Clone>(a: &Option<Stamped<T>>, b: Option<&Option<Stamped<T>>>) -> Option<T> {
|
||||||
let b = b.and_then(|b| b.as_ref());
|
let b = b.and_then(|b| b.as_ref());
|
||||||
match (a.as_ref(), b) {
|
match (a.as_ref(), b) {
|
||||||
@@ -323,7 +444,7 @@ impl State {
|
|||||||
EventBody::PaymentTrialMarked { payment, ends } => {
|
EventBody::PaymentTrialMarked { payment, ends } => {
|
||||||
self.payment_mut(payment)?.trial_ends = Some(Stamped { seq, value: *ends });
|
self.payment_mut(payment)?.trial_ends = Some(Stamped { seq, value: *ends });
|
||||||
}
|
}
|
||||||
EventBody::BudgetCreated { budget, name, limit } => {
|
EventBody::BudgetCreated { budget, name, limit } | EventBody::BudgetShared { budget, name, limit } => {
|
||||||
if budget.is_empty() || self.budgets.contains_key(budget) {
|
if budget.is_empty() || self.budgets.contains_key(budget) {
|
||||||
return Err("a budget with this id exists");
|
return Err("a budget with this id exists");
|
||||||
}
|
}
|
||||||
@@ -335,7 +456,7 @@ impl State {
|
|||||||
return Err("a limit cannot be negative");
|
return Err("a limit cannot be negative");
|
||||||
}
|
}
|
||||||
self.budgets.insert(budget.clone(), Budget { id: budget.clone(), name: name.into(), limit: *limit, seq });
|
self.budgets.insert(budget.clone(), Budget { id: budget.clone(), name: name.into(), limit: *limit, seq });
|
||||||
if self.default_budget.is_none() {
|
if self.default_budget.is_none() && matches!(body, EventBody::BudgetCreated { .. }) {
|
||||||
self.default_budget = Some(budget.clone());
|
self.default_budget = Some(budget.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -366,10 +487,309 @@ impl State {
|
|||||||
.or_default()
|
.or_default()
|
||||||
.push(DecisionRecord { decision: *decision, amount: *amount, on: *on, seq });
|
.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(())
|
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).
|
/// 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> {
|
pub fn effective_payments(&self) -> Vec<EffectivePayment> {
|
||||||
let mut out: Vec<EffectivePayment> = self
|
let mut out: Vec<EffectivePayment> = self
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
//! Invoices (v1.1): the totals to the haléř with and without VAT, the number that is the variable symbol, a paid
|
||||||
|
//! invoice found on a statement and landing in its budget with the reserve set aside, and everything hostile or
|
||||||
|
//! inconsistent refused.
|
||||||
|
|
||||||
|
use fiscus_ledger::import::StatementLine;
|
||||||
|
use fiscus_ledger::invoice::{dic_ok, ico_ok, invoice_number, line_amount, plan_invoice_payments, same_vs, totals, Invoice, InvoiceError, InvoiceLine, Party, Supplier};
|
||||||
|
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||||
|
|
||||||
|
fn d(s: &str) -> Date {
|
||||||
|
s.parse().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Ids(u64);
|
||||||
|
impl Ids {
|
||||||
|
fn next(&mut self) -> String {
|
||||||
|
self.0 += 1;
|
||||||
|
format!("id{:04}", self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ev(ids: &mut Ids, body: EventBody) -> Event {
|
||||||
|
Event::new(ids.next(), Timestamp(0), body)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn party(name: &str) -> Party {
|
||||||
|
Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some("45244782".into()), dic: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supplier(vat_payer: bool, reserve_permille: u16) -> Supplier {
|
||||||
|
let mut p = party("Marek Novák");
|
||||||
|
p.ico = Some("27074358".into());
|
||||||
|
p.dic = vat_payer.then(|| "CZ8001011234".into());
|
||||||
|
Supplier { party: p, vat_payer, reserve_permille, registration: Some("Fyzická osoba zapsaná v živnostenském rejstříku.".into()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn line(text: &str, quantity: i64, price: i64, vat: Option<u8>) -> InvoiceLine {
|
||||||
|
InvoiceLine { text: text.into(), quantity, unit: "h".into(), unit_price: Haler(price), vat }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invoice(id: &str, number: &str, issued: &str, lines: Vec<InvoiceLine>, vat: bool) -> Invoice {
|
||||||
|
Invoice {
|
||||||
|
id: id.into(),
|
||||||
|
number: number.into(),
|
||||||
|
issued: d(issued),
|
||||||
|
due: d(issued).add_days(14),
|
||||||
|
taxable: vat.then(|| d(issued)),
|
||||||
|
customer: party("Odběratel s.r.o."),
|
||||||
|
lines,
|
||||||
|
budget: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn imported(ids: &mut Ids, amount: i64, booked: &str, vs: Option<&str>) -> (Event, String) {
|
||||||
|
let payment = ids.next();
|
||||||
|
let line = StatementLine {
|
||||||
|
bank: "test".into(),
|
||||||
|
account: "1".into(),
|
||||||
|
booked: d(booked),
|
||||||
|
amount: Haler(amount),
|
||||||
|
merchant: "Odběratel s.r.o.".into(),
|
||||||
|
counterparty: Some("123/0100".into()),
|
||||||
|
variable_symbol: vs.map(Into::into),
|
||||||
|
message: None,
|
||||||
|
bank_ref: Some(payment.clone()),
|
||||||
|
};
|
||||||
|
(ev(ids, EventBody::PaymentImported { payment: payment.clone(), line, line_key: format!("test|1|{payment}") }), payment)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(state: &mut State, events: &[Event]) {
|
||||||
|
for e in events {
|
||||||
|
state.apply(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ico_and_dic_are_checked() {
|
||||||
|
assert!(ico_ok("45244782")); // Česká spořitelna
|
||||||
|
assert!(ico_ok("27074358"));
|
||||||
|
assert!(!ico_ok("45244783"));
|
||||||
|
assert!(!ico_ok("4524478"));
|
||||||
|
assert!(!ico_ok("4524478a"));
|
||||||
|
assert!(dic_ok("CZ45244782") && dic_ok("CZ8001011234"));
|
||||||
|
assert!(!dic_ok("SK45244782") && !dic_ok("CZ1234567") && !dic_ok("CZ1234567890123"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_invoice_without_vat_adds_up_to_the_haler() {
|
||||||
|
let t = totals(&[line("Konzultace", 1_500, 120_000, None), line("Licence", 3_000, 33_333, None)], false).unwrap();
|
||||||
|
assert_eq!(t.lines, vec![Haler(180_000), Haler(99_999)]);
|
||||||
|
assert_eq!((t.net, t.vat, t.total), (Haler(279_999), Haler(0), Haler(279_999)));
|
||||||
|
assert!(t.rates.is_empty());
|
||||||
|
// 0,333 h at 1 000 Kč is 333,00; at 1 000,05 Kč 333,016… → 333,02. Rounded half away from zero.
|
||||||
|
assert_eq!(line_amount(333, Haler(100_000)).unwrap(), Haler(33_300));
|
||||||
|
assert_eq!(line_amount(333, Haler(100_005)).unwrap(), Haler(33_302));
|
||||||
|
assert_eq!(line_amount(1, Haler(50)).unwrap(), Haler(0), "0,0005 Kč is nothing");
|
||||||
|
assert_eq!(line_amount(500, Haler(1)).unwrap(), Haler(1), "0,005 Kč rounds up to 0,01");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_vat_invoice_computes_vat_once_per_rate_from_its_base() {
|
||||||
|
let t = totals(&[line("Vývoj", 10_000, 100_000, Some(21)), line("Kniha", 1_000, 100_000, Some(12)), line("Vývoj", 1_000, 3, Some(21)), line("Pojištění", 1_000, 5_000, Some(0))], true).unwrap();
|
||||||
|
// 21 %: base 10 000,03 → VAT 2 100,0063 → 2 100,01; 12 %: 1 000 → 120; 0 %: 50 → 0.
|
||||||
|
assert_eq!(t.rates, vec![(21, Haler(1_000_003), Haler(210_001)), (12, Haler(100_000), Haler(12_000)), (0, Haler(5_000), Haler(0))]);
|
||||||
|
assert_eq!((t.net, t.vat, t.total), (Haler(1_105_003), Haler(222_001), Haler(1_327_004)));
|
||||||
|
// Per rate, not per line: three lines of 0,05 at 21 % are 0,15 → 0,03 VAT (per line it would be 3 × 0,01).
|
||||||
|
let t = totals(&[line("a", 1_000, 5, Some(21)), line("b", 1_000, 5, Some(21)), line("c", 1_000, 5, Some(21))], true).unwrap();
|
||||||
|
assert_eq!(t.vat, Haler(3));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_lines_are_refused() {
|
||||||
|
let ok = line("Práce", 1_000, 100_000, None);
|
||||||
|
assert_eq!(totals(&[], false), Err(InvoiceError::Lines));
|
||||||
|
assert_eq!(totals(&vec![ok.clone(); 51], false), Err(InvoiceError::Lines));
|
||||||
|
assert_eq!(totals(&[line("Práce", 0, 100, None)], false), Err(InvoiceError::Quantity));
|
||||||
|
assert_eq!(totals(&[line("Práce", 1_000, 0, None)], false), Err(InvoiceError::Price));
|
||||||
|
assert_eq!(totals(&[line("Práce", 1_000, -100, None)], false), Err(InvoiceError::Price));
|
||||||
|
assert_eq!(totals(&[line("", 1_000, 100, None)], false), Err(InvoiceError::LineText));
|
||||||
|
assert_eq!(totals(&[line("A\u{0}B", 1_000, 100, None)], false), Err(InvoiceError::LineText));
|
||||||
|
assert_eq!(totals(&[line("Práce", 1_000, 100, Some(21))], false), Err(InvoiceError::RateUse), "a rate without being a VAT payer");
|
||||||
|
assert_eq!(totals(&[line("Práce", 1_000, 100, None)], true), Err(InvoiceError::RateUse), "a VAT invoice line without a rate");
|
||||||
|
assert_eq!(totals(&[line("Práce", 1_000, 100, Some(15))], true), Err(InvoiceError::Rate));
|
||||||
|
// Over what QR Platba and a statement can carry.
|
||||||
|
assert_eq!(totals(&[line("Práce", 1_000_000_000, 999_999_999, None)], false), Err(InvoiceError::Total));
|
||||||
|
assert_eq!(totals(&[line("Práce", 2_000, 999_999_999, None)], false), Err(InvoiceError::Total));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_are_the_year_and_a_sequence_and_the_variable_symbol() {
|
||||||
|
assert_eq!(invoice_number(2026, 1).unwrap(), "20260001");
|
||||||
|
assert_eq!(invoice_number(2026, 0), Err(InvoiceError::Number));
|
||||||
|
assert_eq!(invoice_number(2026, 10_000), Err(InvoiceError::Number));
|
||||||
|
assert!(same_vs("0020260001", "20260001") && same_vs(" 20260001 ", "20260001"));
|
||||||
|
assert!(!same_vs("20260002", "20260001") && !same_vs("", "") && !same_vs("000", "0"));
|
||||||
|
|
||||||
|
let mut ids = Ids(0);
|
||||||
|
let mut s = State::default();
|
||||||
|
assert_eq!(s.next_invoice_number(2026).as_deref(), Some("20260001"));
|
||||||
|
let events = [
|
||||||
|
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
|
||||||
|
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false) }),
|
||||||
|
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i2", "20260002", "2026-04-01", vec![line("Práce", 1_000, 100_000, None)], false) }),
|
||||||
|
];
|
||||||
|
apply(&mut s, &events);
|
||||||
|
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||||
|
assert_eq!(s.next_invoice_number(2026).as_deref(), Some("20260003"));
|
||||||
|
assert_eq!(s.next_invoice_number(2027).as_deref(), Some("20270001"), "each year starts again");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_invoice_that_does_not_fit_is_rejected_and_changes_nothing() {
|
||||||
|
let mut ids = Ids(0);
|
||||||
|
let mut s = State::default();
|
||||||
|
let good = || invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false);
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: good() })]);
|
||||||
|
assert_eq!(s.rejected.len(), 1, "no supplier yet");
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) })]);
|
||||||
|
|
||||||
|
let mut cases: Vec<Invoice> = Vec::new();
|
||||||
|
let mut i = good();
|
||||||
|
i.number = "20250001".into(); // not this year's
|
||||||
|
cases.push(i);
|
||||||
|
let mut i = good();
|
||||||
|
i.number = "20260000".into();
|
||||||
|
cases.push(i);
|
||||||
|
let mut i = good();
|
||||||
|
i.number = "2026001".into();
|
||||||
|
cases.push(i);
|
||||||
|
let mut i = good();
|
||||||
|
i.due = d("2026-02-28");
|
||||||
|
cases.push(i);
|
||||||
|
let mut i = good();
|
||||||
|
i.taxable = Some(d("2026-03-01")); // a DUZP without being a VAT payer
|
||||||
|
cases.push(i);
|
||||||
|
let mut i = good();
|
||||||
|
i.customer.ico = Some("12345678".into());
|
||||||
|
cases.push(i);
|
||||||
|
let mut i = good();
|
||||||
|
i.customer.name = "X\u{7}".into();
|
||||||
|
cases.push(i);
|
||||||
|
let mut i = good();
|
||||||
|
i.customer.address = vec![];
|
||||||
|
cases.push(i);
|
||||||
|
let mut i = good();
|
||||||
|
i.budget = Some("no-such".into());
|
||||||
|
cases.push(i);
|
||||||
|
let before = s.rejected.len();
|
||||||
|
for c in cases.iter().cloned() {
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: c })]);
|
||||||
|
}
|
||||||
|
assert_eq!(s.rejected.len() - before, cases.len());
|
||||||
|
assert!(s.invoices.is_empty() && s.invoice_numbers.is_empty());
|
||||||
|
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: good() })]);
|
||||||
|
let mut again = good();
|
||||||
|
again.id = "i2".into();
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: again })]);
|
||||||
|
assert_eq!(s.invoices.len(), 1, "a number is used once");
|
||||||
|
|
||||||
|
// A VAT payer without a DIČ, a reserve over 60 %.
|
||||||
|
let mut no_dic = supplier(true, 150);
|
||||||
|
no_dic.party.dic = None;
|
||||||
|
let before = s.rejected.len();
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: no_dic }), ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 601) })]);
|
||||||
|
assert_eq!(s.rejected.len() - before, 2);
|
||||||
|
assert_eq!(s.supplier, Some(supplier(false, 150)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_paid_invoice_lands_in_its_budget_with_the_reserve_set_aside_untouched() {
|
||||||
|
let mut ids = Ids(0);
|
||||||
|
let mut s = State::default();
|
||||||
|
let mut inv = invoice("i1", "20260001", "2026-03-01", vec![line("Konzultace", 10_000, 150_000, None)], false);
|
||||||
|
inv.budget = Some("home".into());
|
||||||
|
apply(
|
||||||
|
&mut s,
|
||||||
|
&[
|
||||||
|
ev(&mut ids, EventBody::BudgetCreated { budget: "home".into(), name: "Home".into(), limit: Haler(3_000_000) }),
|
||||||
|
ev(&mut ids, EventBody::AccountSet { iban: "CZ6508000000192000145399".into(), name: "Marek Novak".into() }),
|
||||||
|
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
|
||||||
|
ev(&mut ids, EventBody::InvoiceIssued { invoice: inv }),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||||
|
assert_eq!(s.invoices["i1"].totals.total, Haler(1_500_000));
|
||||||
|
let qr = s.invoice_spayd("i1").unwrap();
|
||||||
|
assert!(qr.contains("*AM:15000.00*") && qr.contains("*X-VS:20260001") && qr.contains("*MSG:Faktura 20260001"), "{qr}");
|
||||||
|
|
||||||
|
// The statement brings three lines: the wrong amount, no symbol, and the payment (the bank pads the symbol).
|
||||||
|
let (wrong, _) = imported(&mut ids, 1_400_000, "2026-03-10", Some("20260001"));
|
||||||
|
let (nosym, _) = imported(&mut ids, 1_500_000, "2026-03-11", None);
|
||||||
|
let (right, paid_by) = imported(&mut ids, 1_500_000, "2026-03-12", Some("0020260001"));
|
||||||
|
apply(&mut s, &[wrong, nosym, right]);
|
||||||
|
let plan = plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0));
|
||||||
|
let kinds: Vec<String> = plan.iter().map(|e| format!("{:?}", e.body).split_whitespace().next().unwrap().to_string()).collect();
|
||||||
|
assert_eq!(kinds, vec!["InvoicePaid", "PaymentCategorised", "PaymentAssigned"]);
|
||||||
|
apply(&mut s, &plan);
|
||||||
|
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||||
|
|
||||||
|
let paid = s.invoices["i1"].paid.clone().unwrap();
|
||||||
|
assert_eq!((paid.payment.as_deref(), paid.on), (Some(paid_by.as_str()), d("2026-03-12")));
|
||||||
|
assert_eq!(paid.reserve, Haler(225_000), "15 % of 15 000 Kč");
|
||||||
|
assert_eq!(s.reserve_balance(), Haler(225_000));
|
||||||
|
let p = s.effective_payment(&paid_by).unwrap();
|
||||||
|
assert_eq!((p.category.as_deref(), p.budget.as_deref()), (Some("income"), Some("home")));
|
||||||
|
assert_eq!(s.invoice_spayd("i1"), None, "no QR for a paid invoice");
|
||||||
|
|
||||||
|
// Planning again finds nothing: paid once.
|
||||||
|
assert!(plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0)).is_empty());
|
||||||
|
|
||||||
|
// The reserve pays the tax: no more than it holds.
|
||||||
|
let before = s.rejected.len();
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w1".into(), amount: Haler(225_001), on: d("2027-03-31"), note: "Daň z příjmů".into() })]);
|
||||||
|
assert_eq!(s.rejected.len() - before, 1);
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w1".into(), amount: Haler(200_000), on: d("2027-03-31"), note: "Daň z příjmů".into() })]);
|
||||||
|
assert_eq!(s.reserve_balance(), Haler(25_000), "{:?}", s.rejected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_vat_payer_sets_aside_all_the_vat_and_the_share_of_the_rest() {
|
||||||
|
let mut ids = Ids(0);
|
||||||
|
let mut s = State::default();
|
||||||
|
apply(
|
||||||
|
&mut s,
|
||||||
|
&[
|
||||||
|
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 100) }),
|
||||||
|
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Vývoj", 10_000, 100_000, Some(21))], true) }),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||||
|
assert_eq!(s.invoices["i1"].totals.total, Haler(1_210_000));
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-05") })]);
|
||||||
|
// VAT 2 100 Kč, and 10 % of 10 000 Kč.
|
||||||
|
assert_eq!(s.reserve_balance(), Haler(310_000));
|
||||||
|
// A later change of the supplier does not change an invoice issued before it.
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 300) })]);
|
||||||
|
assert_eq!(s.invoices["i1"].supplier.reserve_permille, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_payment_pays_one_invoice_once_and_only_its_own_amount() {
|
||||||
|
let mut ids = Ids(0);
|
||||||
|
let mut s = State::default();
|
||||||
|
let one = |id: &str, n: &str| invoice(id, n, "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false);
|
||||||
|
apply(
|
||||||
|
&mut s,
|
||||||
|
&[
|
||||||
|
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
|
||||||
|
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i1", "20260001") }),
|
||||||
|
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i2", "20260002") }),
|
||||||
|
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i3", "20260003") }),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let (line_event, line) = imported(&mut ids, 100_000, "2026-03-02", Some("20260001"));
|
||||||
|
let (small, small_id) = imported(&mut ids, 99_999, "2026-03-02", Some("20260002"));
|
||||||
|
let (early, _) = imported(&mut ids, 100_000, "2026-02-27", Some("20260003"));
|
||||||
|
apply(&mut s, &[line_event, small, early]);
|
||||||
|
let before = s.rejected.len();
|
||||||
|
apply(
|
||||||
|
&mut s,
|
||||||
|
&[
|
||||||
|
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: Some(small_id), on: d("2026-03-02") }), // wrong amount
|
||||||
|
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: Some("no-such".into()), on: d("2026-03-02") }),
|
||||||
|
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: None, on: d("2026-02-01") }), // before it was issued
|
||||||
|
ev(&mut ids, EventBody::InvoicePaid { invoice: "nope".into(), payment: None, on: d("2026-03-02") }),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert_eq!(s.rejected.len() - before, 4);
|
||||||
|
// The early line (before the invoice was issued) pays nothing; the right one pays i1 only.
|
||||||
|
let plan = plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0));
|
||||||
|
let paid: Vec<String> = plan.iter().filter_map(|e| match &e.body { EventBody::InvoicePaid { invoice, .. } => Some(invoice.clone()), _ => None }).collect();
|
||||||
|
assert_eq!(paid, vec!["i1"]);
|
||||||
|
apply(&mut s, &plan);
|
||||||
|
let before = s.rejected.len();
|
||||||
|
apply(
|
||||||
|
&mut s,
|
||||||
|
&[
|
||||||
|
ev(&mut ids, EventBody::InvoicePaid { invoice: "i3".into(), payment: Some(line.clone()), on: d("2026-03-02") }), // used by i1
|
||||||
|
ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-02") }), // paid already
|
||||||
|
ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i1".into() }), // paid: cannot be cancelled
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert_eq!(s.rejected.len() - before, 3);
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i2".into() })]);
|
||||||
|
assert!(s.invoices["i2"].cancelled);
|
||||||
|
let before = s.rejected.len();
|
||||||
|
apply(&mut s, &[ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: None, on: d("2026-03-03") })]);
|
||||||
|
assert_eq!(s.rejected.len() - before, 1, "a cancelled invoice is not paid");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_events_round_trip_and_keep_their_names() {
|
||||||
|
let mut ids = Ids(0);
|
||||||
|
let events = vec![
|
||||||
|
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 150) }),
|
||||||
|
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, Some(21))], true) }),
|
||||||
|
ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-05") }),
|
||||||
|
ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i1".into() }),
|
||||||
|
ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w".into(), amount: Haler(1), on: d("2026-03-05"), note: String::new() }),
|
||||||
|
];
|
||||||
|
let json = serde_json::to_string(&events).unwrap();
|
||||||
|
for name in ["supplier.set", "invoice.issued", "invoice.paid", "invoice.cancelled", "reserve.withdrawn"] {
|
||||||
|
assert!(json.contains(&format!("\"type\":\"{name}\"")), "{name}");
|
||||||
|
}
|
||||||
|
let back: Vec<Event> = serde_json::from_str(&json).unwrap();
|
||||||
|
assert_eq!(back, events);
|
||||||
|
// Replaying the log twice gives the same state.
|
||||||
|
assert_eq!(State::replay(&events), State::replay(&back));
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
//! Day-2 mandatory test: QR Platba. Generated SPAYD strings match the format, and only valid Czech accounts
|
||||||
|
//! get one.
|
||||||
|
|
||||||
|
use fiscus_ledger::pay::{spayd, Iban, PayError};
|
||||||
|
use fiscus_ledger::Haler;
|
||||||
|
|
||||||
|
const IBAN: &str = "CZ6508000000192000145399";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_iban_is_checked_by_mod_97() {
|
||||||
|
assert_eq!(Iban::parse(IBAN).unwrap().as_str(), IBAN);
|
||||||
|
assert_eq!(Iban::parse("cz65 0800 0000 1920 0014 5399").unwrap().as_str(), IBAN);
|
||||||
|
for bad in [
|
||||||
|
"CZ6608000000192000145399", // check digits
|
||||||
|
"CZ650800000019200014539", // too short
|
||||||
|
"CZ65080000001920001453991", // too long
|
||||||
|
"SK3112000000198742637541", // valid, but not Czech
|
||||||
|
"CZ65 0800 0000 1920 0014 539X",
|
||||||
|
"",
|
||||||
|
] {
|
||||||
|
assert!(Iban::parse(bad).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_czech_account_number_becomes_its_iban() {
|
||||||
|
assert_eq!(Iban::parse("19-2000145399/0800").unwrap().as_str(), IBAN);
|
||||||
|
assert_eq!(Iban::parse("2000145399/0800").unwrap().as_str(), "CZ7908000000002000145399");
|
||||||
|
for bad in [
|
||||||
|
"19-2000145398/0800", // the number's mod 11
|
||||||
|
"18-2000145399/0800", // the prefix's mod 11
|
||||||
|
"2000145399/080",
|
||||||
|
"2000145399",
|
||||||
|
"1234567-2000145399/0800",
|
||||||
|
] {
|
||||||
|
assert!(Iban::parse(bad).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The SPAYD 1.0 grammar for what Fiscus writes: `SPD*1.0` then `KEY:value` pairs separated by `*`, values
|
||||||
|
/// without a raw `*`.
|
||||||
|
fn well_formed(s: &str) -> bool {
|
||||||
|
let mut parts = s.split('*');
|
||||||
|
if parts.next() != Some("SPD") || parts.next() != Some("1.0") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let mut keys = Vec::new();
|
||||||
|
for p in parts {
|
||||||
|
let Some((k, v)) = p.split_once(':') else { return false };
|
||||||
|
if v.is_empty() || !k.bytes().all(|b| b.is_ascii_uppercase() || b == b'-') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
keys.push(k);
|
||||||
|
}
|
||||||
|
keys.first() == Some(&"ACC") && keys.contains(&"AM") && keys.contains(&"CC")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn spayd_strings_match_the_format() {
|
||||||
|
let iban = Iban::parse(IBAN).unwrap();
|
||||||
|
let s = spayd(&iban, Haler(45_000), Some("Marek"), "Pizza, 2.11.", Some("123")).unwrap();
|
||||||
|
assert_eq!(s, "SPD*1.0*ACC:CZ6508000000192000145399*AM:450.00*CC:CZK*RN:Marek*MSG:Pizza, 2.11.*X-VS:123");
|
||||||
|
assert!(well_formed(&s));
|
||||||
|
for amount in [1, 99, 100, 123_456, 999_999_999] {
|
||||||
|
let s = spayd(&iban, Haler(amount), None, "x", None).unwrap();
|
||||||
|
assert!(well_formed(&s), "{s}");
|
||||||
|
let am = s.split('*').find_map(|p| p.strip_prefix("AM:")).unwrap();
|
||||||
|
assert_eq!(am, format!("{}.{:02}", amount / 100, amount % 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_star_in_a_text_never_breaks_the_string_and_texts_are_cut_to_size() {
|
||||||
|
let iban = Iban::parse(IBAN).unwrap();
|
||||||
|
let s = spayd(&iban, Haler(100), Some("A*B"), "1*2", None).unwrap();
|
||||||
|
assert!(s.contains("RN:A%2AB") && s.contains("MSG:1%2A2"), "{s}");
|
||||||
|
assert!(well_formed(&s));
|
||||||
|
let long = "ž".repeat(100);
|
||||||
|
let s = spayd(&iban, Haler(100), Some(&long), &long, None).unwrap();
|
||||||
|
let msg = s.split('*').find_map(|p| p.strip_prefix("MSG:")).unwrap();
|
||||||
|
let rn = s.split('*').find_map(|p| p.strip_prefix("RN:")).unwrap();
|
||||||
|
assert_eq!((msg.chars().count(), rn.chars().count()), (60, 35));
|
||||||
|
// `%2A` is never cut in half.
|
||||||
|
let s = spayd(&iban, Haler(100), None, &"*".repeat(30), None).unwrap();
|
||||||
|
let msg = s.split('*').find_map(|p| p.strip_prefix("MSG:")).unwrap();
|
||||||
|
assert!(msg.len() <= 60 && msg.len() % 3 == 0, "{msg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn what_cannot_be_paid_is_an_error() {
|
||||||
|
let iban = Iban::parse(IBAN).unwrap();
|
||||||
|
assert_eq!(spayd(&iban, Haler(0), None, "x", None), Err(PayError::Amount));
|
||||||
|
assert_eq!(spayd(&iban, Haler(-100), None, "x", None), Err(PayError::Amount));
|
||||||
|
assert_eq!(spayd(&iban, Haler(1_000_000_000), None, "x", None), Err(PayError::Amount));
|
||||||
|
for vs in ["", "12345678901", "12a"] {
|
||||||
|
assert_eq!(spayd(&iban, Haler(100), None, "x", Some(vs)), Err(PayError::VariableSymbol), "{vs}");
|
||||||
|
}
|
||||||
|
assert_eq!(spayd(&iban, Haler(100), None, "a\nb", None), Err(PayError::Text));
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
//! Day 2: what a shared budget's log holds. `payment.shared` carries the effective payment and nothing of
|
||||||
|
//! its origin's details; the budget's members see it and can split it; unsharing takes it out again.
|
||||||
|
|
||||||
|
use fiscus_ledger::share::shared_payment;
|
||||||
|
use fiscus_ledger::split::Share;
|
||||||
|
use fiscus_ledger::{Date, Event, EventBody, Glyph, Haler, State, Timestamp};
|
||||||
|
|
||||||
|
fn d(s: &str) -> Date {
|
||||||
|
s.parse().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ev(id: &str, body: EventBody) -> Event {
|
||||||
|
Event::new(id, Timestamp(0), body)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn personal() -> Vec<Event> {
|
||||||
|
vec![
|
||||||
|
ev("e1", EventBody::BudgetCreated { budget: "b-home".into(), name: "Home".into(), limit: Haler(1_000_000) }),
|
||||||
|
ev("e2", EventBody::BudgetCreated { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(500_000) }),
|
||||||
|
ev(
|
||||||
|
"e3",
|
||||||
|
EventBody::PaymentCaptured {
|
||||||
|
payment: "p1".into(),
|
||||||
|
amount: Haler(-45_000),
|
||||||
|
date: d("2026-11-02"),
|
||||||
|
merchant: "Pension Lipno".into(),
|
||||||
|
card: Some("Visa 1234".into()),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
ev("e4", EventBody::PaymentCategorised { payment: "p1".into(), category: "travel".into() }),
|
||||||
|
ev("e5", EventBody::PaymentAssigned { payment: "p1".into(), budget: "b-trip".into() }),
|
||||||
|
ev(
|
||||||
|
"e6",
|
||||||
|
EventBody::PaymentAdded {
|
||||||
|
payment: "p2".into(),
|
||||||
|
amount: Haler(-12_000),
|
||||||
|
date: d("2026-11-02"),
|
||||||
|
merchant: "Lekarna".into(),
|
||||||
|
category: None,
|
||||||
|
note: Some("private".into()),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shared_payment_is_made_only_for_a_payment_in_that_budget() {
|
||||||
|
let s = State::replay(&personal());
|
||||||
|
let body = shared_payment(&s, "p1", "b-trip").expect("p1 is in the trip budget");
|
||||||
|
assert_eq!(
|
||||||
|
body,
|
||||||
|
EventBody::PaymentShared {
|
||||||
|
payment: "p1".into(),
|
||||||
|
budget: "b-trip".into(),
|
||||||
|
amount: Haler(-45_000),
|
||||||
|
date: d("2026-11-02"),
|
||||||
|
merchant: "Pension Lipno".into(),
|
||||||
|
category: Some("travel".into()),
|
||||||
|
glyph: Glyph::Captured,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
let json = serde_json::to_string(&body).unwrap();
|
||||||
|
assert!(!json.contains("Visa") && !json.contains("1234"), "the card stays home: {json}");
|
||||||
|
assert!(shared_payment(&s, "p2", "b-trip").is_none(), "p2 is in the default budget, not the trip");
|
||||||
|
assert!(shared_payment(&s, "p1", "b-home").is_none());
|
||||||
|
assert!(shared_payment(&s, "nope", "b-trip").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shared_log() -> Vec<Event> {
|
||||||
|
let s = State::replay(&personal());
|
||||||
|
vec![
|
||||||
|
ev("g1", EventBody::BudgetCreated { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(500_000) }),
|
||||||
|
ev("g2", shared_payment(&s, "p1", "b-trip").unwrap()),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn members_see_the_shared_payment_in_the_budget() {
|
||||||
|
let s = State::replay(&shared_log());
|
||||||
|
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||||
|
let p = s.effective_payment("p1").unwrap();
|
||||||
|
assert_eq!((p.amount, p.glyph, p.budget.as_deref(), p.category.as_deref()), (Haler(-45_000), Glyph::Captured, Some("b-trip"), Some("travel")));
|
||||||
|
assert_eq!(p.card, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_shared_payment_can_be_split_and_unshared_until_it_is() {
|
||||||
|
let mut log = shared_log();
|
||||||
|
log.push(ev("g3", EventBody::PaymentUnshared { payment: "p1".into(), budget: "b-trip".into() }));
|
||||||
|
let s = State::replay(&log);
|
||||||
|
assert!(s.rejected.is_empty() && s.effective_payment("p1").is_none(), "unshared: gone from the budget");
|
||||||
|
|
||||||
|
let mut log = shared_log();
|
||||||
|
let shares = vec![
|
||||||
|
Share { person: "me".into(), name: "Me".into(), amount: Haler(-22_500) },
|
||||||
|
Share { person: "anna".into(), name: "Anna".into(), amount: Haler(-22_500) },
|
||||||
|
];
|
||||||
|
log.push(ev("g3", EventBody::SplitCreated { split: "s1".into(), payment: "p1".into(), payer: "me".into(), shares }));
|
||||||
|
log.push(ev("g4", EventBody::PaymentUnshared { payment: "p1".into(), budget: "b-trip".into() }));
|
||||||
|
let s = State::replay(&log);
|
||||||
|
assert_eq!(s.rejected.len(), 1, "a split payment stays shared");
|
||||||
|
assert!(s.effective_payment("p1").is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sharing_into_a_budget_the_log_does_not_have_is_rejected() {
|
||||||
|
let s = State::replay(&personal());
|
||||||
|
let s2 = State::replay(&[ev("g2", shared_payment(&s, "p1", "b-trip").unwrap())]);
|
||||||
|
assert_eq!(s2.rejected.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_an_explicit_assignment_shares_a_payment_never_the_default_budget() {
|
||||||
|
// A person whose only budget is a shared one: their unassigned payments fall to it as the default, but
|
||||||
|
// that never makes them shared.
|
||||||
|
let log = vec![
|
||||||
|
ev("e1", EventBody::BudgetCreated { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(500_000) }),
|
||||||
|
ev("e2", EventBody::PaymentCaptured { payment: "p1".into(), amount: Haler(-5_000), date: d("2026-11-02"), merchant: "Kavarna".into(), card: None }),
|
||||||
|
];
|
||||||
|
let s = State::replay(&log);
|
||||||
|
assert_eq!(s.effective_payment("p1").unwrap().budget.as_deref(), Some("b-trip"), "the default budget");
|
||||||
|
assert!(shared_payment(&s, "p1", "b-trip").is_none(), "not assigned, so not shared");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_shared_budget_in_the_personal_log_is_never_the_default() {
|
||||||
|
let log = vec![
|
||||||
|
ev("e1", EventBody::BudgetShared { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(500_000) }),
|
||||||
|
ev("e2", EventBody::PaymentCaptured { payment: "p1".into(), amount: Haler(-5_000), date: d("2026-11-02"), merchant: "Kavarna".into(), card: None }),
|
||||||
|
ev("e3", EventBody::BudgetCreated { budget: "b-home".into(), name: "Home".into(), limit: Haler(1_000_000) }),
|
||||||
|
ev("e4", EventBody::PaymentAssigned { payment: "p1".into(), budget: "b-trip".into() }),
|
||||||
|
];
|
||||||
|
let s = State::replay(&log);
|
||||||
|
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||||
|
assert_eq!(s.default_budget.as_deref(), Some("b-home"));
|
||||||
|
assert_eq!(s.budgets["b-trip"].name, "Trip");
|
||||||
|
assert!(shared_payment(&s, "p1", "b-trip").is_some(), "assigned explicitly");
|
||||||
|
let dup = ev("e5", EventBody::BudgetShared { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(1) });
|
||||||
|
let mut log2 = log.clone();
|
||||||
|
log2.push(dup);
|
||||||
|
assert_eq!(State::replay(&log2).rejected.len(), 1);
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
//! Day-2 mandatory tests: splits always sum exactly to the total and the remainder rule is deterministic;
|
||||||
|
//! `split.created` / `split.settled` refuse anything that does not add up; a share link shows exactly one
|
||||||
|
//! person's share, and nothing once it is settled, expired or unknown.
|
||||||
|
|
||||||
|
use fiscus_ledger::pay::Iban;
|
||||||
|
use fiscus_ledger::split::{split_equal, Person, Share};
|
||||||
|
use fiscus_ledger::{Date, Event, EventBody, Haler, Settlement, State, Timestamp};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
fn d(s: &str) -> Date {
|
||||||
|
s.parse().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn people(ids: &[&str]) -> Vec<Person> {
|
||||||
|
ids.iter().map(|i| Person { id: (*i).into(), name: format!("Name {i}") }).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ev(id: &str, body: EventBody) -> Event {
|
||||||
|
Event::new(id, Timestamp(0), body)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn paid(amount: i64) -> Vec<Event> {
|
||||||
|
vec![ev(
|
||||||
|
"e-pay",
|
||||||
|
EventBody::PaymentAdded {
|
||||||
|
payment: "p1".into(),
|
||||||
|
amount: Haler(amount),
|
||||||
|
date: d("2026-11-02"),
|
||||||
|
merchant: "Pizzeria Uno".into(),
|
||||||
|
category: None,
|
||||||
|
note: None,
|
||||||
|
},
|
||||||
|
)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn created(shares: Vec<Share>) -> Event {
|
||||||
|
ev("e-split", EventBody::SplitCreated { split: "s1".into(), payment: "p1".into(), payer: "me".into(), shares })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn share(person: &str, amount: i64) -> Share {
|
||||||
|
Share { person: person.into(), name: format!("Name {person}"), amount: Haler(amount) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rejected_reason(log: &[Event]) -> Option<String> {
|
||||||
|
State::replay(log).rejected.last().map(|r| r.reason.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#[test]
|
||||||
|
fn shares_always_sum_exactly_to_the_total(total in -10_000_000_000i64..10_000_000_000, n in 1usize..12) {
|
||||||
|
let ids: Vec<String> = (0..n).map(|i| format!("p{i}")).collect();
|
||||||
|
let ps: Vec<Person> = ids.iter().map(|i| Person { id: i.clone(), name: i.clone() }).collect();
|
||||||
|
let shares = split_equal(Haler(total), &ps).unwrap();
|
||||||
|
prop_assert_eq!(shares.len(), n);
|
||||||
|
prop_assert_eq!(shares.iter().map(|s| s.amount.0).sum::<i64>(), total);
|
||||||
|
let max = shares.iter().map(|s| s.amount.0.abs()).max().unwrap();
|
||||||
|
let min = shares.iter().map(|s| s.amount.0.abs()).min().unwrap();
|
||||||
|
prop_assert!(max - min <= 1, "equal shares differ by at most one haléř");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_remainder_does_not_depend_on_the_order_people_were_picked(total in -1_000_000i64..1_000_000, seed in any::<u64>()) {
|
||||||
|
let ids = ["anna", "bara", "cyril", "dana", "eva"];
|
||||||
|
let mut shuffled = ids.to_vec();
|
||||||
|
// A deterministic shuffle from the seed.
|
||||||
|
let mut s = seed;
|
||||||
|
for i in (1..shuffled.len()).rev() {
|
||||||
|
s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||||
|
shuffled.swap(i, (s >> 33) as usize % (i + 1));
|
||||||
|
}
|
||||||
|
prop_assert_eq!(split_equal(Haler(total), &people(&ids)).unwrap(), split_equal(Haler(total), &people(&shuffled)).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_leftover_hal_go_to_the_first_people_by_id() {
|
||||||
|
let shares = split_equal(Haler(-100), &people(&["cyril", "anna", "bara"])).unwrap();
|
||||||
|
let got: Vec<(&str, i64)> = shares.iter().map(|s| (s.person.as_str(), s.amount.0)).collect();
|
||||||
|
assert_eq!(got, vec![("anna", -34), ("bara", -33), ("cyril", -33)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_person_picked_twice_counts_once_and_nobody_is_an_error() {
|
||||||
|
let shares = split_equal(Haler(-90), &people(&["anna", "bara", "anna"])).unwrap();
|
||||||
|
assert_eq!(shares.len(), 2);
|
||||||
|
assert!(split_equal(Haler(-90), &[]).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_split_that_adds_up_is_accepted() {
|
||||||
|
let mut log = paid(-1000);
|
||||||
|
log.push(created(vec![share("me", -334), share("anna", -333), share("bara", -333)]));
|
||||||
|
let s = State::replay(&log);
|
||||||
|
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||||
|
assert_eq!(s.splits["s1"].shares.len(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_split_that_does_not_add_up_is_rejected() {
|
||||||
|
for (shares, why) in [
|
||||||
|
(vec![share("me", -500), share("anna", -499)], "sum"),
|
||||||
|
(vec![share("me", -1001), share("anna", 1)], "sign"),
|
||||||
|
(vec![share("me", -500), share("me", -500)], "twice"),
|
||||||
|
(vec![share("anna", -500), share("bara", -500)], "payer"),
|
||||||
|
(vec![], "nobody"),
|
||||||
|
] {
|
||||||
|
let mut log = paid(-1000);
|
||||||
|
log.push(created(shares));
|
||||||
|
let s = State::replay(&log);
|
||||||
|
assert_eq!(s.rejected.len(), 1, "{why}: {:?}", s.rejected);
|
||||||
|
assert!(s.splits.is_empty(), "{why}: half-applied");
|
||||||
|
}
|
||||||
|
// A payment in (money received) is not split, and a split needs its payment.
|
||||||
|
let mut log = paid(1000);
|
||||||
|
log.push(created(vec![share("me", 500), share("anna", 500)]));
|
||||||
|
assert!(rejected_reason(&log).is_some());
|
||||||
|
assert!(rejected_reason(&[created(vec![share("me", -1)])]).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn settling_is_once_per_person_and_never_the_payer() {
|
||||||
|
let mut log = paid(-1000);
|
||||||
|
log.push(created(vec![share("me", -500), share("anna", -500)]));
|
||||||
|
let settle = |id: &str, person: &str| ev(id, EventBody::SplitSettled { split: "s1".into(), person: person.into(), how: Settlement::Qr });
|
||||||
|
log.push(settle("e-s1", "anna"));
|
||||||
|
assert!(State::replay(&log).rejected.is_empty());
|
||||||
|
for (id, person) in [("e-s2", "anna"), ("e-s3", "me"), ("e-s4", "cyril")] {
|
||||||
|
let mut l = log.clone();
|
||||||
|
l.push(settle(id, person));
|
||||||
|
assert!(rejected_reason(&l).is_some(), "{person} settled");
|
||||||
|
}
|
||||||
|
assert!(State::replay(&log).splits["s1"].settled.contains_key("anna"));
|
||||||
|
}
|
||||||
|
|
||||||
|
const LINK: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90";
|
||||||
|
const OTHER: &str = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
|
||||||
|
|
||||||
|
fn with_link() -> Vec<Event> {
|
||||||
|
let mut log = paid(-1000);
|
||||||
|
log.push(created(vec![share("me", -334), share("anna", -333), share("bara", -333)]));
|
||||||
|
log.push(ev("e-acc", EventBody::AccountSet { iban: "CZ6508000000192000145399".into(), name: "Marek Novak".into() }));
|
||||||
|
log.push(ev(
|
||||||
|
"e-link",
|
||||||
|
EventBody::ShareLinkCreated { link: LINK.into(), split: "s1".into(), person: "anna".into(), expires: d("2026-12-02") },
|
||||||
|
));
|
||||||
|
log
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_share_link_shows_exactly_one_persons_share() {
|
||||||
|
let s = State::replay(&with_link());
|
||||||
|
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||||
|
let v = s.share_view(LINK, d("2026-11-03")).expect("open");
|
||||||
|
assert_eq!(v.name, "Name anna");
|
||||||
|
assert_eq!(v.amount, Haler(333));
|
||||||
|
assert_eq!(v.merchant, "Pizzeria Uno");
|
||||||
|
assert_eq!(v.date, d("2026-11-02"));
|
||||||
|
assert_eq!(v.spayd.as_deref(), Some("SPD*1.0*ACC:CZ6508000000192000145399*AM:3.33*CC:CZK*RN:Marek Novak*MSG:Pizzeria Uno 2.11.2026"));
|
||||||
|
// Everything the page can show is in this one struct; serialise it and look for the others.
|
||||||
|
let all = serde_json::to_string(&v).unwrap();
|
||||||
|
for leak in ["bara", "Name me", "334", "-1000", "10,00", "s1", "p1"] {
|
||||||
|
assert!(!all.contains(leak), "{leak} leaked into {all}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_settled_expired_or_unknown_link_shows_nothing() {
|
||||||
|
let s = State::replay(&with_link());
|
||||||
|
assert!(s.share_view(OTHER, d("2026-11-03")).is_none(), "unknown");
|
||||||
|
assert!(s.share_view(LINK, d("2026-12-03")).is_none(), "expired");
|
||||||
|
assert!(s.share_view(LINK, d("2026-12-02")).is_some(), "the last day is still open");
|
||||||
|
let mut log = with_link();
|
||||||
|
log.push(ev("e-set", EventBody::SplitSettled { split: "s1".into(), person: "anna".into(), how: Settlement::Marked }));
|
||||||
|
assert!(State::replay(&log).share_view(LINK, d("2026-11-03")).is_none(), "settled");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_link_for_the_payer_or_a_stranger_is_rejected() {
|
||||||
|
for person in ["me", "cyril"] {
|
||||||
|
let mut log = with_link();
|
||||||
|
log.pop();
|
||||||
|
log.push(ev(
|
||||||
|
"e-link",
|
||||||
|
EventBody::ShareLinkCreated { link: LINK.into(), split: "s1".into(), person: person.into(), expires: d("2026-12-02") },
|
||||||
|
));
|
||||||
|
assert!(rejected_reason(&log).is_some(), "{person}");
|
||||||
|
}
|
||||||
|
let mut log = with_link();
|
||||||
|
log.push(ev("e-link2", EventBody::ShareLinkCreated { link: "short".into(), split: "s1".into(), person: "bara".into(), expires: d("2026-12-02") }));
|
||||||
|
assert!(rejected_reason(&log).is_some(), "a link is a SHA-256 in hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_account_must_be_a_valid_czech_iban() {
|
||||||
|
assert!(Iban::parse("CZ6508000000192000145399").is_ok());
|
||||||
|
let bad = ev("e-acc", EventBody::AccountSet { iban: "CZ6608000000192000145399".into(), name: "X".into() });
|
||||||
|
assert!(rejected_reason(&[bad]).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn capture_tokens_are_hashes_and_revoke_once() {
|
||||||
|
let add = ev("e-t1", EventBody::CaptureTokenAdded { token: OTHER.into(), name: "Mark's iPhone".into(), kind: fiscus_ledger::CaptureKind::Iphone });
|
||||||
|
let revoke = |id: &str| ev(id, EventBody::CaptureTokenRevoked { token: OTHER.into() });
|
||||||
|
let s = State::replay(std::slice::from_ref(&add));
|
||||||
|
assert!(s.capture_token_active(OTHER));
|
||||||
|
let s = State::replay(&[add.clone(), revoke("e-t2")]);
|
||||||
|
assert!(!s.capture_token_active(OTHER) && s.rejected.is_empty());
|
||||||
|
assert!(rejected_reason(&[add.clone(), revoke("e-t2"), revoke("e-t3")]).is_some());
|
||||||
|
let raw = ev("e-t1", EventBody::CaptureTokenAdded { token: "my-secret-token".into(), name: "x".into(), kind: fiscus_ledger::CaptureKind::Android });
|
||||||
|
assert!(rejected_reason(&[raw]).is_some(), "only a hash is ever stored");
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# 02 — Capture, splits, QR Platba, sharing (day 2)
|
||||||
|
|
||||||
|
Written before the code. Everything here is pure, like day 1: no I/O, no clock, no randomness. The app
|
||||||
|
(Fiscus `docs/02_phones_sharing.md`) moves these events through Fundamentum; the core only defines them,
|
||||||
|
applies them and checks them.
|
||||||
|
|
||||||
|
## New events (`fiscus-ledger`)
|
||||||
|
|
||||||
|
A **personal log** (your own devices, the Fundamentum *self group*) holds every event. A **shared budget**
|
||||||
|
is a log of its own (one MLS group): its members see exactly what was put into it, nothing else.
|
||||||
|
|
||||||
|
| Event | Where | Effect |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| `payment.shared` | shared budget | a member put one payment into this budget: `payment, budget, amount, date, merchant, category, origin`. Creates the payment in this log, or reassigns it after an unshare |
|
||||||
|
| `payment.unshared` | shared budget | takes it out again (it stays in the log, unassigned) |
|
||||||
|
| `budget.shared` | personal | a shared budget (created here or joined): like `budget.created`, but **never the default budget** |
|
||||||
|
| `split.created` | either | `split, payment, payer, shares: [{person, name, amount}]`. Rejected unless the shares sum **exactly** to the payment's amount, every amount has the payment's sign, people are unique, and the payer is one of them |
|
||||||
|
| `split.settled` | either | `split, person, how` (`qr`, `marked`). Rejected for an unknown split or person, the payer, or a second settlement |
|
||||||
|
| `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.
|
||||||
|
|
||||||
|
**Only an explicit `payment.assigned` shares a payment** (`share::shared_payment`). A payment that falls into
|
||||||
|
a budget as the default is never sent anywhere.
|
||||||
|
|
||||||
|
### The split rule
|
||||||
|
`split_equal(total, people)`: the people are **sorted by id and deduplicated first**, then split with
|
||||||
|
equal weights by the day-1 largest-remainder `split()`. Every device computes the same shares in whatever
|
||||||
|
order the people were picked, and the shares always sum to the total. The leftover haléře go to the first
|
||||||
|
people in id order.
|
||||||
|
|
||||||
|
A **share link** is open while its split is not settled for that person and `today <= expires`
|
||||||
|
(`share_link_open`). The page shows exactly `ShareView { name, amount, merchant, date, spayd }` and nothing else.
|
||||||
|
|
||||||
|
## `fiscus-capture`: what the phones send
|
||||||
|
Both are **hostile input**. Each yields a `Capture { amount (an outflow, negative), date, merchant, card }`
|
||||||
|
or a typed error, never a partial payment.
|
||||||
|
|
||||||
|
**The iPhone Shortcut post.** We write the Shortcut, so this is our format, not a bank's. It is a JSON object
|
||||||
|
with exactly `amount`, `merchant`, `card`, `time`, plus an optional `currency`. Anything else is an error.
|
||||||
|
- `amount`: a positive number, or a string in the form Shortcuts writes in Czech or English (`129`,
|
||||||
|
`129,5`, `1 234,50`, `129.00`, optionally `Kč`/`CZK` before or after). It is parsed from its text, never
|
||||||
|
as a float. `currency`, if present, must be `CZK`.
|
||||||
|
- `merchant`: 1–200 characters, no control characters. `card`: 0–60 characters.
|
||||||
|
- `time`: ISO 8601 with an offset (`2026-11-03T14:05:00+01:00`); the payment's date is the local date in it.
|
||||||
|
- At most 4 KiB.
|
||||||
|
*(assumption)* Apple's exact `amount` text is checked against the first real post.
|
||||||
|
|
||||||
|
**Android bank notifications.** `recognise(app, title, text, selected)`:
|
||||||
|
1. If `app` is not one of the bank apps the person selected → `NotSelected`. The listener calls this only for
|
||||||
|
selected apps; the core checks again.
|
||||||
|
2. Otherwise each template **for that app** is tried in turn. A template is literal text with `{amount}`,
|
||||||
|
`{merchant}`, `{card}` and `{_}` holes, matched exactly (no regexes, no fuzziness).
|
||||||
|
3. No template matches → `Unknown`. The app counts it and shows the count in Settings; it is **never
|
||||||
|
guessed**.
|
||||||
|
|
||||||
|
**The template registry is empty**: no bank notification samples exist yet. Templates are written only from
|
||||||
|
real samples in `fixtures/notifications/<bank>/` (see `fixtures/README.md`). The engine is tested with
|
||||||
|
synthetic templates that live only in the tests.
|
||||||
|
|
||||||
|
## QR Platba (`fiscus_ledger::pay`)
|
||||||
|
- `Iban::parse` takes `CZ65 0800 0000 1920 0014 5399` or a Czech account `19-2000145399/0800`. Both checks
|
||||||
|
are strict: the IBAN's mod-97, and for a Czech account the weighted mod-11 of the prefix and the number.
|
||||||
|
Only CZ accounts (24 characters).
|
||||||
|
- `spayd(iban, amount, message, vs)` gives `SPD*1.0*ACC:<IBAN>*AM:<amount>*CC:CZK*MSG:<message>[*X-VS:<vs>]`.
|
||||||
|
- The amount must be positive. It is written from haléře with two decimals (`450.00`), never through a float.
|
||||||
|
- The message is at most 60 characters, and `*` is written as `%2A`.
|
||||||
|
- The variable symbol is 1–10 digits.
|
||||||
|
|
||||||
|
## Household duplicates (`fiscus-insight`)
|
||||||
|
`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.
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# 03 — Invoices and the tax reserve (v1.1)
|
||||||
|
|
||||||
|
`fiscus-ledger::invoice`: issuing invoices (faktury) from the ledger, finding them paid on a statement, and
|
||||||
|
setting a share of each paid one aside for tax. Pure like the rest: no clock, no randomness; dates and ids are
|
||||||
|
parameters.
|
||||||
|
|
||||||
|
## The supplier
|
||||||
|
`supplier.set` names who issues invoices: name, address (1–4 lines), IČO, DIČ, whether they are a VAT payer, a
|
||||||
|
registration line for the invoice, and the reserve: the thousandths of each paid invoice's amount without VAT
|
||||||
|
set aside for income tax and insurance (0–600, so 0–60 %). A VAT payer must have a DIČ. The latest
|
||||||
|
`supplier.set` counts from then on; an invoice keeps the supplier it was issued under, so changing the reserve
|
||||||
|
never changes an invoice issued before.
|
||||||
|
|
||||||
|
IČO: 8 digits, the last the weighted mod-11 check of the first seven. DIČ: `CZ` and 8–10 digits.
|
||||||
|
|
||||||
|
## An invoice
|
||||||
|
`invoice.issued` carries the whole invoice: id, number, issue and due dates, the taxable-supply date (DUZP, on a
|
||||||
|
VAT invoice only), the customer, 1–50 lines, and the budget its payment goes into (`None`: the default one).
|
||||||
|
|
||||||
|
- **Number = variable symbol.** `YYYYNNNN`: the year it was issued and its place in that year
|
||||||
|
(`State::next_invoice_number(year)`). A number is used once. The payment is matched by it.
|
||||||
|
- **A line:** text (1–200), quantity in thousandths (0,001–1 000 000), unit (≤ 10), unit price in haléře,
|
||||||
|
and on a VAT invoice a rate of 21, 12 or 0 %. Its amount is `quantity × price`, rounded half away from
|
||||||
|
zero to the haléř.
|
||||||
|
- **VAT:** per rate, from the base: the base of a rate is the sum of its lines, its VAT `base × rate / 100`
|
||||||
|
rounded once (§ 37 ZDPH). Not per line.
|
||||||
|
- **Total:** 0,01–9 999 999,99 CZK, what QR Platba carries. `State::invoice_spayd` gives the QR Platba of an
|
||||||
|
unpaid invoice: its total, `X-VS` its number, to the account set by `account.set`.
|
||||||
|
|
||||||
|
Every rule is checked when the event is applied; an invoice that breaks one is rejected and changes nothing.
|
||||||
|
|
||||||
|
## Paid
|
||||||
|
`invoice.paid { invoice, payment, on }`: `payment` is the statement line that paid it, or `None` for one marked
|
||||||
|
paid by hand. A line pays one invoice, only of the invoice's exact total, not before the invoice was issued.
|
||||||
|
|
||||||
|
`plan_invoice_payments(state, ids, at)` is what the app runs after an import. For each unpaid invoice, the
|
||||||
|
earliest statement line whose amount is its total and whose variable symbol is its number (leading zeros do
|
||||||
|
not count) pays it: `invoice.paid`, then `payment.categorised` → `income` (unless the person chose a category),
|
||||||
|
then `payment.assigned` → the invoice's budget. Nothing is guessed: a line of another amount, or without the
|
||||||
|
symbol, stays for the person to look at. Run twice, the second plan is empty.
|
||||||
|
|
||||||
|
## The reserve
|
||||||
|
When an invoice is paid, `reserve = VAT + round(net × reserve‰ / 1000)` is set aside: a VAT payer's VAT in full
|
||||||
|
(it is the state's), and the reserve share of the rest. `State::reserve_balance()` is everything set aside less
|
||||||
|
`reserve.withdrawn` (the tax or insurance paid from it), which can never take more than the reserve holds.
|
||||||
|
|
||||||
|
## Cancelling
|
||||||
|
`invoice.cancelled` cancels an unpaid invoice. A paid one stays; a credit note (opravný daňový doklad) is not
|
||||||
|
built yet.
|
||||||
|
|
||||||
|
| Event | Effect |
|
||||||
|
|:--|:--|
|
||||||
|
| `supplier.set` | the supplier from now on |
|
||||||
|
| `invoice.issued` | a new invoice, checked, with its totals |
|
||||||
|
| `invoice.paid` | paid by a statement line or by hand; the reserve set aside |
|
||||||
|
| `invoice.cancelled` | an unpaid invoice withdrawn |
|
||||||
|
| `reserve.withdrawn` | money out of the reserve, at most its balance |
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Bank notification samples (Android)
|
||||||
|
|
||||||
|
Real, **redacted** notifications only, one folder per bank (`fixtures/notifications/<bank>/`), one JSON file
|
||||||
|
per notification:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"app": "cz.example.bank",
|
||||||
|
"title": "the notification's title, exactly",
|
||||||
|
"text": "the notification's text, exactly",
|
||||||
|
"expected": { "amount": -12950, "merchant": "ALBERT", "card": "*1234" }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`expected` is `null` for a notification from the bank app that is not a card payment (a balance, a login, an
|
||||||
|
incoming transfer); it must stay unknown. `amount` is in haléře, negative for a payment.
|
||||||
|
|
||||||
|
Redact names, card numbers and balances, but keep every other character: spaces, no-break spaces, the
|
||||||
|
currency sign and the punctuation are exactly what a template is written from. 3–5 payments per bank app,
|
||||||
|
plus one or two that are not payments. A template (`fiscus-capture/src/notification.rs`, `TEMPLATES`) is
|
||||||
|
written only from the samples here; a bank app with no samples is unsupported, and its notifications are
|
||||||
|
counted as unrecognised, never guessed.
|
||||||
Reference in New Issue
Block a user