Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 03dc2061f9 | |||
| 4e8e80efb4 | |||
| 0f93d0ecb5 | |||
| 95a8a8965b | |||
| 0068d4b69a |
Generated
+4
-4
@@ -139,7 +139,7 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-capture"
|
||||
version = "0.3.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"fiscus-ledger",
|
||||
"proptest",
|
||||
@@ -150,7 +150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-insight"
|
||||
version = "0.3.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"fiscus-ledger",
|
||||
"serde",
|
||||
@@ -159,7 +159,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-ledger"
|
||||
version = "0.3.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -169,7 +169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiscus-statement"
|
||||
version = "0.3.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"fiscus-ledger",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "2"
|
||||
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.3.0"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
|
||||
|
||||
@@ -6,10 +6,10 @@ subscription / price-change / trial detection and a seeded month-end forecast. N
|
||||
|
||||
| Crate | |
|
||||
|:--|:--|
|
||||
| `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning |
|
||||
| `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning, invoices, category plans |
|
||||
| `fiscus-statement` | strict CSV, Czech amount and date fields, decoding; bank parsers only from real samples |
|
||||
| `fiscus-insight` | subscriptions, cancel kits, the forecast |
|
||||
| `fiscus-insight` | subscriptions, cancel kits, the forecast, spending, the month against its plan, the month in numbers |
|
||||
|
||||
Design: [docs/01_core.md](docs/01_core.md). Tests: `cargo test --workspace`.
|
||||
Design: [docs/01_core.md](docs/01_core.md), [02](docs/02_capture_sharing.md), [03 invoices](docs/03_invoices.md), [04 plans and statistics](docs/04_plans_stats.md). Tests: `cargo test --workspace`.
|
||||
|
||||
Licence: MPL-2.0.
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
//! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge,
|
||||
//! how to cancel, and whether the month will stay under its limit. Pure: "today" and seeds are parameters.
|
||||
//! how to cancel, whether the month will stay under its limit, where the money went and how it compares with
|
||||
//! your plan. Pure: "today" and seeds are parameters.
|
||||
|
||||
pub mod cancel;
|
||||
pub mod forecast;
|
||||
pub mod household;
|
||||
pub mod plan;
|
||||
pub mod spending;
|
||||
pub mod stats;
|
||||
pub mod subscriptions;
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
//! The month against your plan: for each category, what you meant to spend (`category.planned`), what you
|
||||
//! spent, what is left, and whether you are ahead of the pace the plan allows by today. Only your own payments
|
||||
//! count, as in the forecast; what other members of a shared budget spend is theirs.
|
||||
|
||||
use crate::spending::{between, outflows};
|
||||
use fiscus_ledger::categories::{self, NOT_PLANNABLE};
|
||||
use fiscus_ledger::date::days_in_month;
|
||||
use fiscus_ledger::{Category, Date, Haler, State};
|
||||
use serde::Serialize;
|
||||
|
||||
/// How a planned category is doing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Pace {
|
||||
/// Below 90 % of what the plan allows by today (or, for a past month, within the plan).
|
||||
Under,
|
||||
OnPace,
|
||||
/// Above 110 % of what the plan allows by today, not over the plan yet.
|
||||
Ahead,
|
||||
/// More than the whole month's plan.
|
||||
Over,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct PlanRow {
|
||||
pub category: Category,
|
||||
pub planned: Option<Haler>,
|
||||
pub spent: Haler,
|
||||
/// Planned less spent; negative when over. `None` without a plan.
|
||||
pub left: Option<Haler>,
|
||||
/// Spent of the plan in thousandths, capped at 1000 (for a bar); 0 without a plan.
|
||||
pub permille: u32,
|
||||
/// `None` without a plan, and for a month that has not begun.
|
||||
pub pace: Option<Pace>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct MonthPlan {
|
||||
/// The 1st of the month.
|
||||
pub month: Date,
|
||||
/// The categories with a plan this month, in the app's order, then those spent on without a plan, the
|
||||
/// largest first.
|
||||
pub rows: Vec<PlanRow>,
|
||||
/// All the plans of the month together.
|
||||
pub planned: Haler,
|
||||
/// Everything spent this month.
|
||||
pub spent: Haler,
|
||||
/// Of that, spent in categories without a plan.
|
||||
pub unplanned: Haler,
|
||||
}
|
||||
|
||||
fn pace(planned: Haler, spent: Haler, month: Date, today: Date) -> Option<Pace> {
|
||||
if today < month {
|
||||
return None;
|
||||
}
|
||||
if spent > planned {
|
||||
return Some(Pace::Over);
|
||||
}
|
||||
if today > month.month_end() {
|
||||
return Some(Pace::Under);
|
||||
}
|
||||
let (y, m, day) = today.ymd();
|
||||
let allowed = i128::from(planned.0) * i128::from(day) / i128::from(days_in_month(y, m));
|
||||
let spent = i128::from(spent.0) * 100;
|
||||
Some(if spent > allowed * 110 {
|
||||
Pace::Ahead
|
||||
} else if spent < allowed * 90 {
|
||||
Pace::Under
|
||||
} else {
|
||||
Pace::OnPace
|
||||
})
|
||||
}
|
||||
|
||||
/// The month of `month` against its plans. For this month, what is spent up to `today`; a later month has
|
||||
/// nothing spent yet. `None` when a sum would not fit.
|
||||
pub fn month_plan(state: &State, month: Date, today: Date) -> Option<MonthPlan> {
|
||||
let start = month.month_start();
|
||||
let end = start.month_end().min(today);
|
||||
let spent_by = if end < start { Default::default() } else { outflows(&between(state, start, end))? };
|
||||
let spent_in = |c: &str| spent_by.get(c).copied().unwrap_or(Haler::ZERO);
|
||||
|
||||
let mut rows = Vec::new();
|
||||
for (category, _) in state.categories() {
|
||||
let Some(planned) = state.plan_for(&category, start) else { continue };
|
||||
let spent = spent_in(&category);
|
||||
let permille = (i128::from(spent.0) * 1000 / i128::from(planned.0)).clamp(0, 1000) as u32;
|
||||
rows.push(PlanRow { left: Some(planned.checked_sub(spent).ok()?), planned: Some(planned), permille, pace: pace(planned, spent, start, today), spent, category });
|
||||
}
|
||||
let mut extra: Vec<(&Category, &Haler)> = spent_by.iter().filter(|(c, _)| state.plan_for(c, start).is_none()).collect();
|
||||
extra.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
|
||||
let unplanned = Haler::sum(extra.iter().map(|(_, a)| **a)).ok()?;
|
||||
rows.extend(extra.into_iter().map(|(c, a)| PlanRow { category: c.clone(), planned: None, spent: *a, left: None, permille: 0, pace: None }));
|
||||
|
||||
Some(MonthPlan {
|
||||
month: start,
|
||||
planned: Haler::sum(rows.iter().filter_map(|r| r.planned)).ok()?,
|
||||
spent: Haler::sum(spent_by.values().copied()).ok()?,
|
||||
unplanned,
|
||||
rows,
|
||||
})
|
||||
}
|
||||
|
||||
/// A plan from your history: for each category you can plan, the average of what you spent on it over the last
|
||||
/// three complete months, rounded **up** to whole hundreds of crowns. Only months since your first payment
|
||||
/// count, so a ledger a month old is not divided by three. Categories you spent nothing on are left out.
|
||||
pub fn suggest(state: &State, today: Date) -> Vec<(Category, Haler)> {
|
||||
let this_month = today.month_start();
|
||||
let Some(first) = state.effective_payments().first().map(|p| p.date.month_start()) else { return Vec::new() };
|
||||
let months: Vec<Date> = (1..=3).map(|n| this_month.add_months(-n)).filter(|m| *m >= first).collect();
|
||||
let Some(oldest) = months.last().copied() else { return Vec::new() };
|
||||
let Some(spent) = outflows(&between(state, oldest, this_month.add_days(-1))) else { return Vec::new() };
|
||||
let hundred = 10_000i128;
|
||||
let mut out = Vec::new();
|
||||
for (category, _) in state.categories() {
|
||||
if NOT_PLANNABLE.contains(&category.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(total) = spent.get(&category).filter(|t| t.0 > 0) else { continue };
|
||||
// Both are positive: rounding up is (a + b - 1) / b.
|
||||
let n = months.len() as i128;
|
||||
let avg = (i128::from(total.0) + n - 1) / n;
|
||||
let up = (avg + hundred - 1) / hundred * hundred;
|
||||
match i64::try_from(up) {
|
||||
Ok(v) if Haler(v) <= categories::MAX_PLAN => out.push((category, Haler(v))),
|
||||
_ => out.push((category, categories::MAX_PLAN)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//! One definition of spending, for every screen: money out of your own payments, as positive amounts, by
|
||||
//! category. Money between your own accounts (`transfers`) is not spending; a payment nobody categorised counts
|
||||
//! as `uncategorised`. Every sum is checked: `None` when one would not fit, never a wrong number.
|
||||
|
||||
use fiscus_ledger::categories::{TRANSFERS, UNCATEGORISED};
|
||||
use fiscus_ledger::{Category, Date, EffectivePayment, Haler, State};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The payments dated in `[from, to]`, a confirmed pair as one.
|
||||
pub fn between(state: &State, from: Date, to: Date) -> Vec<EffectivePayment> {
|
||||
state.effective_payments().into_iter().filter(|p| p.date >= from && p.date <= to).collect()
|
||||
}
|
||||
|
||||
/// The category a payment counts under.
|
||||
pub fn category_of(p: &EffectivePayment) -> &str {
|
||||
p.category.as_deref().unwrap_or(UNCATEGORISED)
|
||||
}
|
||||
|
||||
/// A payment that is spending: money out, not a transfer.
|
||||
pub fn is_spending(p: &EffectivePayment) -> bool {
|
||||
p.amount.0 < 0 && category_of(p) != TRANSFERS
|
||||
}
|
||||
|
||||
/// Money out by category, positive.
|
||||
pub fn outflows(payments: &[EffectivePayment]) -> Option<BTreeMap<Category, Haler>> {
|
||||
let mut by: BTreeMap<Category, Haler> = BTreeMap::new();
|
||||
for p in payments.iter().filter(|p| is_spending(p)) {
|
||||
let slot = by.entry(category_of(p).to_string()).or_insert(Haler::ZERO);
|
||||
*slot = slot.checked_add(p.amount.checked_neg().ok()?).ok()?;
|
||||
}
|
||||
Some(by)
|
||||
}
|
||||
|
||||
/// Money in, not a transfer.
|
||||
pub fn inflow(payments: &[EffectivePayment]) -> Option<Haler> {
|
||||
Haler::sum(payments.iter().filter(|p| p.amount.0 > 0 && category_of(p) != TRANSFERS).map(|p| p.amount)).ok()
|
||||
}
|
||||
|
||||
/// Each part's share of their sum in thousandths, by the largest remainder: the shares add up to exactly 1000
|
||||
/// whenever the sum is above zero (all zeros otherwise). A tie goes to the earlier part, so callers order the
|
||||
/// parts first. A negative part counts as zero.
|
||||
pub fn permille(parts: &[Haler]) -> Vec<u32> {
|
||||
let parts: Vec<i128> = parts.iter().map(|h| i128::from(h.0.max(0))).collect();
|
||||
let total: i128 = parts.iter().sum();
|
||||
if total <= 0 {
|
||||
return vec![0; parts.len()];
|
||||
}
|
||||
let mut shares: Vec<u32> = parts.iter().map(|p| (p * 1000 / total) as u32).collect();
|
||||
let mut left = 1000 - shares.iter().sum::<u32>();
|
||||
let mut order: Vec<usize> = (0..parts.len()).collect();
|
||||
// Largest remainder first; the earlier part on a tie (the sort is stable).
|
||||
order.sort_by_key(|&i| std::cmp::Reverse(parts[i] * 1000 % total));
|
||||
for i in order {
|
||||
if left == 0 {
|
||||
break;
|
||||
}
|
||||
shares[i] += 1;
|
||||
left -= 1;
|
||||
}
|
||||
shares
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shares_always_add_up_to_a_thousand() {
|
||||
let h = |v: &[i64]| v.iter().map(|&x| Haler(x)).collect::<Vec<_>>();
|
||||
assert_eq!(permille(&h(&[1, 1, 1])), [334, 333, 333]);
|
||||
assert_eq!(permille(&h(&[2, 1])), [667, 333]);
|
||||
assert_eq!(permille(&h(&[0, 0])), [0, 0]);
|
||||
assert_eq!(permille(&h(&[])), Vec::<u32>::new());
|
||||
assert_eq!(permille(&h(&[i64::MAX, i64::MAX, 1])), [500, 500, 0]);
|
||||
assert_eq!(permille(&h(&[5, -3])), [1000, 0]);
|
||||
for n in 1..40i64 {
|
||||
let parts: Vec<Haler> = (1..=n).map(|i| Haler(i * 7919 % 1013 + 1)).collect();
|
||||
assert_eq!(permille(&parts).iter().sum::<u32>(), 1000, "{n} parts");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! A month in numbers: where the money went (the slices of a pie, in thousandths that add up to 1000), money
|
||||
//! in and out, the last six months, how far along you are compared with last month by the same day, the
|
||||
//! merchants you paid most, and what the subscriptions took. Your own payments; transfers are not spending.
|
||||
|
||||
use crate::spending::{between, inflow, is_spending, outflows, permille};
|
||||
use crate::subscriptions::Insight;
|
||||
use fiscus_ledger::{Category, Date, Haler, State};
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The pie shows this many categories; the rest are one slice.
|
||||
pub const SLICES: usize = 7;
|
||||
/// Months in the bars, this one included.
|
||||
pub const MONTHS: i32 = 6;
|
||||
pub const TOP_MERCHANTS: usize = 5;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct Slice {
|
||||
/// `None`: every other category, together.
|
||||
pub category: Option<Category>,
|
||||
pub amount: Haler,
|
||||
/// Its share of the month's spending; the slices add up to 1000.
|
||||
pub permille: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct MonthTotal {
|
||||
/// The 1st of the month.
|
||||
pub month: Date,
|
||||
pub out: Haler,
|
||||
pub inflow: Haler,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct MerchantTotal {
|
||||
pub key: String,
|
||||
/// As the latest payment to it wrote it.
|
||||
pub merchant: String,
|
||||
pub amount: Haler,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct MonthStats {
|
||||
/// The 1st of the month.
|
||||
pub month: Date,
|
||||
/// Largest first; at most [`SLICES`], then the rest.
|
||||
pub slices: Vec<Slice>,
|
||||
pub out: Haler,
|
||||
pub inflow: Haler,
|
||||
/// In less out; negative when more went out.
|
||||
pub net: Haler,
|
||||
/// The last [`MONTHS`] months, oldest first, ending with this one.
|
||||
pub months: Vec<MonthTotal>,
|
||||
/// Spent last month up to the same day of the month (all of last month for a past month).
|
||||
pub same_day_last_month: Haler,
|
||||
/// Largest first.
|
||||
pub top_merchants: Vec<MerchantTotal>,
|
||||
/// What the subscriptions charged this month.
|
||||
pub subscriptions: Haler,
|
||||
/// Their share of the month's spending, in thousandths (at most 1000).
|
||||
pub subscriptions_permille: u32,
|
||||
}
|
||||
|
||||
/// `[start, end]` of `month`, cut at `today`; `None` for a month that has not begun.
|
||||
fn span(month: Date, today: Date) -> Option<(Date, Date)> {
|
||||
let start = month.month_start();
|
||||
(start <= today).then(|| (start, start.month_end().min(today)))
|
||||
}
|
||||
|
||||
fn spent(state: &State, from: Date, to: Date) -> Option<Haler> {
|
||||
Haler::sum(outflows(&between(state, from, to))?.into_values()).ok()
|
||||
}
|
||||
|
||||
/// The month of `month`, up to `today`. `insight` is `analyse(state, today)`. `None` for a month that has not
|
||||
/// begun, or when a sum would not fit.
|
||||
pub fn month_stats(state: &State, insight: &Insight, month: Date, today: Date) -> Option<MonthStats> {
|
||||
let (start, end) = span(month, today)?;
|
||||
let payments = between(state, start, end);
|
||||
let by = outflows(&payments)?;
|
||||
let out = Haler::sum(by.values().copied()).ok()?;
|
||||
let inflow = inflow(&payments)?;
|
||||
|
||||
let mut parts: Vec<(Category, Haler)> = by.into_iter().collect();
|
||||
parts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
let mut slices: Vec<(Option<Category>, Haler)> = parts.iter().take(SLICES).map(|(c, a)| (Some(c.clone()), *a)).collect();
|
||||
if parts.len() > SLICES {
|
||||
slices.push((None, Haler::sum(parts[SLICES..].iter().map(|(_, a)| *a)).ok()?));
|
||||
}
|
||||
let shares = permille(&slices.iter().map(|(_, a)| *a).collect::<Vec<_>>());
|
||||
|
||||
let mut months = Vec::new();
|
||||
for n in (0..MONTHS).rev() {
|
||||
let m = start.add_months(-n);
|
||||
let (from, to) = span(m, today)?;
|
||||
let ps = between(state, from, to);
|
||||
months.push(MonthTotal { month: m, out: Haler::sum(outflows(&ps)?.into_values()).ok()?, inflow: crate::spending::inflow(&ps)? });
|
||||
}
|
||||
|
||||
let last = start.add_months(-1);
|
||||
let last_end = if end == start.month_end() { last.month_end() } else { last.add_days(end.ymd().2 as i32 - 1).min(last.month_end()) };
|
||||
let same_day_last_month = spent(state, last, last_end)?;
|
||||
|
||||
let mut merchants: BTreeMap<&str, MerchantTotal> = BTreeMap::new();
|
||||
for p in payments.iter().filter(|p| is_spending(p) && !p.merchant_key.is_empty()) {
|
||||
let t = merchants.entry(&p.merchant_key).or_insert(MerchantTotal { key: p.merchant_key.clone(), merchant: String::new(), amount: Haler::ZERO, count: 0 });
|
||||
t.merchant = p.merchant.clone();
|
||||
t.amount = t.amount.checked_add(p.amount.checked_neg().ok()?).ok()?;
|
||||
t.count += 1;
|
||||
}
|
||||
let mut top_merchants: Vec<MerchantTotal> = merchants.into_values().collect();
|
||||
top_merchants.sort_by(|a, b| b.amount.cmp(&a.amount).then(a.key.cmp(&b.key)));
|
||||
top_merchants.truncate(TOP_MERCHANTS);
|
||||
|
||||
// A subscription charge counts once, by the payment it was, and only when it is spending this month.
|
||||
let spending_ids: BTreeMap<&str, Haler> = payments
|
||||
.iter()
|
||||
.filter(|p| is_spending(p))
|
||||
.flat_map(|p| [Some(p.id.as_str()), p.line.as_deref(), p.captured.as_deref()].into_iter().flatten().map(move |id| (id, p.amount)))
|
||||
.collect();
|
||||
let mut charged = std::collections::BTreeSet::new();
|
||||
let mut subscriptions = Haler::ZERO;
|
||||
for c in insight.subscriptions.iter().flat_map(|s| &s.charges) {
|
||||
let Some(paid) = spending_ids.get(c.payment.as_str()) else { continue };
|
||||
if charged.insert(c.payment.as_str()) {
|
||||
subscriptions = subscriptions.checked_add(paid.checked_neg().ok()?).ok()?;
|
||||
}
|
||||
}
|
||||
let subscriptions_permille = if out.0 > 0 { (i128::from(subscriptions.0) * 1000 / i128::from(out.0)).clamp(0, 1000) as u32 } else { 0 };
|
||||
|
||||
Some(MonthStats {
|
||||
month: start,
|
||||
slices: slices.into_iter().zip(shares).map(|((category, amount), permille)| Slice { category, amount, permille }).collect(),
|
||||
net: inflow.checked_sub(out).ok()?,
|
||||
out,
|
||||
inflow,
|
||||
months,
|
||||
same_day_last_month,
|
||||
top_merchants,
|
||||
subscriptions,
|
||||
subscriptions_permille,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Spending, the month against its plan, and a month in numbers: one definition of spending everywhere,
|
||||
//! shares that always add up to 1000, the pace by today, and the suggested plan rounded up.
|
||||
|
||||
use fiscus_insight::plan::{month_plan, suggest, Pace};
|
||||
use fiscus_insight::stats::{month_stats, SLICES};
|
||||
use fiscus_insight::subscriptions::analyse;
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
/// A ledger from `(date, amount in haléře, merchant, category)` added by hand, then `extra` events.
|
||||
fn ledger(payments: &[(&str, i64, &str, &str)], extra: Vec<EventBody>) -> State {
|
||||
let mut log: Vec<Event> = payments
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (date, amount, merchant, category))| {
|
||||
Event::new(
|
||||
format!("e{i}"),
|
||||
Timestamp(0),
|
||||
EventBody::PaymentAdded {
|
||||
payment: format!("p{i}"),
|
||||
amount: Haler(*amount),
|
||||
date: d(date),
|
||||
merchant: merchant.to_string(),
|
||||
category: (!category.is_empty()).then(|| category.to_string()),
|
||||
note: None,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
log.extend(extra.into_iter().enumerate().map(|(i, b)| Event::new(format!("x{i}"), Timestamp(0), b)));
|
||||
let s = State::replay(&log);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
s
|
||||
}
|
||||
|
||||
fn planned(category: &str, amount: i64, from: &str) -> EventBody {
|
||||
EventBody::CategoryPlanned { category: category.into(), amount: Haler(amount), from: d(from) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_month_against_its_plan() {
|
||||
let today = d("2026-11-15");
|
||||
let s = ledger(
|
||||
&[
|
||||
("2026-11-02", -300_000, "Albert", "groceries"),
|
||||
("2026-11-10", -150_000, "Lidl", "groceries"),
|
||||
("2026-11-12", -250_000, "Lokál", "eating-out"),
|
||||
("2026-11-14", -40_000, "Trafika", ""),
|
||||
("2026-11-03", -1_000_000, "To savings", "transfers"),
|
||||
("2026-11-05", 5_000_000, "Salary", "income"),
|
||||
("2026-11-20", -90_000, "Albert", "groceries"),
|
||||
("2026-10-30", -999_999, "Albert", "groceries"),
|
||||
("2026-11-08", -60_000, "Shell", "transport"),
|
||||
],
|
||||
vec![planned("groceries", 1_000_000, "2026-10-01"), planned("eating-out", 200_000, "2026-11-01"), planned("transport", 400_000, "2026-11-01")],
|
||||
);
|
||||
let p = month_plan(&s, today, today).unwrap();
|
||||
assert_eq!(p.month, d("2026-11-01"));
|
||||
type Row<'a> = (&'a str, Option<i64>, i64, Option<i64>, u32, Option<Pace>);
|
||||
let rows: Vec<Row> =
|
||||
p.rows.iter().map(|r| (r.category.as_str(), r.planned.map(|x| x.0), r.spent.0, r.left.map(|x| x.0), r.permille, r.pace)).collect();
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
// Half the month gone (15 of 30 days): 4 500 of 10 000 is 90 % of the pace, on pace.
|
||||
("groceries", Some(1_000_000), 450_000, Some(550_000), 450, Some(Pace::OnPace)),
|
||||
("eating-out", Some(200_000), 250_000, Some(-50_000), 1000, Some(Pace::Over)),
|
||||
("transport", Some(400_000), 60_000, Some(340_000), 150, Some(Pace::Under)),
|
||||
// Spent with no plan: uncategorised. Transfers, income, the future and last month do not count.
|
||||
("uncategorised", None, 40_000, None, 0, None),
|
||||
]
|
||||
);
|
||||
assert_eq!((p.planned, p.spent, p.unplanned), (Haler(1_600_000), Haler(800_000), Haler(40_000)));
|
||||
|
||||
// A past month is done: within the plan is Under, past it Over. A month to come has nothing spent.
|
||||
let oct = month_plan(&s, d("2026-10-01"), today).unwrap();
|
||||
assert_eq!(oct.rows[0].pace, Some(Pace::Under));
|
||||
assert_eq!(oct.rows[0].spent, Haler(999_999));
|
||||
let dec = month_plan(&s, d("2026-12-01"), today).unwrap();
|
||||
assert_eq!(dec.spent, Haler::ZERO);
|
||||
assert!(dec.rows.iter().all(|r| r.pace.is_none()), "not begun");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ahead_of_the_pace() {
|
||||
let s = ledger(&[("2026-11-03", -500_000, "Albert", "groceries")], vec![planned("groceries", 1_000_000, "2026-11-01")]);
|
||||
// 5 days of 30 allow 1 666,66; 5 000 is far ahead, but not over the month's 10 000.
|
||||
assert_eq!(month_plan(&s, d("2026-11-05"), d("2026-11-05")).unwrap().rows[0].pace, Some(Pace::Ahead));
|
||||
assert_eq!(month_plan(&s, d("2026-11-30"), d("2026-11-30")).unwrap().rows[0].pace, Some(Pace::Under));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_suggested_plan_is_the_average_rounded_up_to_hundreds() {
|
||||
let s = ledger(
|
||||
&[
|
||||
("2026-08-10", -100_000, "Albert", "groceries"),
|
||||
("2026-09-10", -200_000, "Albert", "groceries"),
|
||||
("2026-10-10", -300_001, "Albert", "groceries"),
|
||||
("2026-10-11", -12_345, "Lokál", "eating-out"),
|
||||
("2026-10-12", -50_000, "To savings", "transfers"),
|
||||
("2026-10-13", -7_000, "?", ""),
|
||||
("2026-11-01", -999_999, "Albert", "groceries"),
|
||||
("2026-07-01", -5_000_000, "Albert", "groceries"),
|
||||
],
|
||||
vec![],
|
||||
);
|
||||
// Aug, Sep, Oct (not this November, not July): 6 000,01 / 3 = 2 000,0034 → 2 100.
|
||||
let got = suggest(&s, d("2026-11-15"));
|
||||
assert_eq!(got, [("groceries".to_string(), Haler(210_000)), ("eating-out".to_string(), Haler(10_000))]);
|
||||
|
||||
// A ledger only a month old is not divided by three.
|
||||
let young = ledger(&[("2026-10-10", -150_000, "Albert", "groceries")], vec![]);
|
||||
assert_eq!(suggest(&young, d("2026-11-15")), [("groceries".to_string(), Haler(150_000))]);
|
||||
assert!(suggest(&State::default(), d("2026-11-15")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_month_in_numbers() {
|
||||
let today = d("2026-11-15");
|
||||
let mut payments = vec![
|
||||
("2026-11-02", -300_000, "Albert Praha", "groceries"),
|
||||
("2026-11-09", -100_000, "ALBERT PRAHA", "groceries"),
|
||||
("2026-11-03", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
|
||||
("2026-11-04", -50_000, "Lokál", "eating-out"),
|
||||
("2026-11-05", 4_000_000, "Salary", "income"),
|
||||
("2026-11-06", -1_000_000, "To savings", "transfers"),
|
||||
("2026-11-07", -33_100, "", "fun"),
|
||||
("2026-10-02", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
|
||||
("2026-09-02", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
|
||||
("2026-10-10", -200_000, "Albert Praha", "groceries"),
|
||||
("2026-10-20", -500_000, "Albert Praha", "groceries"),
|
||||
("2026-11-20", -77_700, "Albert Praha", "groceries"),
|
||||
];
|
||||
// Eight more categories, so the pie has a slice for the rest.
|
||||
let more = ["transport", "housing", "utilities", "shopping", "health", "kids", "travel", "gifts"];
|
||||
for (i, c) in more.iter().enumerate() {
|
||||
payments.push(("2026-11-10", -(1_000 + i as i64), "Shop", c));
|
||||
}
|
||||
let s = ledger(&payments, vec![]);
|
||||
let st = month_stats(&s, &analyse(&s, today), today, today).unwrap();
|
||||
|
||||
assert_eq!(st.month, d("2026-11-01"));
|
||||
let spent = 300_000 + 100_000 + 16_900 + 50_000 + 33_100 + (1_000..1_008).sum::<i64>();
|
||||
assert_eq!((st.out, st.inflow, st.net), (Haler(spent), Haler(4_000_000), Haler(4_000_000 - spent)));
|
||||
assert_eq!(st.slices.len(), SLICES + 1);
|
||||
assert_eq!(st.slices.iter().map(|s| s.permille).sum::<u32>(), 1000, "the slices add up");
|
||||
assert_eq!(st.slices[0].category.as_deref(), Some("groceries"));
|
||||
assert_eq!(st.slices[0].amount, Haler(400_000));
|
||||
assert!(st.slices.last().unwrap().category.is_none(), "the rest");
|
||||
assert!(st.slices.windows(2).take(SLICES - 1).all(|w| w[0].amount >= w[1].amount), "largest first");
|
||||
|
||||
// Six months, oldest first; October in full, November up to today.
|
||||
let months: Vec<(Date, i64)> = st.months.iter().map(|m| (m.month, m.out.0)).collect();
|
||||
assert_eq!(months.len(), 6);
|
||||
assert_eq!(months[0].0, d("2026-06-01"));
|
||||
assert_eq!(months[4], (d("2026-10-01"), 716_900));
|
||||
assert_eq!(months[5], (d("2026-11-01"), spent));
|
||||
// By 15 October: the Spotify charge and the first Albert.
|
||||
assert_eq!(st.same_day_last_month, Haler(216_900));
|
||||
|
||||
let top: Vec<(&str, i64, usize)> = st.top_merchants.iter().map(|m| (m.key.as_str(), m.amount.0, m.count)).collect();
|
||||
assert_eq!(top[0], ("albert praha", 400_000, 2), "one merchant however the bank writes it");
|
||||
assert!(top.iter().all(|(k, _, _)| !k.is_empty()), "a payment without a merchant is not a merchant");
|
||||
assert!(top.len() <= 5);
|
||||
|
||||
assert_eq!(st.subscriptions, Haler(16_900));
|
||||
assert_eq!(st.subscriptions_permille, (16_900 * 1000 / spent) as u32);
|
||||
|
||||
// A past month: whole, compared with all of the month before.
|
||||
let oct = month_stats(&s, &analyse(&s, today), d("2026-10-31"), today).unwrap();
|
||||
assert_eq!((oct.out, oct.same_day_last_month), (Haler(716_900), Haler(16_900)));
|
||||
// A month to come has no numbers yet; an empty month is zeros, not nothing.
|
||||
assert!(month_stats(&s, &analyse(&s, today), d("2026-12-01"), today).is_none());
|
||||
let empty = month_stats(&s, &analyse(&s, today), d("2026-03-01"), today).unwrap();
|
||||
assert!(empty.slices.is_empty());
|
||||
assert_eq!((empty.out, empty.subscriptions_permille), (Haler::ZERO, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sum_that_would_not_fit_gives_no_numbers() {
|
||||
let s = ledger(&[("2026-11-02", i64::MIN + 1, "A", "fun"), ("2026-11-03", i64::MIN + 1, "B", "fun")], vec![]);
|
||||
let today = d("2026-11-15");
|
||||
assert!(month_stats(&s, &analyse(&s, today), today, today).is_none());
|
||||
assert!(month_plan(&s, today, today).is_none());
|
||||
}
|
||||
@@ -1,6 +1,15 @@
|
||||
//! The categories the app offers. A category is an id; the label is what the app shows.
|
||||
|
||||
pub const UNCATEGORISED: &str = "uncategorised";
|
||||
/// Money between your own accounts: never spending.
|
||||
pub const TRANSFERS: &str = "transfers";
|
||||
pub const INCOME: &str = "income";
|
||||
|
||||
/// Categories a monthly plan cannot be for: money in, money moved, and money not yet sorted.
|
||||
pub const NOT_PLANNABLE: [&str; 3] = [INCOME, TRANSFERS, UNCATEGORISED];
|
||||
|
||||
/// The most a category's monthly plan can be: 100 000 000 CZK, far from any sum overflowing.
|
||||
pub const MAX_PLAN: crate::money::Haler = crate::money::Haler(10_000_000_000);
|
||||
|
||||
/// `(id, label)` in the order the app lists them.
|
||||
pub const DEFAULT: &[(&str, &str)] = &[
|
||||
@@ -16,8 +25,8 @@ pub const DEFAULT: &[(&str, &str)] = &[
|
||||
("fun", "Fun"),
|
||||
("travel", "Travel"),
|
||||
("gifts", "Gifts"),
|
||||
("income", "Income"),
|
||||
("transfers", "Transfers"),
|
||||
(INCOME, "Income"),
|
||||
(TRANSFERS, "Transfers"),
|
||||
("other", "Other"),
|
||||
(UNCATEGORISED, "Uncategorised"),
|
||||
];
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use crate::date::{Date, Timestamp};
|
||||
use crate::import::StatementLine;
|
||||
use crate::invoice::{Invoice, InvoiceId, Supplier};
|
||||
use crate::money::Haler;
|
||||
use crate::split::Share;
|
||||
use crate::state::Glyph;
|
||||
@@ -141,4 +142,27 @@ pub enum EventBody {
|
||||
/// 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 },
|
||||
/// The most you mean to spend on one category in a month, from the month of `from` (its 1st) on, until a
|
||||
/// later plan for that category replaces it. Zero removes the plan. Personal log only.
|
||||
#[serde(rename = "category.planned")]
|
||||
CategoryPlanned { category: Category, amount: Haler, from: Date },
|
||||
/// A category of your own (an id as [`crate::categories::is_valid`]) and the name the app shows for it.
|
||||
#[serde(rename = "category.created")]
|
||||
CategoryCreated { category: Category, label: String },
|
||||
}
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
//! 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>,
|
||||
}
|
||||
|
||||
/// The language an invoice is printed in, chosen per invoice.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Language {
|
||||
#[default]
|
||||
Cs,
|
||||
En,
|
||||
}
|
||||
|
||||
#[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 the printed invoice is in. Absent in an event: Czech.
|
||||
#[serde(default)]
|
||||
pub language: Language,
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ pub mod categories;
|
||||
pub mod date;
|
||||
pub mod event;
|
||||
pub mod import;
|
||||
pub mod invoice;
|
||||
pub mod matching;
|
||||
pub mod merchant;
|
||||
pub mod money;
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::categories;
|
||||
use crate::date::Date;
|
||||
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
|
||||
use crate::import::StatementLine;
|
||||
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
|
||||
use crate::merchant::merchant_key;
|
||||
use crate::money::Haler;
|
||||
use crate::pay::{spayd, Iban};
|
||||
@@ -142,6 +143,46 @@ pub struct ShareView {
|
||||
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 PlanRecord {
|
||||
/// The 1st of the month the plan counts from.
|
||||
pub from: Date,
|
||||
/// Positive; zero removes the plan.
|
||||
pub amount: Haler,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Withdrawal {
|
||||
pub id: String,
|
||||
pub amount: Haler,
|
||||
pub on: Date,
|
||||
pub note: String,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Rejection {
|
||||
pub event: EventId,
|
||||
@@ -175,6 +216,17 @@ pub struct State {
|
||||
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>,
|
||||
/// Category → its monthly plans, in log order (`category.planned`).
|
||||
pub category_plans: BTreeMap<Category, Vec<PlanRecord>>,
|
||||
/// Your own categories: id → the name shown (`category.created`).
|
||||
pub custom_categories: BTreeMap<Category, String>,
|
||||
pub rejected: Vec<Rejection>,
|
||||
}
|
||||
|
||||
@@ -618,6 +670,92 @@ impl State {
|
||||
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::CategoryPlanned { category, amount, from } => {
|
||||
if !self.category_known(category) || categories::NOT_PLANNABLE.contains(&category.as_str()) {
|
||||
return Err("not a category that can have a plan");
|
||||
}
|
||||
if amount.0 < 0 || *amount > categories::MAX_PLAN {
|
||||
return Err("a plan is 0-100 000 000 CZK");
|
||||
}
|
||||
if from.ymd().2 != 1 {
|
||||
return Err("a plan starts on the 1st of a month");
|
||||
}
|
||||
self.category_plans.entry(category.clone()).or_default().push(PlanRecord { from: *from, amount: *amount, seq });
|
||||
}
|
||||
EventBody::CategoryCreated { category, label } => {
|
||||
if !categories::is_valid(category) {
|
||||
return Err("not a category id");
|
||||
}
|
||||
if self.category_known(category) {
|
||||
return Err("this category exists");
|
||||
}
|
||||
if !name_ok(label, MAX_PERSON) || label.trim() != label {
|
||||
return Err("a category's name must be 1-40 characters");
|
||||
}
|
||||
self.custom_categories.insert(category.clone(), label.clone());
|
||||
}
|
||||
EventBody::SubscriptionsShared { budget, names } => {
|
||||
if !self.budgets.contains_key(budget) {
|
||||
return Err("no such budget");
|
||||
@@ -636,6 +774,61 @@ impl State {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A default category or one of your own.
|
||||
pub fn category_known(&self, id: &str) -> bool {
|
||||
categories::DEFAULT.iter().any(|(d, _)| *d == id) || self.custom_categories.contains_key(id)
|
||||
}
|
||||
|
||||
/// The name the app shows for a category: yours, the default one, or the id itself.
|
||||
pub fn category_label(&self, id: &str) -> String {
|
||||
self.custom_categories.get(id).cloned().unwrap_or_else(|| categories::label(id).to_string())
|
||||
}
|
||||
|
||||
/// Every category the app offers: the default ones in their order, then yours by id.
|
||||
pub fn categories(&self) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = categories::DEFAULT.iter().map(|(id, l)| (id.to_string(), l.to_string())).collect();
|
||||
out.extend(self.custom_categories.iter().map(|(id, l)| (id.clone(), l.clone())));
|
||||
out
|
||||
}
|
||||
|
||||
/// The plan for `category` in the month of `month`: the latest plan from that month or before (by month,
|
||||
/// then log order); `None` without one, or when it was set to zero.
|
||||
pub fn plan_for(&self, category: &str, month: Date) -> Option<Haler> {
|
||||
let start = month.month_start();
|
||||
self.category_plans
|
||||
.get(category)?
|
||||
.iter()
|
||||
.filter(|p| p.from <= start)
|
||||
.max_by_key(|p| (p.from, p.seq))
|
||||
.map(|p| p.amount)
|
||||
.filter(|a| a.0 > 0)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
//! 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, Language, 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,
|
||||
language: Language::Cs,
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invoice_is_printed_in_czech_or_english_and_czech_when_unsaid() {
|
||||
let mut i = invoice("i1", "20260001", "2026-03-01", vec![line("Work", 1_000, 100_000, None)], false);
|
||||
i.language = Language::En;
|
||||
let json = serde_json::to_string(&i).unwrap();
|
||||
assert!(json.contains("\"language\":\"en\""), "{json}");
|
||||
assert_eq!(serde_json::from_str::<Invoice>(&json).unwrap(), i);
|
||||
// An event written without the field reads as Czech.
|
||||
let older = json.replace(",\"language\":\"en\"", "");
|
||||
assert!(!older.contains("language"));
|
||||
assert_eq!(serde_json::from_str::<Invoice>(&older).unwrap().language, Language::Cs);
|
||||
// Anything else is refused.
|
||||
assert!(serde_json::from_str::<Invoice>(&json.replace("\"en\"", "\"de\"")).is_err());
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Category plans and categories of your own: a plan carries forward until a later one replaces it, zero
|
||||
//! removes it, and only a real spending category can have one. Every refusal changes nothing.
|
||||
|
||||
use fiscus_ledger::categories::MAX_PLAN;
|
||||
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
|
||||
|
||||
fn d(s: &str) -> Date {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn plan(id: &str, category: &str, amount: i64, from: &str) -> Event {
|
||||
Event::new(id, Timestamp(0), EventBody::CategoryPlanned { category: category.into(), amount: Haler(amount), from: d(from) })
|
||||
}
|
||||
|
||||
fn created(id: &str, category: &str, label: &str) -> Event {
|
||||
Event::new(id, Timestamp(0), EventBody::CategoryCreated { category: category.into(), label: label.into() })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plan_carries_forward_until_a_later_one_replaces_it() {
|
||||
let s = State::replay(&[plan("p1", "groceries", 800_000, "2026-09-01"), plan("p2", "groceries", 900_000, "2026-11-01"), plan("p3", "eating-out", 200_000, "2026-10-01")]);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
assert_eq!(s.plan_for("groceries", d("2026-08-31")), None, "not before its month");
|
||||
assert_eq!(s.plan_for("groceries", d("2026-09-15")), Some(Haler(800_000)));
|
||||
assert_eq!(s.plan_for("groceries", d("2026-10-31")), Some(Haler(800_000)), "carried forward");
|
||||
assert_eq!(s.plan_for("groceries", d("2026-11-01")), Some(Haler(900_000)));
|
||||
assert_eq!(s.plan_for("groceries", d("2027-06-10")), Some(Haler(900_000)));
|
||||
assert_eq!(s.plan_for("eating-out", d("2026-09-30")), None);
|
||||
assert_eq!(s.plan_for("transport", d("2026-11-01")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_latest_plan_for_a_month_wins_and_zero_removes_it() {
|
||||
// Written later for an earlier month: the plan from November still counts in November.
|
||||
let s = State::replay(&[plan("p1", "groceries", 900_000, "2026-11-01"), plan("p2", "groceries", 700_000, "2026-10-01")]);
|
||||
assert_eq!(s.plan_for("groceries", d("2026-11-20")), Some(Haler(900_000)));
|
||||
assert_eq!(s.plan_for("groceries", d("2026-10-20")), Some(Haler(700_000)));
|
||||
// Two for the same month: the later in the log.
|
||||
let s = State::replay(&[plan("p1", "groceries", 900_000, "2026-11-01"), plan("p2", "groceries", 500_000, "2026-11-01")]);
|
||||
assert_eq!(s.plan_for("groceries", d("2026-11-20")), Some(Haler(500_000)));
|
||||
// Zero from December: no plan from then on.
|
||||
let s = State::replay(&[plan("p1", "groceries", 900_000, "2026-11-01"), plan("p2", "groceries", 0, "2026-12-01")]);
|
||||
assert_eq!(s.plan_for("groceries", d("2026-11-30")), Some(Haler(900_000)));
|
||||
assert_eq!(s.plan_for("groceries", d("2026-12-01")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_spending_category_can_have_a_plan() {
|
||||
for (category, amount, from, why) in [
|
||||
("income", 100, "2026-11-01", "money in"),
|
||||
("transfers", 100, "2026-11-01", "money moved"),
|
||||
("uncategorised", 100, "2026-11-01", "not sorted"),
|
||||
("fuel", 100, "2026-11-01", "an unknown category"),
|
||||
("Groceries", 100, "2026-11-01", "not an id"),
|
||||
("groceries", -1, "2026-11-01", "negative"),
|
||||
("groceries", MAX_PLAN.0 + 1, "2026-11-01", "over 100 million"),
|
||||
("groceries", 100, "2026-11-02", "not the 1st"),
|
||||
] {
|
||||
let s = State::replay(&[plan("p", category, amount, from)]);
|
||||
assert_eq!(s.rejected.len(), 1, "{why}");
|
||||
assert!(s.category_plans.is_empty(), "{why}: nothing kept");
|
||||
}
|
||||
let s = State::replay(&[plan("p", "groceries", MAX_PLAN.0, "2026-11-01")]);
|
||||
assert!(s.rejected.is_empty(), "exactly 100 million is a plan");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn categories_of_your_own() {
|
||||
let s = State::replay(&[created("c1", "fuel", "Fuel"), plan("p1", "fuel", 300_000, "2026-11-01")]);
|
||||
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
|
||||
assert_eq!(s.category_label("fuel"), "Fuel");
|
||||
assert_eq!(s.category_label("groceries"), "Groceries");
|
||||
assert_eq!(s.plan_for("fuel", d("2026-11-03")), Some(Haler(300_000)));
|
||||
let all = s.categories();
|
||||
assert_eq!(all.last().unwrap(), &("fuel".to_string(), "Fuel".to_string()), "yours after the default ones");
|
||||
assert_eq!(all[0].0, "groceries");
|
||||
|
||||
for (event, why) in [
|
||||
(created("c2", "fuel", "Petrol"), "the same id twice"),
|
||||
(created("c2", "groceries", "Food"), "a default category"),
|
||||
(created("c2", "Fuel-2", "Fuel"), "not an id"),
|
||||
(created("c2", "parking", ""), "an empty name"),
|
||||
(created("c2", "parking", " Parking"), "a name with spaces around"),
|
||||
(created("c2", "parking", &"x".repeat(41)), "a long name"),
|
||||
(created("c2", "parking", "Park\ning"), "a control character"),
|
||||
] {
|
||||
let mut t = s.clone();
|
||||
t.apply(&event);
|
||||
assert_eq!(t.rejected.len(), 1, "{why}");
|
||||
assert_eq!(t.custom_categories.len(), 1, "{why}: nothing kept");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_events_round_trip_and_replay_the_same() {
|
||||
let log = vec![created("c1", "fuel", "Fuel"), plan("p1", "fuel", 300_000, "2026-11-01"), plan("p2", "groceries", 900_000, "2026-10-01")];
|
||||
let json = serde_json::to_string(&log).unwrap();
|
||||
for name in ["category.planned", "category.created"] {
|
||||
assert!(json.contains(name), "{name}");
|
||||
}
|
||||
let back: Vec<Event> = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, log);
|
||||
assert_eq!(State::replay(&back), State::replay(&log));
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
# 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, the budget its payment goes into (`None`: the default one), and
|
||||
the language it is printed in: `cs` or `en`, chosen per invoice (absent: Czech).
|
||||
|
||||
- **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,68 @@
|
||||
# 04 — Spending, category plans and the month in numbers (v0.5.0)
|
||||
|
||||
Pure like the rest: `today` and the month are parameters. Money in haléře; every share is whole thousandths.
|
||||
|
||||
## One definition of spending (`fiscus-insight::spending`)
|
||||
Spending is money out of your own payments (a confirmed pair once), as positive amounts, by category. Money
|
||||
between your own accounts (`transfers`) is not spending; a payment nobody categorised counts as `uncategorised`.
|
||||
Money in is positive payments that are not transfers. Every sum is checked: when one would not fit, the answer
|
||||
is `None`, never a wrong number.
|
||||
|
||||
`permille(parts)` gives each part's share in thousandths by the largest remainder, so the shares add up to
|
||||
exactly 1000 whenever there is anything to share (a pie never has a gap or an overlap). A tie goes to the
|
||||
earlier part; callers order the parts first.
|
||||
|
||||
## Category plans (`category.planned`, `fiscus-insight::plan`)
|
||||
`category.planned { category, amount, from }`: the most you mean to spend on a category in a month, from the
|
||||
month of `from` (always the 1st) on, until a later plan for that category replaces it. You plan once; zero
|
||||
removes the plan. `State::plan_for(category, month)` is the plan from that month or before, the latest month
|
||||
first, then the latest in the log.
|
||||
|
||||
A plan is for a spending category only: not `income`, `transfers` or `uncategorised`, and a category the
|
||||
ledger knows (a default one or one of your own). 0 to 100 000 000 CZK.
|
||||
|
||||
Plans are in your personal log and count **your own payments only**, like the forecast. They are never shared:
|
||||
the sharing boundary (`share.rs`, the app's `outgoing`) builds only `payment.shared` and never copies other
|
||||
events.
|
||||
|
||||
`month_plan(state, month, today)`: per planned category, what you spent this month up to today, what is left
|
||||
(negative when over), the spent share of the plan (capped at 1000, for a bar), and the pace:
|
||||
|
||||
| Pace | When |
|
||||
|:--|:--|
|
||||
| Over | spent more than the whole month's plan |
|
||||
| Ahead | more than 110 % of what the plan allows by today (`plan × day / days in month`) |
|
||||
| On pace | 90–110 % |
|
||||
| Under | below 90 %; for a past month, within the plan |
|
||||
|
||||
Then the categories spent on without a plan (largest first), and the month's totals: planned, spent, and the
|
||||
part of it spent without a plan. A month that has not begun has nothing spent and no pace.
|
||||
|
||||
`suggest(state, today)`: a plan from your history. For each category you can plan, the average spent over the
|
||||
last three complete months, rounded **up** to whole hundreds of crowns. Only months since your first payment
|
||||
count, so a ledger one month old is not divided by three.
|
||||
|
||||
## Categories of your own (`category.created`)
|
||||
`category.created { category, label }`: an id as `categories::is_valid` that is not a default category or one
|
||||
you made before, and a name of 1–40 characters (no spaces around it, no control characters). It can be planned
|
||||
and used like a default one. `State::category_label` and `State::categories()` (the default ones in their order,
|
||||
then yours by id) are what the app lists.
|
||||
|
||||
## The month in numbers (`fiscus-insight::stats`)
|
||||
`month_stats(state, insight, month, today)` for a month that has begun (`None` for one to come):
|
||||
- **slices**: spending by category, the largest 7, then the rest as one slice; thousandths that add up to 1000;
|
||||
- **out, in, net** (in less out);
|
||||
- **months**: the last six, oldest first, ending with this one (up to today);
|
||||
- **same day last month**: spent last month up to the same day (all of it for a past month);
|
||||
- **top merchants**: the 5 you paid most, by merchant key (however the bank writes the name), with the latest
|
||||
name and how many payments; a payment without a merchant is not a merchant;
|
||||
- **subscriptions**: what the subscriptions `analyse` found charged this month, and their share of spending.
|
||||
|
||||
## Tests
|
||||
`fiscus-ledger/tests/plans.rs` (5): a plan carries forward, the latest for a month wins, zero removes it,
|
||||
every refusal (income, transfers, uncategorised, unknown, not an id, negative, over the limit, not the 1st)
|
||||
changes nothing, categories of your own and their refusals, the events round-trip and replay the same.
|
||||
`fiscus-insight/tests/stats.rs` (5) and `spending.rs` (1): the month against its plan with every pace, the
|
||||
suggested plan, the month in numbers, shares that always add up to 1000, and no numbers when a sum would not
|
||||
fit. Three deliberate mistakes (transfers as spending, a plan before its month, no largest remainder) each fail
|
||||
them.
|
||||
Reference in New Issue
Block a user