Compare commits

..

6 Commits

Author SHA1 Message Date
mnovak 507eb62216 [fiscus-capture] Receipts: the fields every Czech receipt shows, read from an OCR's words; payment.receipt_attached
fiscus_capture::receipt::read takes the OCR's lines (words with boxes and confidence in thousandths) and finds
the total, date and time, IČO (check digit), DIČ and the shop's name by their labels, never a shop's layout;
unsure words mark their field, the shop is always to check; bounded, control characters dropped, a proptest.
The phone's post takes a receipt (source receipt, ico, dic). The ledger gains payment.receipt_attached (the
payment keeps its merchant and key), known_shop and receipt_match (exactly one candidate or none).
docs/07_receipts.md; fixtures/receipts/ waits for redacted samples. v0.9.0.
2026-11-17 19:40:08 +01:00
mnovak c6805aea8f [repo] Merge: feature/shared-projects (project.shared and project.unshared, one budget at a time; v0.8.0, PR #10) 2026-11-16 03:17:54 +01:00
mnovak 59bbeaf9de [ledger] Shared projects: project.shared and project.unshared, one budget at a time, with their checks; v0.8.0 2026-11-16 03:17:42 +01:00
mnovak a3a50615bb [repo] Merge: feature/projects (projects: budget lines, payments in projects, tasks, phases, time and invoices, the project medals; v0.7.0, PR #9) 2026-11-11 21:08:01 +01:00
mnovak 65899bc170 [insight] Projects: spent by line and unplanned, income without VAT and never twice, profit and margin, progress, the forecast, late, time by task and week, billed and unbilled; Project on budget and Finished on time medals 2026-11-11 21:07:42 +01:00
mnovak 3245341ebc [ledger] Projects: project.created/changed/status_set/line_set/phase_set, payments put into projects and project rules, tasks, time and invoices from projects, with their checks; v0.7.0 2026-11-11 21:07:41 +01:00
25 changed files with 2161 additions and 13 deletions
Generated
+4 -4
View File
@@ -139,7 +139,7 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]] [[package]]
name = "fiscus-capture" name = "fiscus-capture"
version = "0.6.0" version = "0.9.0"
dependencies = [ dependencies = [
"fiscus-ledger", "fiscus-ledger",
"proptest", "proptest",
@@ -150,7 +150,7 @@ dependencies = [
[[package]] [[package]]
name = "fiscus-insight" name = "fiscus-insight"
version = "0.6.0" version = "0.9.0"
dependencies = [ dependencies = [
"fiscus-ledger", "fiscus-ledger",
"serde", "serde",
@@ -159,7 +159,7 @@ dependencies = [
[[package]] [[package]]
name = "fiscus-ledger" name = "fiscus-ledger"
version = "0.6.0" version = "0.9.0"
dependencies = [ dependencies = [
"proptest", "proptest",
"serde", "serde",
@@ -169,7 +169,7 @@ dependencies = [
[[package]] [[package]]
name = "fiscus-statement" name = "fiscus-statement"
version = "0.6.0" version = "0.9.0"
dependencies = [ dependencies = [
"encoding_rs", "encoding_rs",
"fiscus-ledger", "fiscus-ledger",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"] members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
[workspace.package] [workspace.package]
version = "0.6.0" version = "0.9.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"
+3 -3
View File
@@ -6,10 +6,10 @@ subscription / price-change / trial detection and a seeded month-end forecast. N
| Crate | | | Crate | |
|:--|:--| |:--|:--|
| `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning, invoices, category plans, savings goals and challenges | | `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning, invoices, category plans, savings goals and challenges, projects (lines, tasks, phases, time) |
| `fiscus-statement` | strict CSV, Czech amount and date fields, decoding; bank parsers only from real samples | | `fiscus-statement` | strict CSV, Czech amount and date fields, decoding; bank parsers only from real samples |
| `fiscus-insight` | subscriptions, cancel kits, the forecast, spending, the month against its plan, the month in numbers, goals and their ways to save, medals | | `fiscus-insight` | subscriptions, cancel kits, the forecast, spending, the month against its plan, the month in numbers, goals and their ways to save, medals, projects against their budgets |
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), [05 goals and rewards](docs/05_goals_rewards.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), [05 goals and rewards](docs/05_goals_rewards.md), [06 projects](docs/06_projects.md). Tests: `cargo test --workspace`.
Licence: MPL-2.0. Licence: MPL-2.0.
+4 -1
View File
@@ -3,9 +3,10 @@
pub mod amount; pub mod amount;
pub mod notification; pub mod notification;
pub mod receipt;
pub mod shortcut; pub mod shortcut;
use fiscus_ledger::{Date, Haler, Timestamp}; use fiscus_ledger::{Date, Haler, ReceiptInfo, Timestamp};
/// One card payment a phone saw: an outflow, so `amount` is negative. /// One card payment a phone saw: an outflow, so `amount` is negative.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
@@ -15,6 +16,8 @@ pub struct Capture {
pub at: Timestamp, pub at: Timestamp,
pub merchant: String, pub merchant: String,
pub card: Option<String>, pub card: Option<String>,
/// A receipt read on the phone (`"source": "receipt"`): the shop is the merchant, with its IČO and DIČ.
pub receipt: Option<ReceiptInfo>,
} }
/// 1–200 characters, no control characters. /// 1–200 characters, no control characters.
+1 -1
View File
@@ -175,5 +175,5 @@ fn capture(fields: &Fields, date: Date, at: Timestamp) -> Option<Capture> {
if card.is_some_and(|c| !card_ok(c)) { if card.is_some_and(|c| !card_ok(c)) {
return None; return None;
} }
Some(Capture { amount, date, at, merchant: merchant.to_string(), card: card.filter(|c| !c.is_empty()).map(str::to_string) }) Some(Capture { amount, date, at, merchant: merchant.to_string(), card: card.filter(|c| !c.is_empty()).map(str::to_string), receipt: None })
} }
+368
View File
@@ -0,0 +1,368 @@
//! A receipt's text as an OCR read it (lines of words, each with its box and confidence; docs/07_receipts.md).
//! What every Czech receipt must show is found by its label, never by a shop's layout: the total (`Celkem`,
//! `K úhradě`…), the date and time, the IČO (with its check digit) and DIČ, and the shop's name above them.
//!
//! Hostile input: bounded in size, control characters dropped, and a field is either read whole or not at all.
//! A field read from words the OCR was not sure of is marked `sure: false`, for you to check; the shop's name is
//! always to check. Amounts are read from their text into haléře, never through a float, and confidence is in
//! thousandths.
use crate::amount;
use fiscus_ledger::invoice::{dic_ok, ico_ok};
use fiscus_ledger::{Date, Haler};
/// At most this many lines, words in a line, and characters in a word.
pub const MAX_LINES: usize = 600;
pub const MAX_WORDS: usize = 120;
pub const MAX_WORD: usize = 80;
/// A word read with at least this confidence (thousandths) counts as sure.
pub const SURE: u16 = 800;
/// A box in the image's pixels (as the OCR gives it, upright).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BBox {
pub x: u32,
pub y: u32,
pub w: u32,
pub h: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Word {
pub text: String,
/// 0-1000.
pub confidence: u16,
pub bbox: BBox,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Line {
pub words: Vec<Word>,
}
/// One field read, where it was on the image, and whether every word of it was read surely.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Field<T> {
pub value: T,
pub sure: bool,
pub boxes: Vec<BBox>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Receipt {
/// What was paid, positive.
pub total: Option<Field<Haler>>,
pub date: Option<Field<Date>>,
/// Hours and minutes.
pub time: Option<Field<(u8, u8)>>,
pub shop: Option<Field<String>>,
pub ico: Option<Field<String>>,
pub dic: Option<Field<String>>,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ReceiptError {
#[error("there is more text than a receipt holds")]
TooLarge,
}
/// The labels of the total, best first: what is to pay beats a sum that might be before a discount.
const TOTAL_LABELS: [(&str, u8); 9] = [
("K UHRADE", 0),
("CASTKA K UHRADE", 0),
("CELKEM K UHRADE", 0),
("CELKEM", 1),
("CELKOVA CASTKA", 1),
("CELKEM KC", 1),
("CELKEM CZK", 1),
("SUMA", 2),
("TOTAL", 2),
];
/// A line with one of these is about VAT, a subtotal or rounding, never the total.
const NOT_TOTAL: [&str; 6] = ["DPH", "ZAKLAD", "SAZBA", "MEZISOUCET", "ZAOKROUHLENI", "VRACENO"];
/// A word as it reads for matching labels: upper case, Czech letters without their marks, punctuation at the
/// ends dropped.
fn fold(s: &str) -> String {
let up: String = s
.chars()
.flat_map(char::to_uppercase)
.map(|c| match c {
'Á' | 'Ä' => 'A',
'Č' => 'C',
'Ď' => 'D',
'É' | 'Ě' => 'E',
'Í' => 'I',
'Ň' => 'N',
'Ó' | 'Ö' => 'O',
'Ř' => 'R',
'Š' => 'S',
'Ť' => 'T',
'Ú' | 'Ů' | 'Ü' => 'U',
'Ý' => 'Y',
'Ž' => 'Z',
c => c,
})
.collect();
up.trim_matches(|c: char| !c.is_alphanumeric()).to_string()
}
struct Prepared<'a> {
words: Vec<&'a Word>,
texts: Vec<String>,
folded: Vec<String>,
}
impl Prepared<'_> {
fn sure(&self, idx: &[usize]) -> bool {
idx.iter().all(|&i| self.words[i].confidence >= SURE)
}
fn boxes(&self, idx: &[usize]) -> Vec<BBox> {
idx.iter().map(|&i| self.words[i].bbox).collect()
}
/// Where `label` (folded words) starts in this line, if it is there as whole words.
fn find(&self, label: &str) -> Option<usize> {
let want: Vec<&str> = label.split(' ').collect();
(0..self.folded.len()).find(|&i| i + want.len() <= self.folded.len() && want.iter().enumerate().all(|(k, w)| self.folded[i + k] == *w))
}
}
/// The receipt's fields, as far as they can be read. Nothing found is an empty [`Receipt`], not an error.
pub fn read(lines: &[Line]) -> Result<Receipt, ReceiptError> {
if lines.len() > MAX_LINES || lines.iter().any(|l| l.words.len() > MAX_WORDS || l.words.iter().any(|w| w.text.chars().count() > MAX_WORD)) {
return Err(ReceiptError::TooLarge);
}
let prepared: Vec<Prepared> = lines
.iter()
.map(|l| {
let words: Vec<&Word> = l.words.iter().filter(|w| !clean(&w.text).is_empty()).collect();
let texts: Vec<String> = words.iter().map(|w| clean(&w.text)).collect();
let folded = texts.iter().map(|t| fold(t)).collect();
Prepared { words, texts, folded }
})
.collect();
let mut out = Receipt { total: total(&prepared), ..Default::default() };
let (date, time) = date_time(&prepared);
out.date = date;
out.time = time;
out.dic = dic(&prepared);
let ico_line;
(out.ico, ico_line) = ico(&prepared);
if out.ico.is_none() {
// A company's DIČ is CZ and its IČO.
out.ico = out.dic.as_ref().filter(|d| d.value.len() == 10 && ico_ok(&d.value[2..])).map(|d| Field { value: d.value[2..].to_string(), sure: d.sure, boxes: d.boxes.clone() });
}
out.shop = shop(&prepared, ico_line);
Ok(out)
}
/// The word's text without control characters, trimmed.
fn clean(s: &str) -> String {
s.chars().filter(|c| !c.is_control()).collect::<String>().trim().to_string()
}
/// An amount written over words `i..=j`: `1 284,90`, `1284.90`, `-89,00` (a sign is ignored), with `Kč` after it
/// dropped. Groups of three digits may be split over words. `Some(None)`: well formed, but not a payment Fiscus
/// believes (over 10 000 000 Kč, or nothing); `None`: not an amount.
fn amount_at(p: &Prepared, i: usize, j: usize) -> Option<Option<Haler>> {
let text = p.texts[i..=j].join(" ");
let t = text.trim_start_matches(['-', '−']).trim_end_matches(|c: char| c.is_alphabetic() || c == '.').trim();
let (int, frac) = t.rsplit_once([',', '.'])?;
if frac.len() != 2 || !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let groups: Vec<&str> = int.split([' ', '.', '\u{a0}']).collect();
let ok = if groups.len() == 1 {
(1..=7).contains(&groups[0].len()) && groups[0].bytes().all(|b| b.is_ascii_digit())
} else {
(1..=3).contains(&groups[0].len()) && groups.iter().all(|g| g.bytes().all(|b| b.is_ascii_digit())) && groups[1..].iter().all(|g| g.len() == 3)
};
if !ok {
return None;
}
Some(amount::parse_positive(&format!("{},{frac}", groups.concat())))
}
/// The rightmost amount in a line from word `from` on, and the words it was written in.
fn last_amount(p: &Prepared, from: usize) -> Option<(Haler, Vec<usize>)> {
for j in (from..p.texts.len()).rev() {
// The longest reading that ends at j, so "1 284,90" wins over "284,90"; and one too large is refused
// whole, never read as its tail.
if let Some((i, a)) = (j.saturating_sub(2).max(from)..=j).find_map(|i| amount_at(p, i, j).map(|a| (i, a))) {
return a.map(|a| (a, (i..=j).collect()));
}
}
None
}
fn total(lines: &[Prepared]) -> Option<Field<Haler>> {
let mut best: Option<(u8, Field<Haler>)> = None;
for (n, p) in lines.iter().enumerate() {
if NOT_TOTAL.iter().any(|w| p.folded.iter().any(|f| f == w)) {
continue;
}
let Some((rank, at, len)) = TOTAL_LABELS.iter().filter_map(|(l, r)| p.find(l).map(|at| (*r, at, l.split(' ').count()))).min_by_key(|(r, _, len)| (*r, usize::MAX - len)) else { continue };
let label: Vec<usize> = (at..at + len).collect();
// On the label's line, or alone on the next one.
let found = last_amount(p, at + len).map(|(a, idx)| (a, idx, p)).or_else(|| {
let next = lines.get(n + 1)?;
let (a, idx) = last_amount(next, 0)?;
(idx.len() == next.texts.len()).then_some((a, idx, next))
});
let Some((amount, idx, q)) = found else { continue };
let field = Field { value: amount, sure: p.sure(&label) && q.sure(&idx), boxes: [p.boxes(&label), q.boxes(&idx)].concat() };
let better = match &best {
None => true,
Some((r, f)) => rank < *r || (rank == *r && amount > f.value),
};
if better {
best = Some((rank, field));
}
}
best.map(|(_, f)| f)
}
/// Digits only, if the text is digits (a stray `.` or `:` at the ends is dropped).
fn digits(s: &str) -> Option<&str> {
let d = s.trim_matches(|c: char| !c.is_ascii_alphanumeric());
(!d.is_empty() && d.bytes().all(|b| b.is_ascii_digit())).then_some(d)
}
/// A date in one word or over up to three (`16.11.2026`, `16. 11. 2026`, `16.11.26`, `2026-11-16`, `16/11/2026`).
fn date_at(p: &Prepared, i: usize) -> Option<(Date, Vec<usize>)> {
for len in 1..=3 {
if i + len > p.texts.len() {
break;
}
let text: String = p.texts[i..i + len].concat();
let t = text.trim_end_matches('.');
let parts: Vec<&str> = t.split(['.', '-', '/']).collect();
if parts.len() != 3 || parts.iter().any(|x| x.is_empty() || !x.bytes().all(|b| b.is_ascii_digit())) {
continue;
}
let n = |s: &str| s.parse::<u32>().ok();
let (y, m, d) = if parts[0].len() == 4 {
(n(parts[0])?, n(parts[1])?, n(parts[2])?)
} else if parts[2].len() == 4 && parts[0].len() <= 2 && parts[1].len() <= 2 {
(n(parts[2])?, n(parts[1])?, n(parts[0])?)
} else if parts[2].len() == 2 && parts[0].len() <= 2 && parts[1].len() <= 2 {
(2000 + n(parts[2])?, n(parts[1])?, n(parts[0])?)
} else {
continue;
};
if !(2000..=2100).contains(&y) {
continue;
}
if let Some(date) = Date::from_ymd(y as i32, m, d) {
return Some((date, (i..i + len).collect()));
}
}
None
}
/// `14:32` or `14:32:05` in one word.
fn time_at(p: &Prepared, i: usize) -> Option<(u8, u8)> {
let parts: Vec<&str> = p.texts[i].split(':').collect();
if !(2..=3).contains(&parts.len()) || parts.iter().any(|x| x.len() != 2 || !x.bytes().all(|b| b.is_ascii_digit())) {
return None;
}
let (h, m) = (parts[0].parse::<u8>().ok()?, parts[1].parse::<u8>().ok()?);
(h <= 23 && m <= 59).then_some((h, m))
}
type DateTime = (Option<Field<Date>>, Option<Field<(u8, u8)>>);
/// The date (one with a time on its line first), and the time on its line or anywhere.
fn date_time(lines: &[Prepared]) -> DateTime {
let mut first: Option<(Field<Date>, usize)> = None;
for (n, p) in lines.iter().enumerate() {
for i in 0..p.texts.len() {
let Some((date, idx)) = date_at(p, i) else { continue };
let field = Field { value: date, sure: p.sure(&idx), boxes: p.boxes(&idx) };
if let Some(t) = (0..p.texts.len()).find_map(|k| time_at(p, k).map(|t| (t, k))) {
let time = Field { value: t.0, sure: p.sure(&[t.1]), boxes: p.boxes(&[t.1]) };
return (Some(field), Some(time));
}
if first.is_none() {
first = Some((field, n));
}
}
}
let time = lines.iter().find_map(|p| (0..p.texts.len()).find_map(|k| time_at(p, k).map(|t| Field { value: t, sure: p.sure(&[k]), boxes: p.boxes(&[k]) })));
(first.map(|(f, _)| f), time)
}
/// The IČO after its label (`IČ`, `IČO`, `IČ:`), 8 digits with a check digit; and its line.
fn ico(lines: &[Prepared]) -> (Option<Field<String>>, Option<usize>) {
for (n, p) in lines.iter().enumerate() {
for (i, f) in p.folded.iter().enumerate() {
if f != "IC" && f != "ICO" {
continue;
}
for k in i + 1..(i + 3).min(p.texts.len()) {
if let Some(d) = digits(&p.texts[k]) {
let value = format!("{d:0>8}");
if d.len() <= 8 && ico_ok(&value) {
return (Some(Field { value, sure: p.sure(&[i, k]), boxes: p.boxes(&[i, k]) }), Some(n));
}
break;
}
}
}
}
(None, None)
}
/// The DIČ: `CZ` and 8-10 digits, in one word or two (`CZ 25672541`).
fn dic(lines: &[Prepared]) -> Option<Field<String>> {
for p in lines {
for i in 0..p.texts.len() {
for len in 1..=2 {
if i + len > p.texts.len() {
break;
}
let t: String = p.texts[i..i + len].concat().trim_matches(|c: char| !c.is_ascii_alphanumeric()).to_uppercase();
let t = t.strip_prefix("DIC:").unwrap_or(&t).to_string();
if t.starts_with("CZ") && dic_ok(&t) {
let idx: Vec<usize> = (i..i + len).collect();
return Some(Field { value: t, sure: p.sure(&idx), boxes: p.boxes(&idx) });
}
}
}
}
None
}
/// The shop's name: the first line from the top with three letters or more and no label of its own, above the
/// IČO's line (or among the first six lines without one). All capitals become Title Case. Always to check.
fn shop(lines: &[Prepared], ico_line: Option<usize>) -> Option<Field<String>> {
let end = ico_line.unwrap_or(6).min(lines.len());
const SKIP: [&str; 10] = ["IC", "ICO", "DIC", "TEL", "WWW", "EMAIL", "PROVOZOVNA", "ADRESA", "DANOVY", "UCTENKA"];
for p in &lines[..end] {
let letters = p.texts.iter().flat_map(|t| t.chars()).filter(|c| c.is_alphabetic()).count();
let digits = p.texts.iter().flat_map(|t| t.chars()).filter(|c| c.is_ascii_digit()).count();
if letters < 3 || digits * 2 > letters || p.folded.iter().any(|f| SKIP.contains(&f.as_str()) || f.contains('@') || f.starts_with("WWW") || f.starts_with("HTTP")) {
continue;
}
let name: Vec<String> = p.texts.iter().map(|t| title(t)).collect();
let value: String = name.join(" ").chars().take(fiscus_ledger::receipt::MAX_SHOP).collect::<String>().trim().to_string();
if value.is_empty() {
continue;
}
let idx: Vec<usize> = (0..p.texts.len()).collect();
return Some(Field { value, sure: false, boxes: p.boxes(&idx) });
}
None
}
/// `ALBERT` → `Albert`; a word with lower case letters, or not all letters (`s.r.o.`, `4×3,90`), stays.
fn title(w: &str) -> String {
if w.chars().count() > 1 && w.chars().all(|c| c.is_alphabetic() && !c.is_lowercase()) {
let mut c = w.chars();
let first = c.next().map(|f| f.to_string()).unwrap_or_default();
first + &c.as_str().to_lowercase()
} else {
w.to_string()
}
}
+22 -2
View File
@@ -1,8 +1,10 @@
//! The iPhone Shortcut post (`POST /inbox`). We write the Shortcut, so the shape is ours: //! 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. //! `{"amount", "merchant", "card", "time"}` and an optional `"currency": "CZK"`, nothing else. The Android app
//! posts a receipt it read the same way, with `"source": "receipt"` and the shop's optional `"ico"` and `"dic"`
//! (docs/07_receipts.md).
use crate::{amount, card_ok, merchant_ok, Capture}; use crate::{amount, card_ok, merchant_ok, Capture};
use fiscus_ledger::{Date, Timestamp}; use fiscus_ledger::{Date, ReceiptInfo, Timestamp};
use serde::Deserialize; use serde::Deserialize;
use serde_json::value::RawValue; use serde_json::value::RawValue;
@@ -25,6 +27,10 @@ pub enum CaptureError {
Card, Card,
#[error("the time is not ISO 8601 with an offset (2026-11-03T14:05:00+01:00)")] #[error("the time is not ISO 8601 with an offset (2026-11-03T14:05:00+01:00)")]
Time, Time,
#[error("the source is not receipt")]
Source,
#[error("an IČO or DIČ comes only with a receipt, and must be valid (8 digits with a check digit; CZ and 8-10 digits)")]
Receipt,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -36,6 +42,9 @@ struct Post<'a> {
card: String, card: String,
time: String, time: String,
currency: Option<String>, currency: Option<String>,
source: Option<String>,
ico: Option<String>,
dic: Option<String>,
} }
/// One post → one capture, or the first thing wrong with it. /// One post → one capture, or the first thing wrong with it.
@@ -63,6 +72,16 @@ pub fn parse(body: &[u8]) -> Result<Capture, CaptureError> {
return Err(CaptureError::Card); return Err(CaptureError::Card);
} }
let (date, at) = parse_time(&post.time).ok_or(CaptureError::Time)?; let (date, at) = parse_time(&post.time).ok_or(CaptureError::Time)?;
let receipt = match post.source.as_deref() {
None if post.ico.is_none() && post.dic.is_none() => None,
None => return Err(CaptureError::Receipt),
Some("receipt") => {
let info = ReceiptInfo { shop: post.merchant.trim().chars().take(fiscus_ledger::receipt::MAX_SHOP).collect::<String>().trim().to_string(), ico: post.ico, dic: post.dic };
info.check().map_err(|_| CaptureError::Receipt)?;
Some(info)
}
Some(_) => return Err(CaptureError::Source),
};
let card = post.card.trim(); let card = post.card.trim();
Ok(Capture { Ok(Capture {
amount: amount.checked_neg().map_err(|_| CaptureError::Amount)?, amount: amount.checked_neg().map_err(|_| CaptureError::Amount)?,
@@ -70,6 +89,7 @@ pub fn parse(body: &[u8]) -> Result<Capture, CaptureError> {
at, at,
merchant: post.merchant.trim().to_string(), merchant: post.merchant.trim().to_string(),
card: (!card.is_empty()).then(|| card.to_string()), card: (!card.is_empty()).then(|| card.to_string()),
receipt,
}) })
} }
+142
View File
@@ -0,0 +1,142 @@
//! Receipts read from an OCR's lines (docs/07_receipts.md): the fields every Czech receipt shows, found by their
//! labels; what to pay beats a sum before a discount; VAT lines are never the total; an IČO needs its check digit;
//! unsure words are marked; hostile text is bounded and never panics. Synthetic text here: real receipts come as
//! redacted OCR output in `fixtures/receipts/` (none yet).
use fiscus_capture::receipt::{read, BBox, Line, ReceiptError, Word, MAX_LINES};
use fiscus_ledger::{Date, Haler};
use proptest::prelude::*;
/// A receipt as text, one line per `\n`; a word ending in `?` was read with low confidence (and loses the `?`).
fn page(text: &str) -> Vec<Line> {
text.lines()
.enumerate()
.map(|(y, l)| Line {
words: l
.split_whitespace()
.enumerate()
.map(|(x, w)| {
let (t, c) = match w.strip_suffix('?') {
Some(t) if !t.is_empty() => (t, 420),
_ => (w, 960),
};
Word { text: t.into(), confidence: c, bbox: BBox { x: x as u32 * 50, y: y as u32 * 20, w: 40, h: 16 } }
})
.collect(),
})
.collect()
}
fn d(s: &str) -> Date {
s.parse().unwrap()
}
const ALBERT: &str = "ALBERT HYPERMARKET
Praha 5
IČ: 25672541 DIČ: CZ25672541
Rohlík tukový 4×3,90 15,60
Mléko polotučné 1 l 24,90
Káva zrnková 1 kg 389,00
CELKEM Kč 1 284,90
Platba kartou 1 284,90
DPH 12 % 137,67
16.11.2026 14:32 Pokl. 07
Děkujeme za nákup";
#[test]
fn a_supermarket_receipt_gives_every_field() {
let r = read(&page(ALBERT)).unwrap();
let total = r.total.unwrap();
assert_eq!((total.value, total.sure), (Haler(128_490), true));
assert_eq!(total.boxes.len(), 4, "the label and the amount, over two words each");
assert_eq!(r.date.unwrap().value, d("2026-11-16"));
assert_eq!(r.time.unwrap().value, (14, 32));
assert_eq!(r.ico.unwrap().value, "25672541");
assert_eq!(r.dic.unwrap().value, "CZ25672541");
let shop = r.shop.unwrap();
assert_eq!((shop.value.as_str(), shop.sure), ("Albert Hypermarket", false), "the shop's name is always to check");
}
#[test]
fn what_is_to_pay_beats_a_sum_before_a_discount_and_vat_lines_are_never_the_total() {
let r = read(&page("OBI\nIČO 25672541\nCELKEM 1 400,00\nSleva -115,10\nZáklad DPH 21 % 1 061,90\nK ÚHRADĚ 1 284,90\n2. 11. 2026")).unwrap();
assert_eq!(r.total.unwrap().value, Haler(128_490));
let r = read(&page("DPH celkem 223,00\nZaokrouhlení 0,10\nSUMA 89,90")).unwrap();
assert_eq!(r.total.unwrap().value, Haler(8_990));
}
#[test]
fn an_amount_alone_on_the_line_after_its_label_counts() {
let r = read(&page("CELKEM\n389,00\n16.11.2026")).unwrap();
assert_eq!(r.total.unwrap().value, Haler(38_900));
let r = read(&page("CELKEM\n2 ks 389,00")).unwrap();
assert!(r.total.is_none(), "a next line that is more than an amount is not the total");
}
#[test]
fn a_word_read_without_confidence_marks_its_field() {
let r = read(&page("CELKEM 1 284,90?\n16.11.2026? 14:32")).unwrap();
assert!(!r.total.unwrap().sure);
assert!(!r.date.unwrap().sure);
assert!(r.time.unwrap().sure);
}
#[test]
fn dates_in_the_ways_receipts_print_them() {
for (text, want) in [("16. 11. 2026", "2026-11-16"), ("2026-11-16", "2026-11-16"), ("16.11.26", "2026-11-16"), ("1/2/2027", "2027-02-01"), ("Datum: 05.01.2027 08:15", "2027-01-05")] {
assert_eq!(read(&page(text)).unwrap().date.map(|f| f.value), Some(d(want)), "{text}");
}
for text in ["31.02.2026", "16.11.1999", "16.13.2026", "1.2.3.4"] {
assert!(read(&page(text)).unwrap().date.is_none(), "{text}");
}
assert_eq!(read(&page("Čas 25:61\n09:05")).unwrap().time.map(|f| f.value), Some((9, 5)));
}
#[test]
fn an_ico_needs_its_check_digit_and_a_company_dic_gives_one() {
assert!(read(&page("IČ: 25672542")).unwrap().ico.is_none(), "the check digit does not fit");
assert_eq!(read(&page("IČO 2567254 1")).unwrap().ico, None, "split digits are not an IČO");
let r = read(&page("DIČ: CZ 25672541")).unwrap();
assert_eq!((r.dic.as_ref().unwrap().value.as_str(), r.ico.unwrap().value.as_str()), ("CZ25672541", "25672541"));
let r = read(&page("DIČ: CZ7811241234")).unwrap();
assert!(r.ico.is_none(), "a person's DIČ is a birth number, not an IČO");
}
#[test]
fn the_shop_is_the_first_line_with_a_name_above_the_ico() {
let r = read(&page("www.example.cz\n123 456\nLékárna U Anděla\nIČ 25672541\nCELKEM 189,00")).unwrap();
assert_eq!(r.shop.unwrap().value, "Lékárna U Anděla");
let r = read(&page("IČ 25672541\nZboží 189,00")).unwrap();
assert!(r.shop.is_none(), "nothing above the IČO");
}
#[test]
fn nothing_to_go_on_is_an_empty_receipt_not_an_error() {
assert_eq!(read(&[]).unwrap(), Default::default());
let r = read(&page("Děkujeme za nákup\nNa shledanou")).unwrap();
assert!(r.total.is_none() && r.date.is_none() && r.ico.is_none());
}
#[test]
fn hostile_text_is_bounded_and_control_characters_are_dropped() {
let many: Vec<Line> = (0..=MAX_LINES).map(|_| Line::default()).collect();
assert_eq!(read(&many), Err(ReceiptError::TooLarge));
let long = vec![Line { words: vec![Word { text: "x".repeat(81), confidence: 900, bbox: BBox::default() }] }];
assert_eq!(read(&long), Err(ReceiptError::TooLarge));
let r = read(&page("CELKEM\u{7} 1\u{0} 284,90\nALB\u{1b}ERT")).unwrap();
assert_eq!(r.total.unwrap().value, Haler(128_490));
let r = read(&page("CELKEM 99 999 999,00")).unwrap();
assert!(r.total.is_none(), "over the largest payment Fiscus believes");
}
proptest! {
#[test]
fn any_text_reads_without_panicking_and_a_total_is_a_believable_payment(words in prop::collection::vec(prop::collection::vec("[ -~ÁČĎÉĚÍŇÓŘŠŤÚŮÝŽáčďéěíňóřšťúůýž×−]{0,12}", 0..12), 0..40)) {
let lines: Vec<Line> = words.iter().map(|l| Line { words: l.iter().map(|t| Word { text: t.clone(), confidence: 900, bbox: BBox::default() }).collect() }).collect();
if let Ok(r) = read(&lines) {
if let Some(t) = r.total {
prop_assert!(t.value.0 > 0 && t.value <= fiscus_capture::amount::MAX);
}
}
}
}
+22
View File
@@ -90,3 +90,25 @@ proptest! {
prop_assert!(parse(&full.as_bytes()[..cut]).is_err()); prop_assert!(parse(&full.as_bytes()[..cut]).is_err());
} }
} }
#[test]
fn a_receipt_read_on_the_phone_carries_its_shop_ico_and_dic_and_nothing_else_does() {
let body = |extra: &str| format!(r#"{{"amount":"1 284,90","merchant":" Albert Hypermarket ","card":"","time":"2026-11-16T14:32:00+01:00"{extra}}}"#);
let c = parse(body(r#","source":"receipt","ico":"25672541","dic":"CZ25672541""#).as_bytes()).unwrap();
assert_eq!(c.amount, Haler(-128_490));
assert_eq!(c.card, None);
let r = c.receipt.unwrap();
assert_eq!((r.shop.as_str(), r.ico.as_deref(), r.dic.as_deref()), ("Albert Hypermarket", Some("25672541"), Some("CZ25672541")));
let c = parse(body(r#","source":"receipt""#).as_bytes()).unwrap();
assert_eq!(c.receipt.unwrap().ico, None, "a receipt without an IČO is fine");
assert_eq!(parse(post("129.5").as_bytes()).unwrap().receipt, None, "a card capture has no receipt");
for (extra, why) in [
(r#","ico":"25672541""#, CaptureError::Receipt),
(r#","source":"receipt","ico":"25672542""#, CaptureError::Receipt),
(r#","source":"receipt","dic":"SK2020123456""#, CaptureError::Receipt),
(r#","source":"card""#, CaptureError::Source),
(r#","source":"receipt","items":[]"#, CaptureError::Malformed),
] {
assert_eq!(parse(body(extra).as_bytes()), Err(why), "{extra}");
}
}
+2 -1
View File
@@ -1,12 +1,13 @@
//! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge, //! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge,
//! how to cancel, whether the month will stay under its limit, where the money went and how it compares with //! how to cancel, whether the month will stay under its limit, where the money went and how it compares with
//! your plan, how your savings goals fill, and the medals and challenges you earn. Pure: "today" and seeds are parameters. //! your plan, how your savings goals fill, your projects against their budgets and tasks, and the medals and challenges you earn. Pure: "today" and seeds are parameters.
pub mod cancel; pub mod cancel;
pub mod forecast; pub mod forecast;
pub mod goals; pub mod goals;
pub mod household; pub mod household;
pub mod plan; pub mod plan;
pub mod projects;
pub mod rewards; pub mod rewards;
pub mod spending; pub mod spending;
pub mod stats; pub mod stats;
+278
View File
@@ -0,0 +1,278 @@
//! Projects: what each one has cost against its budget lines, what it earned (a business), how far its tasks are,
//! what it will cost in the end, whether it is late, and its time. A payment counts in a project by hand
//! (`payment.projected`) or by a project rule of its merchant; it still counts in its budget and its month too.
use crate::spending::is_spending;
use fiscus_ledger::goal::Colour;
use fiscus_ledger::project::{week_of, EntryId, Kind, Phase, ProjectRecord, Status, TaskRecord, TaskStatus};
use fiscus_ledger::{Date, Haler, State};
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct LineStatus {
pub id: String,
pub name: String,
pub planned: Haler,
pub spent: Haler,
/// Planned less spent; negative when over.
pub left: Haler,
pub over: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub struct TaskCounts {
pub todo: usize,
pub doing: usize,
pub done: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ProjectSummary {
pub id: String,
pub name: String,
pub kind: Kind,
pub status: Status,
pub colour: Colour,
pub starts: Option<Date>,
pub ends: Option<Date>,
/// All the budget lines together.
pub planned: Haler,
/// Money out of the payments in the project (positive).
pub spent: Haler,
/// A business: paid invoices of the project (without VAT) and money in put into it.
pub income: Haler,
pub profit: Haler,
/// Profit of income in thousandths; `None` without income.
pub margin_permille: Option<i64>,
/// What the open tasks are estimated to cost.
pub open_estimates: Haler,
/// Spent plus the open estimates: what it will have cost.
pub forecast: Haler,
/// Tasks done, in thousandths: by their estimates when every task has one, else by count.
pub progress_permille: u32,
pub tasks: TaskCounts,
pub late_tasks: usize,
/// Spent, or the forecast, above the plan.
pub over_budget: bool,
/// An open task past its due date, or the project past its end with tasks open.
pub late: bool,
pub minutes: u64,
pub unbilled_minutes: u64,
pub unbilled: Haler,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ProjectPayment {
pub id: String,
pub date: Date,
pub merchant: String,
pub amount: Haler,
pub line: Option<String>,
/// Counted by a project rule, not put in by hand.
pub by_rule: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct TaskStatusRow {
pub task: TaskRecord,
pub late: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct TaskTime {
pub task: Option<String>,
pub minutes: u64,
pub amount: Haler,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ProjectDetail {
pub summary: ProjectSummary,
pub lines: Vec<LineStatus>,
/// Spent outside any line.
pub unplanned: Haler,
/// The latest first.
pub payments: Vec<ProjectPayment>,
/// Open tasks by due date (none last), then the done ones, the latest done first.
pub tasks: Vec<TaskStatusRow>,
/// By start.
pub phases: Vec<Phase>,
pub time_by_task: Vec<TaskTime>,
/// Monday of each week with time → minutes, oldest first.
pub time_by_week: Vec<(Date, u64)>,
/// What all the time is worth, and the entries not invoiced yet (by date).
pub billable: Haler,
pub unbilled_entries: Vec<EntryId>,
pub invoices: Vec<String>,
}
fn sum(it: impl Iterator<Item = Haler>) -> Haler {
Haler(it.fold(0i64, |s, h| s.saturating_add(h.0)))
}
fn permille(part: i64, whole: i64) -> u32 {
if whole <= 0 {
return 0;
}
(i128::from(part.clamp(0, whole)) * 1000 / i128::from(whole)) as u32
}
fn summary_and_rows(state: &State, p: &ProjectRecord, today: Date) -> (ProjectSummary, Vec<LineStatus>, Haler, Vec<ProjectPayment>, Vec<TaskStatusRow>) {
// The payments in the project.
let mut payments = Vec::new();
let mut by_line: BTreeMap<Option<String>, i64> = BTreeMap::new();
let mut inflow = 0i64;
let invoice_payments: Vec<&String> = state.invoice_payments.iter().filter(|(_, inv)| p.invoices.contains(*inv)).map(|(pay, _)| pay).collect();
for e in state.effective_payments() {
let Some((project, line)) = state.project_of(&e) else { continue };
if project != p.id {
continue;
}
let line = line.filter(|l| p.line(l).is_some());
if is_spending(&e) {
let slot = by_line.entry(line.clone()).or_insert(0);
*slot = slot.saturating_add(e.amount.0.saturating_neg());
} else if e.amount.0 > 0 && e.category.as_deref() != Some(fiscus_ledger::categories::TRANSFERS) && !invoice_payments.contains(&&e.id) {
inflow = inflow.saturating_add(e.amount.0);
}
payments.push(ProjectPayment { by_rule: !state.projects.payments.contains_key(&e.id), id: e.id, date: e.date, merchant: e.merchant, amount: e.amount, line });
}
payments.sort_by(|a, b| b.date.cmp(&a.date).then(a.id.cmp(&b.id)));
let spent = Haler(by_line.values().fold(0i64, |s, v| s.saturating_add(*v)));
let unplanned = Haler(by_line.get(&None).copied().unwrap_or(0));
let lines: Vec<LineStatus> = p
.lines
.iter()
.map(|l| {
let s = Haler(by_line.get(&Some(l.id.clone())).copied().unwrap_or(0));
let left = Haler(l.planned.0.saturating_sub(s.0));
LineStatus { id: l.id.clone(), name: l.name.clone(), planned: l.planned, spent: s, left, over: left.0 < 0 }
})
.collect();
let planned = sum(p.lines.iter().map(|l| l.planned));
// Income: the project's paid invoices without VAT, and money in put into it (not the lines that paid them).
let invoiced = sum(p.invoices.iter().filter_map(|i| state.invoices.get(i)).filter(|r| r.paid.is_some() && !r.cancelled).map(|r| r.totals.net));
let income = Haler(invoiced.0.saturating_add(inflow));
let profit = Haler(income.0.saturating_sub(spent.0));
let margin_permille = (income.0 > 0).then(|| (i128::from(profit.0) * 1000 / i128::from(income.0)) as i64);
// Tasks.
let mut tasks: Vec<TaskStatusRow> = state
.projects
.tasks
.values()
.filter(|t| t.project == p.id)
.map(|t| TaskStatusRow { late: t.status != TaskStatus::Done && t.fields.due.is_some_and(|d| d < today), task: t.clone() })
.collect();
tasks.sort_by(|a, b| {
let done = |t: &TaskStatusRow| t.task.status == TaskStatus::Done;
done(a).cmp(&done(b)).then_with(|| {
if done(a) {
b.task.done_on.cmp(&a.task.done_on)
} else {
(a.task.fields.due.is_none(), a.task.fields.due).cmp(&(b.task.fields.due.is_none(), b.task.fields.due))
}
})
.then(a.task.seq.cmp(&b.task.seq))
});
let mut counts = TaskCounts::default();
for t in &tasks {
match t.task.status {
TaskStatus::Todo => counts.todo += 1,
TaskStatus::Doing => counts.doing += 1,
TaskStatus::Done => counts.done += 1,
}
}
let open_estimates = sum(tasks.iter().filter(|t| t.task.status != TaskStatus::Done).filter_map(|t| t.task.fields.estimate));
let all_estimated = !tasks.is_empty() && tasks.iter().all(|t| t.task.fields.estimate.is_some_and(|e| e.0 > 0));
let progress_permille = if all_estimated {
let total = sum(tasks.iter().filter_map(|t| t.task.fields.estimate));
let done = sum(tasks.iter().filter(|t| t.task.status == TaskStatus::Done).filter_map(|t| t.task.fields.estimate));
permille(done.0, total.0)
} else {
permille(counts.done as i64, tasks.len() as i64)
};
let forecast = Haler(spent.0.saturating_add(open_estimates.0));
let late_tasks = tasks.iter().filter(|t| t.late).count();
let open = p.is_open();
let late = open && (late_tasks > 0 || (p.ends.is_some_and(|e| e < today) && counts.todo + counts.doing > 0));
let over_budget = planned.0 > 0 && (spent > planned || forecast > planned);
// Time.
let entries: Vec<_> = state.projects.time.values().filter(|t| t.project == p.id).collect();
let minutes: u64 = entries.iter().map(|t| u64::from(t.minutes)).sum();
let unbilled_minutes: u64 = entries.iter().filter(|t| t.invoice.is_none()).map(|t| u64::from(t.minutes)).sum();
let unbilled = sum(entries.iter().filter(|t| t.invoice.is_none()).map(|t| t.amount()));
let summary = ProjectSummary {
id: p.id.clone(),
name: p.name.clone(),
kind: p.kind,
status: p.status,
colour: p.colour,
starts: p.starts,
ends: p.ends,
planned,
spent,
income,
profit,
margin_permille,
open_estimates,
forecast,
progress_permille,
tasks: counts,
late_tasks,
over_budget,
late,
minutes,
unbilled_minutes,
unbilled,
};
(summary, lines, unplanned, payments, tasks)
}
/// Every project: the open ones in the order made, then the done ones, the latest done first.
pub fn projects(state: &State, today: Date) -> Vec<ProjectSummary> {
let mut open: Vec<&ProjectRecord> = state.projects.projects.values().filter(|p| p.is_open()).collect();
open.sort_by_key(|p| p.seq);
let mut done: Vec<&ProjectRecord> = state.projects.projects.values().filter(|p| !p.is_open()).collect();
done.sort_by_key(|p| std::cmp::Reverse((p.status_on, p.seq)));
open.into_iter().chain(done).map(|p| summary_and_rows(state, p, today).0).collect()
}
/// One project in full.
pub fn project(state: &State, id: &str, today: Date) -> Option<ProjectDetail> {
let p = state.projects.projects.get(id)?;
let (summary, lines, unplanned, payments, tasks) = summary_and_rows(state, p, today);
let mut phases = p.phases.clone();
phases.sort_by(|a, b| a.starts.cmp(&b.starts).then(a.id.cmp(&b.id)));
let mut entries: Vec<_> = state.projects.time.values().filter(|t| t.project == p.id).collect();
entries.sort_by(|a, b| a.on.cmp(&b.on).then(a.seq.cmp(&b.seq)));
let mut by_task: BTreeMap<Option<String>, (u64, i64)> = BTreeMap::new();
let mut by_week: BTreeMap<Date, u64> = BTreeMap::new();
for t in &entries {
let slot = by_task.entry(t.task.clone()).or_insert((0, 0));
slot.0 += u64::from(t.minutes);
slot.1 = slot.1.saturating_add(t.amount().0);
*by_week.entry(week_of(t.on)).or_insert(0) += u64::from(t.minutes);
}
let mut time_by_task: Vec<TaskTime> = by_task.into_iter().map(|(task, (minutes, amount))| TaskTime { task, minutes, amount: Haler(amount) }).collect();
time_by_task.sort_by(|a, b| b.minutes.cmp(&a.minutes).then(a.task.cmp(&b.task)));
Some(ProjectDetail {
lines,
unplanned,
payments,
tasks,
phases,
time_by_task,
time_by_week: by_week.into_iter().collect(),
billable: sum(entries.iter().map(|t| t.amount())),
unbilled_entries: entries.iter().filter(|t| t.invoice.is_none()).map(|t| t.id.clone()).collect(),
invoices: p.invoices.iter().cloned().collect(),
summary,
})
}
+18
View File
@@ -32,6 +32,10 @@ pub enum Medal {
GoalMilestone { goal: String, name: String, permille: u32 }, GoalMilestone { goal: String, name: String, permille: u32 },
/// Money put aside in this many complete months running (3 or more), up to `until`'s month. /// Money put aside in this many complete months running (3 or more), up to `until`'s month.
SavingStreak { months: u32, until: Date }, SavingStreak { months: u32, until: Date },
/// A project done within its budget (it had one).
ProjectOnBudget { project: String, name: String },
/// A project done by its end date (it had one).
FinishedOnTime { project: String, name: String },
} }
#[derive(Clone, Debug, PartialEq, Eq, Serialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize)]
@@ -332,6 +336,20 @@ pub fn rewards(state: &State, insight: &Insight, shared: &BTreeSet<BudgetId>, to
medals.push(Earned { medal: Medal::SavingStreak { months: n, until: last }, on: last.month_end() }); medals.push(Earned { medal: Medal::SavingStreak { months: n, until: last }, on: last.month_end() });
} }
// Projects done: within their budget, by their end date.
let summaries = crate::projects::projects(state, today);
for p in state.projects.projects.values().filter(|p| !p.is_open()) {
let Some(on) = p.status_on else { continue };
if let Some(s) = summaries.iter().find(|s| s.id == p.id) {
if s.planned.0 > 0 && s.spent <= s.planned {
medals.push(Earned { medal: Medal::ProjectOnBudget { project: p.id.clone(), name: p.name.clone() }, on });
}
}
if p.ends.is_some_and(|e| on <= e) {
medals.push(Earned { medal: Medal::FinishedOnTime { project: p.id.clone(), name: p.name.clone() }, on });
}
}
medals.sort_by_key(|m| std::cmp::Reverse(m.on)); medals.sort_by_key(|m| std::cmp::Reverse(m.on));
let month = today.month_start(); let month = today.month_start();
Rewards { Rewards {
+214
View File
@@ -0,0 +1,214 @@
//! A project's numbers: spent by line and unplanned, payments by hand and by rule within the project's dates,
//! income without VAT and never twice, profit and margin, progress by estimates or by count, the forecast, late,
//! time by task and week, billed and unbilled, and the two project medals.
use fiscus_insight::projects::{project, projects};
use fiscus_insight::rewards::{rewards, Medal};
use fiscus_insight::subscriptions::analyse;
use fiscus_ledger::goal::Colour;
use fiscus_ledger::invoice::{Invoice, InvoiceLine, Language, Party, Supplier};
use fiscus_ledger::project::{Kind, Status, TaskFields, TaskStatus};
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
use std::collections::BTreeSet;
fn d(s: &str) -> Date {
s.parse().unwrap()
}
fn ledger(bodies: Vec<EventBody>) -> State {
let log: Vec<Event> = bodies.into_iter().enumerate().map(|(i, b)| Event::new(format!("e{i}"), Timestamp(0), b)).collect();
let s = State::replay(&log);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
s
}
fn made(id: &str, kind: Kind, starts: &str, ends: &str) -> EventBody {
EventBody::ProjectCreated { project: id.into(), name: format!("Project {id}"), kind, template: None, starts: Some(d(starts)), ends: Some(d(ends)), colour: Colour::Blue, rate: Some(Haler(80_000)) }
}
fn line(project: &str, id: &str, planned: i64) -> EventBody {
EventBody::ProjectLineSet { project: project.into(), line: id.into(), name: id.to_uppercase(), planned: Haler(planned) }
}
fn paid(id: &str, amount: i64, date: &str, merchant: &str, category: Option<&str>) -> EventBody {
EventBody::PaymentAdded { payment: id.into(), amount: Haler(amount), date: d(date), merchant: merchant.into(), category: category.map(str::to_string), note: None }
}
fn into(payment: &str, project: &str, line: Option<&str>) -> EventBody {
EventBody::PaymentProjected { payment: payment.into(), project: project.into(), line: line.map(str::to_string) }
}
fn task(id: &str, project: &str, due: Option<&str>, estimate: Option<i64>) -> EventBody {
EventBody::TaskCreated {
task: id.into(),
project: project.into(),
fields: TaskFields { title: format!("Task {id}"), phase: None, due: due.map(d), estimate: estimate.map(Haler), line: None, assignee: None, milestone: false },
}
}
fn done(task: &str, on: &str) -> EventBody {
EventBody::TaskStatusSet { task: task.into(), status: TaskStatus::Done, on: d(on) }
}
#[test]
fn a_renovation_spent_by_line_by_hand_and_by_rule_within_its_dates() {
let today = d("2026-11-20");
let s = ledger(vec![
made("flat", Kind::Simple, "2026-11-01", "2027-02-28"),
line("flat", "kitchen", 12_000_000),
line("flat", "tiles", 4_500_000),
paid("p1", -9_000_000, "2026-11-04", "IKEA Zlicin", None),
into("p1", "flat", Some("kitchen")),
paid("p2", -5_000_000, "2026-11-06", "Siko koupelny", None),
into("p2", "flat", Some("tiles")),
paid("p3", -120_000, "2026-11-08", "Hornbach Cerny Most", None),
paid("p4", -80_000, "2026-10-20", "Hornbach Cerny Most", None),
paid("p5", -50_000, "2026-11-09", "Albert", Some("groceries")),
EventBody::ProjectRuleSet { merchant_key: fiscus_ledger::merchant::merchant_key("Hornbach Cerny Most"), project: Some("flat".into()) },
task("t1", "flat", Some("2026-11-10"), None),
task("t2", "flat", Some("2026-12-10"), None),
task("t3", "flat", None, None),
done("t3", "2026-11-07"),
]);
let p = project(&s, "flat", today).unwrap();
let lines: Vec<(&str, Haler, Haler, bool)> = p.lines.iter().map(|l| (l.id.as_str(), l.spent, l.left, l.over)).collect();
assert_eq!(lines, [("kitchen", Haler(9_000_000), Haler(3_000_000), false), ("tiles", Haler(5_000_000), Haler(-500_000), true)]);
// Hornbach in November by the rule (before the project started: not), Albert never.
assert_eq!(p.unplanned, Haler(120_000));
assert_eq!(p.summary.spent, Haler(14_120_000));
assert_eq!(p.payments.iter().map(|x| (x.id.as_str(), x.by_rule)).collect::<Vec<_>>(), [("p3", true), ("p2", false), ("p1", false)]);
assert_eq!((p.summary.planned, p.summary.over_budget), (Haler(16_500_000), false), "a line over is not the project over");
// One task of three done (no estimates: by count); t1 is past its due date.
assert_eq!((p.summary.progress_permille, p.summary.late_tasks, p.summary.late), (333, 1, true));
assert_eq!((p.summary.tasks.todo, p.summary.tasks.done), (2, 1));
assert_eq!(p.tasks.iter().map(|t| (t.task.id.as_str(), t.late)).collect::<Vec<_>>(), [("t1", true), ("t2", false), ("t3", false)]);
}
#[test]
fn the_forecast_and_progress_by_estimates() {
let today = d("2026-11-20");
let s = ledger(vec![
made("flat", Kind::Simple, "2026-11-01", "2027-02-28"),
line("flat", "all", 10_000_000),
paid("p1", -6_000_000, "2026-11-04", "Firma Novak", None),
into("p1", "flat", Some("all")),
task("t1", "flat", None, Some(6_000_000)),
task("t2", "flat", None, Some(5_000_000)),
done("t1", "2026-11-05"),
]);
let p = &projects(&s, today)[0];
// 6 of 11 (by estimates) done; 6 spent + 5 to come = 11 > 10 planned.
assert_eq!((p.progress_permille, p.open_estimates, p.forecast, p.over_budget), (545, Haler(5_000_000), Haler(11_000_000), true));
}
#[test]
fn a_business_earns_from_paid_invoices_without_vat_and_never_twice() {
let today = d("2026-11-20");
let party = |name: &str, ico: &str| Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some(ico.into()), dic: None };
let invoice = |id: &str, number: &str| Invoice {
id: id.into(),
number: number.into(),
issued: d("2026-11-05"),
due: d("2026-11-19"),
taxable: None,
customer: party("Pekárna Novák", "45244782"),
lines: vec![InvoiceLine { text: "Web".into(), quantity: 10_000, unit: "h".into(), unit_price: Haler(80_000), vat: None }],
budget: None,
language: Language::Cs,
};
let s = ledger(vec![
made("web", Kind::Business, "2026-11-01", "2026-12-31"),
EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } },
EventBody::InvoiceIssued { invoice: invoice("i1", "20260001") },
EventBody::InvoiceIssued { invoice: invoice("i2", "20260002") },
EventBody::TimeLogged { entry: "l1".into(), project: "web".into(), task: None, minutes: 600, on: d("2026-11-03"), rate: Haler(80_000), note: String::new() },
EventBody::TimeLogged { entry: "l2".into(), project: "web".into(), task: None, minutes: 90, on: d("2026-11-10"), rate: Haler(80_000), note: String::new() },
EventBody::InvoiceProjected { invoice: "i1".into(), project: "web".into(), entries: vec!["l1".into()] },
EventBody::InvoiceProjected { invoice: "i2".into(), project: "web".into(), entries: vec![] },
// i1 marked paid by hand (its money in is not put into the project: the invoice is the income).
EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-11-18") },
// A tip from the client straight into the project; a tool bought for it.
paid("in2", 50_000, "2026-11-19", "Pekarna Novak", Some("income")),
into("in2", "web", None),
paid("out1", -100_000, "2026-11-12", "Adobe", None),
into("out1", "web", None),
]);
let p = project(&s, "web", today).unwrap();
// i1 paid (8 000 Kč without VAT) and the tip (500 Kč); i2 is not paid yet.
assert_eq!(p.summary.income, Haler(800_000 + 50_000));
let s2 = ledger(vec![
made("web", Kind::Business, "2026-11-01", "2026-12-31"),
EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } },
EventBody::InvoiceIssued { invoice: invoice("i1", "20260001") },
EventBody::InvoiceProjected { invoice: "i1".into(), project: "web".into(), entries: vec![] },
EventBody::PaymentImported {
payment: "line1".into(),
line: fiscus_ledger::import::StatementLine {
bank: "test".into(),
account: "1/0000".into(),
booked: d("2026-11-18"),
amount: Haler(800_000),
merchant: "Pekarna Novak".into(),
counterparty: None,
variable_symbol: Some("20260001".into()),
message: None,
bank_ref: None,
},
line_key: "k1".into(),
},
EventBody::InvoicePaid { invoice: "i1".into(), payment: Some("line1".into()), on: d("2026-11-18") },
into("line1", "web", None),
]);
// A statement line that paid the project's invoice, put into the project too, is the invoice: counted once.
assert_eq!(project(&s2, "web", today).unwrap().summary.income, Haler(800_000));
assert_eq!((p.summary.spent, p.summary.profit), (Haler(100_000), Haler(750_000)));
assert_eq!(p.summary.margin_permille, Some(882));
// 11 h 30 min logged; 10 h billed by i1, 1 h 30 min (1 200 Kč) not yet.
assert_eq!((p.summary.minutes, p.summary.unbilled_minutes, p.summary.unbilled, p.billable), (690, 90, Haler(120_000), Haler(920_000)));
assert_eq!(p.unbilled_entries, ["l2"]);
assert_eq!(p.time_by_week, [(d("2026-11-02"), 600), (d("2026-11-09"), 90)]);
assert_eq!((p.time_by_task[0].task.clone(), p.time_by_task[0].minutes), (None, 690));
assert_eq!(p.invoices, ["i1", "i2"]);
}
#[test]
fn a_project_late_past_its_end_and_the_medals_when_done() {
let s = ledger(vec![
made("trip", Kind::Simple, "2026-08-01", "2026-09-30"),
line("trip", "all", 3_000_000),
paid("p1", -2_500_000, "2026-08-15", "Booking.com", None),
into("p1", "trip", None),
task("t1", "trip", None, None),
]);
let today = d("2026-10-05");
assert!(projects(&s, today)[0].late, "past its end with a task open");
let mut log = vec![
made("trip", Kind::Simple, "2026-08-01", "2026-09-30"),
line("trip", "all", 3_000_000),
paid("p1", -2_500_000, "2026-08-15", "Booking.com", None),
into("p1", "trip", None),
task("t1", "trip", None, None),
done("t1", "2026-09-20"),
EventBody::ProjectStatusSet { project: "trip".into(), status: Status::Done, on: d("2026-09-25") },
made("late", Kind::Simple, "2026-08-01", "2026-09-01"),
line("late", "all", 100_000),
paid("p2", -500_000, "2026-08-15", "Bauhaus", None),
into("p2", "late", None),
EventBody::ProjectStatusSet { project: "late".into(), status: Status::Done, on: d("2026-09-10") },
];
let s = ledger(std::mem::take(&mut log));
assert!(!projects(&s, today).iter().any(|p| p.late), "a done project is never late");
let r = rewards(&s, &analyse(&s, today), &BTreeSet::new(), today);
let got: Vec<(&str, Date)> = r
.medals
.iter()
.filter_map(|e| match &e.medal {
Medal::ProjectOnBudget { project, .. } => Some(("on budget", if project == "trip" { e.on } else { d("1970-01-01") })),
Medal::FinishedOnTime { project, .. } => Some(("on time", if project == "trip" { e.on } else { d("1970-01-01") })),
_ => None,
})
.collect();
assert_eq!(got, [("on budget", d("2026-09-25")), ("on time", d("2026-09-25"))], "the trip earns both; the late, over one neither");
}
+51
View File
@@ -2,6 +2,7 @@
use crate::date::{Date, Timestamp}; use crate::date::{Date, Timestamp};
use crate::goal::{ChallengeGoal, ChallengeId, Colour, GoalId, Way, WayKind}; use crate::goal::{ChallengeGoal, ChallengeId, Colour, GoalId, Way, WayKind};
use crate::project::{EntryId, Kind, LineId, PhaseId, ProjectId, Status, TaskFields, TaskId, TaskStatus};
use crate::import::StatementLine; use crate::import::StatementLine;
use crate::invoice::{Invoice, InvoiceId, Supplier}; use crate::invoice::{Invoice, InvoiceId, Supplier};
use crate::money::Haler; use crate::money::Haler;
@@ -86,6 +87,10 @@ pub enum EventBody {
PaymentAssigned { payment: PaymentId, budget: BudgetId }, PaymentAssigned { payment: PaymentId, budget: BudgetId },
#[serde(rename = "payment.trial_marked")] #[serde(rename = "payment.trial_marked")]
PaymentTrialMarked { payment: PaymentId, ends: Date }, PaymentTrialMarked { payment: PaymentId, ends: Date },
/// A receipt for the payment: the shop's name you confirmed, its IČO and DIČ (docs/07_receipts.md). A later one
/// replaces it. The payment keeps its own merchant.
#[serde(rename = "payment.receipt_attached")]
ReceiptAttached { payment: PaymentId, receipt: crate::receipt::ReceiptInfo },
#[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 /// A shared budget in a personal log (created here or joined): like `budget.created`, but never the
@@ -187,4 +192,50 @@ pub enum EventBody {
/// Given up; a challenge is given up once. /// Given up; a challenge is given up once.
#[serde(rename = "challenge.abandoned")] #[serde(rename = "challenge.abandoned")]
ChallengeAbandoned { challenge: ChallengeId, on: Date }, ChallengeAbandoned { challenge: ChallengeId, on: Date },
/// A project (see [`crate::project`]): simple or business, from a template or empty.
#[serde(rename = "project.created")]
ProjectCreated { project: ProjectId, name: String, kind: Kind, template: Option<String>, starts: Option<Date>, ends: Option<Date>, colour: Colour, rate: Option<Haler> },
/// Its name, kind, dates, colour or rate changed; the latest counts.
#[serde(rename = "project.changed")]
ProjectChanged { project: ProjectId, name: String, kind: Kind, starts: Option<Date>, ends: Option<Date>, colour: Colour, rate: Option<Haler> },
#[serde(rename = "project.status_set")]
ProjectStatusSet { project: ProjectId, status: Status, on: Date },
/// A budget line: its name and planned amount. Zero planned removes it.
#[serde(rename = "project.line_set")]
ProjectLineSet { project: ProjectId, line: LineId, name: String, planned: Haler },
/// A phase of a project, from `starts` to `ends`.
#[serde(rename = "project.phase_set")]
ProjectPhaseSet { project: ProjectId, phase: PhaseId, name: String, starts: Date, ends: Date },
#[serde(rename = "project.phase_removed")]
ProjectPhaseRemoved { project: ProjectId, phase: PhaseId },
/// A payment put into a project (and one of its lines). One project per payment; it stays in its budget.
#[serde(rename = "payment.projected")]
PaymentProjected { payment: PaymentId, project: ProjectId, line: Option<LineId> },
#[serde(rename = "payment.unprojected")]
PaymentUnprojected { payment: PaymentId },
/// "Always <merchant key> → <project>"; `None` removes the rule. It stops when the project is done.
#[serde(rename = "project.rule_set")]
ProjectRuleSet { merchant_key: String, project: Option<ProjectId> },
#[serde(rename = "task.created")]
TaskCreated { task: TaskId, project: ProjectId, fields: TaskFields },
#[serde(rename = "task.changed")]
TaskChanged { task: TaskId, fields: TaskFields },
#[serde(rename = "task.status_set")]
TaskStatusSet { task: TaskId, status: TaskStatus, on: Date },
/// Time worked on a business project (a task of it, or the project as a whole), at an hourly rate.
#[serde(rename = "time.logged")]
TimeLogged { entry: EntryId, project: ProjectId, task: Option<TaskId>, minutes: u32, on: Date, rate: Haler, note: String },
#[serde(rename = "time.removed")]
TimeRemoved { entry: EntryId },
/// An invoice issued for a business project, and the time entries it bills (none: not from time).
#[serde(rename = "invoice.projected")]
InvoiceProjected { invoice: InvoiceId, project: ProjectId, entries: Vec<EntryId> },
/// The project is shared with the members of a shared budget: the app mirrors its name, dates, status, lines,
/// phases and tasks through that budget's log. Time, invoices and project rules are never shared. One budget
/// at a time.
#[serde(rename = "project.shared")]
ProjectShared { project: ProjectId, budget: BudgetId },
/// Not shared any more: the members keep the copy they have.
#[serde(rename = "project.unshared")]
ProjectUnshared { project: ProjectId },
} }
+3
View File
@@ -12,6 +12,8 @@ pub mod matching;
pub mod merchant; pub mod merchant;
pub mod money; pub mod money;
pub mod pay; pub mod pay;
pub mod project;
pub mod receipt;
pub mod share; pub mod share;
pub mod split; pub mod split;
pub mod state; pub mod state;
@@ -19,4 +21,5 @@ pub mod state;
pub use date::{Date, Timestamp}; pub use date::{Date, Timestamp};
pub use event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, Settlement, SplitId}; pub use event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, Settlement, SplitId};
pub use money::Haler; pub use money::Haler;
pub use receipt::{KnownShop, ReceiptInfo};
pub use state::{EffectivePayment, Glyph, Origin, ShareView, State}; pub use state::{EffectivePayment, Glyph, Origin, ShareView, State};
+172
View File
@@ -0,0 +1,172 @@
//! Projects: planning and tracking a piece of work with its own budget, tasks and (for a business) phases, time
//! and income. A project is a second label on payments: a payment in a project still counts in its budget and in
//! the month, so nothing is counted twice. Personal log only, like plans and goals.
use crate::date::Date;
use crate::event::{BudgetId, PaymentId};
use crate::goal::Colour;
use crate::invoice::InvoiceId;
use crate::money::Haler;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
pub type ProjectId = String;
pub type TaskId = String;
pub type LineId = String;
pub type PhaseId = String;
pub type EntryId = String;
/// At most this many projects not done at once.
pub const MAX_OPEN_PROJECTS: usize = 50;
/// Per project: budget lines, phases, and tasks not done.
pub const MAX_LINES: usize = 100;
pub const MAX_PHASES: usize = 50;
pub const MAX_OPEN_TASKS: usize = 200;
/// A planned amount, an estimate: 0 to 100 000 000 Kč.
pub const MAX_AMOUNT: Haler = Haler(10_000_000_000);
/// An hourly rate: 0 to 100 000 Kč.
pub const MAX_RATE: Haler = Haler(10_000_000);
/// Time logged on one day across all projects: at most 24 hours.
pub const MAX_MINUTES_A_DAY: u32 = 24 * 60;
/// Simple (a renovation, a trip): a budget and a checklist. Business (a side business, client work): also
/// income, phases, a timeline and time.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
Simple,
Business,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
Planning,
Active,
OnHold,
Done,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskStatus {
Todo,
Doing,
Done,
}
/// A task's fields as `task.created` and `task.changed` carry them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskFields {
pub title: String,
pub phase: Option<PhaseId>,
pub due: Option<Date>,
pub estimate: Option<Haler>,
pub line: Option<LineId>,
pub assignee: Option<String>,
pub milestone: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Line {
pub id: LineId,
pub name: String,
pub planned: Haler,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Phase {
pub id: PhaseId,
pub name: String,
pub starts: Date,
pub ends: Date,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectRecord {
pub id: ProjectId,
pub name: String,
pub kind: Kind,
pub template: Option<String>,
pub starts: Option<Date>,
pub ends: Option<Date>,
pub colour: Colour,
/// The hourly rate time is logged at unless an entry says otherwise (business).
pub rate: Option<Haler>,
pub status: Status,
/// When the status was last set (the day a project was done).
pub status_on: Option<Date>,
/// In the order made.
pub lines: Vec<Line>,
pub phases: Vec<Phase>,
/// Invoices issued for this project.
pub invoices: BTreeSet<InvoiceId>,
pub seq: u64,
}
impl ProjectRecord {
pub fn is_open(&self) -> bool {
self.status != Status::Done
}
pub fn line(&self, id: &str) -> Option<&Line> {
self.lines.iter().find(|l| l.id == id)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskRecord {
pub id: TaskId,
pub project: ProjectId,
pub fields: TaskFields,
pub status: TaskStatus,
/// The day it was done.
pub done_on: Option<Date>,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimeEntry {
pub id: EntryId,
pub project: ProjectId,
pub task: Option<TaskId>,
pub minutes: u32,
pub on: Date,
/// Per hour.
pub rate: Haler,
pub note: String,
/// The invoice that billed it.
pub invoice: Option<InvoiceId>,
pub seq: u64,
}
impl TimeEntry {
/// What the entry is worth: minutes × the hourly rate, rounded to the haléř (half up).
pub fn amount(&self) -> Haler {
let v = (i128::from(self.minutes) * i128::from(self.rate.0) + 30) / 60;
Haler(i64::try_from(v).unwrap_or(i64::MAX))
}
}
/// Everything about projects in a ledger.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Projects {
pub projects: BTreeMap<ProjectId, ProjectRecord>,
pub tasks: BTreeMap<TaskId, TaskRecord>,
pub time: BTreeMap<EntryId, TimeEntry>,
/// A payment put into a project (and a line) by hand.
pub payments: BTreeMap<PaymentId, (ProjectId, Option<LineId>)>,
/// "Always this merchant → this project", by merchant key.
pub rules: BTreeMap<String, ProjectId>,
/// A project shared with a shared budget's members → that budget (`project.shared`).
#[serde(default)]
pub shared: BTreeMap<ProjectId, BudgetId>,
}
/// The Monday of `d`'s week.
pub fn week_of(d: Date) -> Date {
// 1970-01-01 was a Thursday.
d.add_days(-(d.days() + 3).rem_euclid(7))
}
+78
View File
@@ -0,0 +1,78 @@
//! A receipt attached to a payment (`payment.receipt_attached`, docs/07_receipts.md): the shop's name as you
//! confirmed it, and its IČO and DIČ. The payment keeps its own merchant and merchant key (so the rules that bring
//! a category stay as they are); the receipt only adds what the shop is. Known shops and the payment a receipt
//! fills in are read from the state here, so the PC and the node decide alike.
use crate::date::Date;
use crate::event::{Category, PaymentId};
use crate::invoice::{dic_ok, ico_ok};
use crate::money::Haler;
use crate::state::State;
use serde::{Deserialize, Serialize};
/// The shop's name is 1-100 characters.
pub const MAX_SHOP: usize = 100;
/// A receipt fills in a payment of the same amount at most this many days before or after its date (a card
/// payment can be booked a few days later).
pub const MATCH_DAYS: i32 = 3;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReceiptInfo {
pub shop: String,
pub ico: Option<String>,
pub dic: Option<String>,
}
impl ReceiptInfo {
/// What the ledger accepts: a name without control characters, a valid IČO (with its check digit) and DIČ.
pub fn check(&self) -> Result<(), &'static str> {
let shop = self.shop.trim();
if shop.is_empty() || shop.chars().count() > MAX_SHOP || shop.chars().any(char::is_control) || shop != self.shop {
return Err("a shop's name must be 1-100 characters, trimmed, without control characters");
}
if self.ico.as_deref().is_some_and(|i| !ico_ok(i)) {
return Err("not a valid IČO (8 digits with a check digit)");
}
if self.dic.as_deref().is_some_and(|d| !dic_ok(d)) {
return Err("not a valid DIČ (CZ and 8-10 digits)");
}
Ok(())
}
}
/// What a shop's IČO brings from your earlier receipts: the name you confirmed last, and the category of that
/// payment.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KnownShop {
pub name: String,
pub category: Option<Category>,
pub payment: PaymentId,
}
impl State {
/// The shop of your latest receipt with this IČO, if any.
pub fn known_shop(&self, ico: &str) -> Option<KnownShop> {
self.effective_payments()
.into_iter()
.filter_map(|p| {
let r = p.receipt.as_ref()?;
(r.ico.as_deref() == Some(ico)).then(|| (p.receipt_seq, KnownShop { name: r.shop.clone(), category: p.category.clone(), payment: p.id.clone() }))
})
.max_by_key(|(seq, _)| *seq)
.map(|(_, k)| k)
}
/// The one payment a receipt of `total` (positive) on `date` fills in: an outflow of exactly that amount,
/// within [`MATCH_DAYS`], without a receipt yet. None when there is none, or more than one (then the receipt
/// is a payment of its own, and nothing is guessed).
pub fn receipt_match(&self, total: Haler, date: Date) -> Option<PaymentId> {
let amount = total.checked_neg().ok()?;
let mut found = self
.effective_payments()
.into_iter()
.filter(|p| p.amount == amount && p.receipt.is_none() && p.date.days_until(date).abs() <= MATCH_DAYS)
.map(|p| p.id);
let first = found.next()?;
found.next().is_none().then_some(first)
}
}
+301
View File
@@ -6,10 +6,12 @@ use crate::date::Date;
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId}; use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
use crate::goal::{self, ChallengeGoal, ChallengeId, ChallengeRecord, GoalId, GoalRecord, Saving, Way, WayKind}; use crate::goal::{self, ChallengeGoal, ChallengeId, ChallengeRecord, GoalId, GoalRecord, Saving, Way, WayKind};
use crate::import::StatementLine; use crate::import::StatementLine;
use crate::project::{self, Line, Phase, ProjectRecord, Projects, TaskRecord, TaskStatus, TimeEntry};
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals}; 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::pay::{spayd, Iban};
use crate::receipt::ReceiptInfo;
use crate::split::Share; use crate::split::Share;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
@@ -66,6 +68,9 @@ pub struct PaymentRecord {
pub category: Option<Stamped<Category>>, pub category: Option<Stamped<Category>>,
pub budget: Option<Stamped<BudgetId>>, pub budget: Option<Stamped<BudgetId>>,
pub trial_ends: Option<Stamped<Date>>, pub trial_ends: Option<Stamped<Date>>,
/// The receipt attached to it (docs/07_receipts.md).
#[serde(default)]
pub receipt: Option<Stamped<ReceiptInfo>>,
/// The other half of a confirmed pair. /// The other half of a confirmed pair.
pub partner: Option<PaymentId>, pub partner: Option<PaymentId>,
} }
@@ -234,6 +239,8 @@ pub struct State {
pub saving_ids: BTreeSet<String>, pub saving_ids: BTreeSet<String>,
/// Challenges by id (`challenge.*`). /// Challenges by id (`challenge.*`).
pub challenges: BTreeMap<ChallengeId, ChallengeRecord>, pub challenges: BTreeMap<ChallengeId, ChallengeRecord>,
/// Projects, their tasks, time, and the payments put into them (`project.*`, `task.*`, `time.*`).
pub projects: Projects,
pub rejected: Vec<Rejection>, pub rejected: Vec<Rejection>,
} }
@@ -269,6 +276,9 @@ pub struct EffectivePayment {
pub category_source: CategorySource, pub category_source: CategorySource,
pub budget: Option<BudgetId>, pub budget: Option<BudgetId>,
pub trial_ends: Option<Date>, pub trial_ends: Option<Date>,
/// The receipt attached to it, and when (its event's place in the log; 0 without one).
pub receipt: Option<ReceiptInfo>,
pub receipt_seq: u64,
} }
/// A person's name, or one shared subscription name. /// A person's name, or one shared subscription name.
@@ -287,6 +297,42 @@ fn name_ok(s: &str, max: usize) -> bool {
!s.trim().is_empty() && s.chars().count() <= max && text_ok(s) !s.trim().is_empty() && s.chars().count() <= max && text_ok(s)
} }
/// A project's name, dates and rate, for `project.created` and `project.changed`.
fn project_fields(name: &str, starts: Option<Date>, ends: Option<Date>, rate: Option<Haler>) -> Result<(), &'static str> {
if !name_ok(name, 60) || name.trim() != name {
return Err("a project name must be 1-60 characters");
}
if let (Some(s), Some(e)) = (starts, ends) {
if e < s {
return Err("a project ends before it starts");
}
}
if rate.is_some_and(|r| r.0 < 0 || r > project::MAX_RATE) {
return Err("an hourly rate is 0-100 000 CZK");
}
Ok(())
}
/// A task's fields, checked against its project.
fn task_fields(p: &ProjectRecord, f: &project::TaskFields) -> Result<(), &'static str> {
if !name_ok(&f.title, 120) || f.title.trim() != f.title {
return Err("a task title must be 1-120 characters");
}
if f.phase.as_ref().is_some_and(|ph| !p.phases.iter().any(|x| &x.id == ph)) {
return Err("no such phase in the project");
}
if f.line.as_ref().is_some_and(|l| p.line(l).is_none()) {
return Err("no such budget line in the project");
}
if f.estimate.is_some_and(|e| e.0 < 0 || e > project::MAX_AMOUNT) {
return Err("an estimate is 0-100 000 000 CZK");
}
if f.assignee.as_ref().is_some_and(|a| !name_ok(a, 40) || a.trim() != a) {
return Err("an assignee name must be 1-40 characters");
}
Ok(())
}
/// A goal's name and target, for `goal.created` and `goal.changed`. /// A goal's name and target, for `goal.created` and `goal.changed`.
fn goal_fields(name: &str, target: Haler) -> Result<(), &'static str> { fn goal_fields(name: &str, target: Haler) -> Result<(), &'static str> {
if !name_ok(name, 60) || name.trim() != name { if !name_ok(name, 60) || name.trim() != name {
@@ -383,6 +429,7 @@ impl State {
category: None, category: None,
budget: None, budget: None,
trial_ends: None, trial_ends: None,
receipt: None,
partner: None, partner: None,
}, },
); );
@@ -413,6 +460,7 @@ impl State {
category: None, category: None,
budget: None, budget: None,
trial_ends: None, trial_ends: None,
receipt: None,
partner: None, partner: None,
}, },
); );
@@ -441,6 +489,7 @@ impl State {
category: category.clone().map(|value| Stamped { seq, value }), category: category.clone().map(|value| Stamped { seq, value }),
budget: None, budget: None,
trial_ends: None, trial_ends: None,
receipt: None,
partner: None, partner: None,
}, },
); );
@@ -475,6 +524,10 @@ 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::ReceiptAttached { payment, receipt } => {
receipt.check()?;
self.payment_mut(payment)?.receipt = Some(Stamped { seq, value: receipt.clone() });
}
EventBody::BudgetCreated { budget, name, limit } | EventBody::BudgetShared { 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");
@@ -556,6 +609,7 @@ impl State {
category: category.clone().map(|value| Stamped { seq, value }), category: category.clone().map(|value| Stamped { seq, value }),
budget: Some(Stamped { seq, value: budget.clone() }), budget: Some(Stamped { seq, value: budget.clone() }),
trial_ends: None, trial_ends: None,
receipt: None,
partner: None, partner: None,
}, },
); );
@@ -911,10 +965,255 @@ impl State {
} }
c.abandoned = Some(*on); c.abandoned = Some(*on);
} }
EventBody::ProjectCreated { project, name, kind, template, starts, ends, colour, rate } => {
if !id_ok(project) || self.projects.projects.contains_key(project) {
return Err("a project with this id exists");
}
project_fields(name, *starts, *ends, *rate)?;
if template.as_ref().is_some_and(|t| !id_ok(t)) {
return Err("not a template id");
}
if self.projects.projects.values().filter(|p| p.is_open()).count() >= project::MAX_OPEN_PROJECTS {
return Err("at most 50 projects are open at once");
}
self.projects.projects.insert(
project.clone(),
ProjectRecord {
id: project.clone(),
name: name.clone(),
kind: *kind,
template: template.clone(),
starts: *starts,
ends: *ends,
colour: *colour,
rate: *rate,
status: project::Status::Active,
status_on: None,
lines: Vec::new(),
phases: Vec::new(),
invoices: BTreeSet::new(),
seq,
},
);
}
EventBody::ProjectChanged { project, name, kind, starts, ends, colour, rate } => {
project_fields(name, *starts, *ends, *rate)?;
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
if *kind == project::Kind::Simple && (!p.phases.is_empty() || self.projects.time.values().any(|t| &t.project == project)) {
return Err("a project with phases or time stays a business project");
}
(p.name, p.kind, p.starts, p.ends, p.colour, p.rate) = (name.clone(), *kind, *starts, *ends, *colour, *rate);
}
EventBody::ProjectStatusSet { project, status, on } => {
let reopening = *status != project::Status::Done;
let open = self.projects.projects.values().filter(|p| p.is_open()).count();
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
if reopening && !p.is_open() && open >= project::MAX_OPEN_PROJECTS {
return Err("at most 50 projects are open at once");
}
p.status = *status;
p.status_on = Some(*on);
}
EventBody::ProjectLineSet { project, line, name, planned } => {
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
if !id_ok(line) {
return Err("not a line id");
}
if planned.0 < 0 || *planned > project::MAX_AMOUNT {
return Err("a planned amount is 0-100 000 000 CZK");
}
if planned.0 == 0 {
p.lines.retain(|l| &l.id != line);
} else {
if !name_ok(name, 60) || name.trim() != name {
return Err("a budget line name must be 1-60 characters");
}
match p.lines.iter().position(|l| &l.id == line) {
Some(i) => (p.lines[i].name, p.lines[i].planned) = (name.clone(), *planned),
None if p.lines.len() >= project::MAX_LINES => return Err("at most 100 budget lines a project"),
None => p.lines.push(Line { id: line.clone(), name: name.clone(), planned: *planned, seq }),
}
}
}
EventBody::ProjectPhaseSet { project, phase, name, starts, ends } => {
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
if p.kind != project::Kind::Business {
return Err("only a business project has phases");
}
if !id_ok(phase) {
return Err("not a phase id");
}
if !name_ok(name, 60) || name.trim() != name {
return Err("a phase name must be 1-60 characters");
}
if ends < starts {
return Err("a phase ends before it starts");
}
match p.phases.iter().position(|x| &x.id == phase) {
Some(i) => (p.phases[i].name, p.phases[i].starts, p.phases[i].ends) = (name.clone(), *starts, *ends),
None if p.phases.len() >= project::MAX_PHASES => return Err("at most 50 phases a project"),
None => p.phases.push(Phase { id: phase.clone(), name: name.clone(), starts: *starts, ends: *ends }),
}
}
EventBody::ProjectPhaseRemoved { project, phase } => {
if self.projects.tasks.values().any(|t| &t.project == project && t.fields.phase.as_ref() == Some(phase)) {
return Err("tasks are still in this phase");
}
let p = self.projects.projects.get_mut(project).ok_or("no such project")?;
let before = p.phases.len();
p.phases.retain(|x| &x.id != phase);
if p.phases.len() == before {
return Err("no such phase in the project");
}
}
EventBody::PaymentProjected { payment, project, line } => {
if self.effective_payment(payment).is_none() {
return Err("no such payment");
}
let p = self.projects.projects.get(project).ok_or("no such project")?;
if !p.is_open() {
return Err("the project is done");
}
if line.as_ref().is_some_and(|l| p.line(l).is_none()) {
return Err("no such budget line in the project");
}
self.projects.payments.insert(payment.clone(), (project.clone(), line.clone()));
}
EventBody::PaymentUnprojected { payment } => {
if self.projects.payments.remove(payment).is_none() {
return Err("this payment is in no project");
}
}
EventBody::ProjectRuleSet { merchant_key: key, project } => {
if key.is_empty() || merchant_key(key) != *key {
return Err("not a merchant key");
}
match project {
Some(id) => {
if !self.projects.projects.get(id).is_some_and(ProjectRecord::is_open) {
return Err("no such open project");
}
self.projects.rules.insert(key.clone(), id.clone());
}
None => {
self.projects.rules.remove(key);
}
}
}
EventBody::TaskCreated { task, project, fields } => {
if !id_ok(task) || self.projects.tasks.contains_key(task) {
return Err("a task with this id exists");
}
let p = self.projects.projects.get(project).ok_or("no such project")?;
task_fields(p, fields)?;
if self.projects.tasks.values().filter(|t| &t.project == project && t.status != TaskStatus::Done).count() >= project::MAX_OPEN_TASKS {
return Err("at most 200 open tasks a project");
}
self.projects.tasks.insert(task.clone(), TaskRecord { id: task.clone(), project: project.clone(), fields: fields.clone(), status: TaskStatus::Todo, done_on: None, seq });
}
EventBody::TaskChanged { task, fields } => {
let t = self.projects.tasks.get(task).ok_or("no such task")?;
let p = self.projects.projects.get(&t.project).ok_or("no such project")?;
task_fields(p, fields)?;
self.projects.tasks.get_mut(task).expect("checked").fields = fields.clone();
}
EventBody::TaskStatusSet { task, status, on } => {
let t = self.projects.tasks.get_mut(task).ok_or("no such task")?;
t.status = *status;
t.done_on = (*status == TaskStatus::Done).then_some(*on);
}
EventBody::TimeLogged { entry, project, task, minutes, on, rate, note } => {
if !id_ok(entry) || self.projects.time.contains_key(entry) {
return Err("a time entry with this id exists");
}
let p = self.projects.projects.get(project).ok_or("no such project")?;
if p.kind != project::Kind::Business {
return Err("only a business project logs time");
}
if task.as_ref().is_some_and(|t| !self.projects.tasks.get(t).is_some_and(|x| &x.project == project)) {
return Err("no such task in the project");
}
let day: u32 = self.projects.time.values().filter(|t| t.on == *on).map(|t| t.minutes).sum();
if *minutes == 0 || day + minutes > project::MAX_MINUTES_A_DAY {
return Err("time logged is 1 minute to 24 hours a day");
}
if rate.0 < 0 || *rate > project::MAX_RATE {
return Err("an hourly rate is 0-100 000 CZK");
}
if note.chars().count() > 200 || !text_ok(note) {
return Err("a note is at most 200 characters");
}
self.projects.time.insert(
entry.clone(),
TimeEntry { id: entry.clone(), project: project.clone(), task: task.clone(), minutes: *minutes, on: *on, rate: *rate, note: note.clone(), invoice: None, seq },
);
}
EventBody::TimeRemoved { entry } => {
let t = self.projects.time.get(entry).ok_or("no such time entry")?;
if t.invoice.is_some() {
return Err("this time is invoiced");
}
self.projects.time.remove(entry);
}
EventBody::InvoiceProjected { invoice, project, entries } => {
if !self.invoices.contains_key(invoice) {
return Err("no such invoice");
}
let p = self.projects.projects.get(project).ok_or("no such project")?;
if p.kind != project::Kind::Business {
return Err("only a business project has invoices");
}
if self.projects.projects.values().any(|x| x.invoices.contains(invoice)) {
return Err("this invoice is in a project already");
}
if entries.iter().collect::<BTreeSet<_>>().len() != entries.len() {
return Err("a time entry appears twice");
}
for e in entries {
match self.projects.time.get(e) {
Some(t) if &t.project == project && t.invoice.is_none() => {}
Some(t) if t.invoice.is_some() => return Err("this time is invoiced"),
_ => return Err("no such time entry in the project"),
}
}
for e in entries {
self.projects.time.get_mut(e).expect("checked").invoice = Some(invoice.clone());
}
self.projects.projects.get_mut(project).expect("checked").invoices.insert(invoice.clone());
}
EventBody::ProjectShared { project, budget } => {
if !self.projects.projects.contains_key(project) {
return Err("no such project");
}
if !self.budgets.contains_key(budget) {
return Err("no such budget");
}
if self.projects.shared.contains_key(project) {
return Err("the project is shared already");
}
self.projects.shared.insert(project.clone(), budget.clone());
}
EventBody::ProjectUnshared { project } => {
if self.projects.shared.remove(project).is_none() {
return Err("the project is not shared");
}
}
} }
Ok(()) Ok(())
} }
/// The project a payment is in, and its line: put there by hand, else by a project rule of its merchant while
/// the project is open and the payment falls in the project's dates.
pub fn project_of(&self, p: &EffectivePayment) -> Option<(String, Option<String>)> {
if let Some((project, line)) = self.projects.payments.get(&p.id) {
return Some((project.clone(), line.clone()));
}
let id = self.projects.rules.get(&p.merchant_key)?;
let rec = self.projects.projects.get(id)?;
let in_dates = rec.starts.is_none_or(|s| p.date >= s) && rec.ends.is_none_or(|e| p.date <= e);
(rec.is_open() && in_dates).then(|| (id.clone(), None))
}
/// A default category or one of your own. /// A default category or one of your own.
pub fn category_known(&self, id: &str) -> bool { pub fn category_known(&self, id: &str) -> bool {
categories::DEFAULT.iter().any(|(d, _)| *d == id) || self.custom_categories.contains_key(id) categories::DEFAULT.iter().any(|(d, _)| *d == id) || self.custom_categories.contains_key(id)
@@ -1062,6 +1361,8 @@ impl State {
category_source, category_source,
budget, budget,
trial_ends: latest(&p.trial_ends, partner.map(|q| &q.trial_ends)), trial_ends: latest(&p.trial_ends, partner.map(|q| &q.trial_ends)),
receipt_seq: [p.receipt.as_ref(), partner.and_then(|q| q.receipt.as_ref())].into_iter().flatten().map(|r| r.seq).max().unwrap_or(0),
receipt: latest(&p.receipt, partner.map(|q| &q.receipt)),
} }
} }
} }
+243
View File
@@ -0,0 +1,243 @@
//! Projects in the ledger: what is accepted, and every refusal changing nothing. A done project takes no more
//! payments, a simple project has no phases or time, time never passes 24 hours a day, and an entry is
//! invoiced once.
use fiscus_ledger::goal::Colour;
use fiscus_ledger::project::{week_of, Kind, Status, TaskFields, TaskStatus};
use fiscus_ledger::{Date, Event, EventBody, 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 project(id: &str, kind: Kind) -> EventBody {
EventBody::ProjectCreated { project: id.into(), name: "Flat".into(), kind, template: Some("renovation".into()), starts: Some(d("2026-11-01")), ends: Some(d("2027-02-28")), colour: Colour::Teal, rate: Some(Haler(80_000)) }
}
fn task(id: &str, project: &str, title: &str) -> EventBody {
EventBody::TaskCreated { task: id.into(), project: project.into(), fields: fields(title) }
}
fn fields(title: &str) -> TaskFields {
TaskFields { title: title.into(), phase: None, due: None, estimate: None, line: None, assignee: None, milestone: false }
}
fn payment(id: &str, amount: i64, date: &str, merchant: &str) -> EventBody {
EventBody::PaymentAdded { payment: id.into(), amount: Haler(amount), date: d(date), merchant: merchant.into(), category: None, note: None }
}
fn log(entry: &str, project: &str, minutes: u32, on: &str) -> EventBody {
EventBody::TimeLogged { entry: entry.into(), project: project.into(), task: None, minutes, on: d(on), rate: Haler(80_000), note: String::new() }
}
#[test]
fn a_project_is_shared_with_one_budget_at_a_time_and_unshared_once() {
let budget = |id: &str| EventBody::BudgetShared { budget: id.into(), name: "Home".into(), limit: Haler(0) };
let base = vec![project("p1", Kind::Simple), budget("home"), budget("chata")];
let share = |b: &str| EventBody::ProjectShared { project: "p1".into(), budget: b.into() };
assert_eq!(refusal(&base, share("home")), None);
assert_eq!(refusal(&base, EventBody::ProjectShared { project: "nope".into(), budget: "home".into() }).as_deref(), Some("no such project"));
assert_eq!(refusal(&base, share("nope")).as_deref(), Some("no such budget"));
let mut shared = base.clone();
shared.push(share("home"));
assert_eq!(refusal(&shared, share("chata")).as_deref(), Some("the project is shared already"));
assert_eq!(refusal(&shared, share("home")).as_deref(), Some("the project is shared already"));
let state = State::replay(&shared.iter().enumerate().map(|(i, b)| ev(&format!("s{i}"), b.clone())).collect::<Vec<_>>());
assert_eq!(state.projects.shared.get("p1").map(String::as_str), Some("home"));
assert_eq!(refusal(&base, EventBody::ProjectUnshared { project: "p1".into() }).as_deref(), Some("the project is not shared"));
shared.push(EventBody::ProjectUnshared { project: "p1".into() });
assert_eq!(refusal(&shared, EventBody::ProjectUnshared { project: "p1".into() }).as_deref(), Some("the project is not shared"));
assert_eq!(refusal(&shared, share("chata")), None, "shared again, elsewhere");
}
#[test]
fn the_shared_events_keep_their_names_on_the_wire() {
let json = serde_json::to_string(&EventBody::ProjectShared { project: "p1".into(), budget: "home".into() }).unwrap();
assert!(json.contains("\"project.shared\""), "{json}");
let json = serde_json::to_string(&EventBody::ProjectUnshared { project: "p1".into() }).unwrap();
assert!(json.contains("\"project.unshared\""), "{json}");
// A state saved before sharing existed still reads.
let old = serde_json::json!({ "projects": {}, "tasks": {}, "time": {}, "payments": {}, "rules": {} });
let p: fiscus_ledger::project::Projects = serde_json::from_value(old).unwrap();
assert!(p.shared.is_empty());
}
/// The base ledger, then `body`: the reason it was refused, or `None` when it was accepted.
fn refusal(base: &[EventBody], body: EventBody) -> Option<String> {
let mut log: Vec<Event> = base.iter().enumerate().map(|(i, b)| ev(&format!("b{i}"), b.clone())).collect();
let before = State::replay(&log);
assert!(before.rejected.is_empty(), "{:?}", before.rejected);
log.push(ev("x", body));
let after = State::replay(&log);
match after.rejected.last() {
Some(r) => {
assert_eq!(after.projects, before.projects, "a refusal changes no project");
Some(r.reason.clone())
}
None => None,
}
}
#[test]
fn a_project_its_lines_tasks_and_payments() {
let s = State::replay(&[
ev("e1", project("p1", Kind::Simple)),
ev("e2", EventBody::ProjectLineSet { project: "p1".into(), line: "kitchen".into(), name: "Kitchen".into(), planned: Haler(12_000_000) }),
ev("e3", EventBody::ProjectLineSet { project: "p1".into(), line: "tiles".into(), name: "Tiles".into(), planned: Haler(4_500_000) }),
ev("e4", EventBody::ProjectLineSet { project: "p1".into(), line: "tiles".into(), name: "Tiles and grout".into(), planned: Haler(5_000_000) }),
ev("e5", task("t1", "p1", "Order the kitchen")),
ev("e6", EventBody::TaskStatusSet { task: "t1".into(), status: TaskStatus::Done, on: d("2026-11-05") }),
ev("e7", payment("pay1", -1_250_000, "2026-11-04", "IKEA Zlicin")),
ev("e8", EventBody::PaymentProjected { payment: "pay1".into(), project: "p1".into(), line: Some("kitchen".into()) }),
ev("e9", EventBody::ProjectLineSet { project: "p1".into(), line: "kitchen".into(), name: "Kitchen".into(), planned: Haler(0) }),
]);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
let p = &s.projects.projects["p1"];
assert_eq!(p.lines.iter().map(|l| (l.name.as_str(), l.planned)).collect::<Vec<_>>(), [("Tiles and grout", Haler(5_000_000))], "zero removes a line");
assert_eq!((p.status, p.kind), (Status::Active, Kind::Simple));
let t = &s.projects.tasks["t1"];
assert_eq!((t.status, t.done_on), (TaskStatus::Done, Some(d("2026-11-05"))));
assert_eq!(s.projects.payments["pay1"], ("p1".to_string(), Some("kitchen".to_string())));
}
#[test]
fn a_project_is_checked_when_made_and_changed() {
let made = |name: &str, starts: &str, ends: &str, rate: i64| EventBody::ProjectCreated {
project: "p1".into(),
name: name.into(),
kind: Kind::Business,
template: None,
starts: Some(d(starts)),
ends: Some(d(ends)),
colour: Colour::Amber,
rate: Some(Haler(rate)),
};
assert_eq!(refusal(&[], made("", "2026-11-01", "2026-12-01", 0)).as_deref(), Some("a project name must be 1-60 characters"));
assert_eq!(refusal(&[], made(" Web", "2026-11-01", "2026-12-01", 0)).as_deref(), Some("a project name must be 1-60 characters"));
assert_eq!(refusal(&[], made("Web", "2026-12-01", "2026-11-01", 0)).as_deref(), Some("a project ends before it starts"));
assert_eq!(refusal(&[], made("Web", "2026-11-01", "2026-12-01", -1)).as_deref(), Some("an hourly rate is 0-100 000 CZK"));
assert_eq!(refusal(&[], made("Web", "2026-11-01", "2026-12-01", 10_000_001)).as_deref(), Some("an hourly rate is 0-100 000 CZK"));
assert_eq!(refusal(&[project("p1", Kind::Simple)], project("p1", Kind::Simple)).as_deref(), Some("a project with this id exists"));
let fifty: Vec<EventBody> = (0..50).map(|i| project(&format!("p{i}"), Kind::Simple)).collect();
assert_eq!(refusal(&fifty, project("p50", Kind::Simple)).as_deref(), Some("at most 50 projects are open at once"));
let mut one_done = fifty.clone();
one_done.push(EventBody::ProjectStatusSet { project: "p3".into(), status: Status::Done, on: d("2026-11-20") });
assert_eq!(refusal(&one_done, project("p50", Kind::Simple)), None, "a done project frees its place");
let mut full_again = one_done.clone();
full_again.push(project("p50", Kind::Simple));
assert_eq!(refusal(&full_again, EventBody::ProjectStatusSet { project: "p3".into(), status: Status::Active, on: d("2026-11-21") }).as_deref(), Some("at most 50 projects are open at once"), "nor can it reopen into a full list");
let base = [project("p1", Kind::Business), log("l1", "p1", 60, "2026-11-02")];
let to_simple = EventBody::ProjectChanged { project: "p1".into(), name: "Flat".into(), kind: Kind::Simple, starts: None, ends: None, colour: Colour::Coral, rate: None };
assert_eq!(refusal(&base, to_simple).as_deref(), Some("a project with phases or time stays a business project"));
}
#[test]
fn lines_phases_and_tasks_are_checked() {
let base = [project("p1", Kind::Simple), project("b1", Kind::Business)];
let line = |planned: i64, name: &str| EventBody::ProjectLineSet { project: "p1".into(), line: "l".into(), name: name.into(), planned: Haler(planned) };
assert_eq!(refusal(&base, line(-1, "Tiles")).as_deref(), Some("a planned amount is 0-100 000 000 CZK"));
assert_eq!(refusal(&base, line(10_000_000_001, "Tiles")).as_deref(), Some("a planned amount is 0-100 000 000 CZK"));
assert_eq!(refusal(&base, line(100, "")).as_deref(), Some("a budget line name must be 1-60 characters"));
let phase = |project: &str, starts: &str, ends: &str| EventBody::ProjectPhaseSet { project: project.into(), phase: "ph1".into(), name: "Design".into(), starts: d(starts), ends: d(ends) };
assert_eq!(refusal(&base, phase("p1", "2026-11-01", "2026-11-30")).as_deref(), Some("only a business project has phases"));
assert_eq!(refusal(&base, phase("b1", "2026-11-30", "2026-11-01")).as_deref(), Some("a phase ends before it starts"));
assert_eq!(refusal(&base, phase("b1", "2026-11-01", "2026-11-30")), None);
let mut f = fields("Tile the bathroom");
f.line = Some("nope".into());
assert_eq!(refusal(&base, EventBody::TaskCreated { task: "t".into(), project: "p1".into(), fields: f }).as_deref(), Some("no such budget line in the project"));
let mut f = fields("Tile the bathroom");
f.phase = Some("nope".into());
assert_eq!(refusal(&base, EventBody::TaskCreated { task: "t".into(), project: "b1".into(), fields: f }).as_deref(), Some("no such phase in the project"));
let mut f = fields("Tile the bathroom");
f.estimate = Some(Haler(-1));
assert_eq!(refusal(&base, EventBody::TaskCreated { task: "t".into(), project: "p1".into(), fields: f }).as_deref(), Some("an estimate is 0-100 000 000 CZK"));
assert_eq!(refusal(&base, task("t", "p1", "")).as_deref(), Some("a task title must be 1-120 characters"));
assert_eq!(refusal(&base, task("t", "nope", "Tile")).as_deref(), Some("no such project"));
let two_hundred: Vec<EventBody> = std::iter::once(project("p1", Kind::Simple)).chain((0..200).map(|i| task(&format!("t{i}"), "p1", "Job"))).collect();
assert_eq!(refusal(&two_hundred, task("t200", "p1", "One more")).as_deref(), Some("at most 200 open tasks a project"));
let with_task = [project("b1", Kind::Business), phase("b1", "2026-11-01", "2026-11-30"), EventBody::TaskCreated { task: "t".into(), project: "b1".into(), fields: TaskFields { phase: Some("ph1".into()), ..fields("Wireframes") } }];
assert_eq!(refusal(&with_task, EventBody::ProjectPhaseRemoved { project: "b1".into(), phase: "ph1".into() }).as_deref(), Some("tasks are still in this phase"));
}
#[test]
fn payments_go_into_an_open_project_once() {
let base = [project("p1", Kind::Simple), payment("pay1", -50_000, "2026-11-03", "Hornbach")];
assert_eq!(refusal(&base, EventBody::PaymentProjected { payment: "nope".into(), project: "p1".into(), line: None }).as_deref(), Some("no such payment"));
assert_eq!(refusal(&base, EventBody::PaymentProjected { payment: "pay1".into(), project: "p1".into(), line: Some("nope".into()) }).as_deref(), Some("no such budget line in the project"));
assert_eq!(refusal(&base, EventBody::PaymentUnprojected { payment: "pay1".into() }).as_deref(), Some("this payment is in no project"));
let mut done = base.to_vec();
done.push(EventBody::ProjectStatusSet { project: "p1".into(), status: Status::Done, on: d("2026-11-10") });
assert_eq!(refusal(&done, EventBody::PaymentProjected { payment: "pay1".into(), project: "p1".into(), line: None }).as_deref(), Some("the project is done"));
assert_eq!(refusal(&done, EventBody::ProjectRuleSet { merchant_key: "hornbach".into(), project: Some("p1".into()) }).as_deref(), Some("no such open project"));
assert_eq!(refusal(&base, EventBody::ProjectRuleSet { merchant_key: "Hornbach Praha".into(), project: Some("p1".into()) }).as_deref(), Some("not a merchant key"));
}
#[test]
fn time_is_business_only_never_over_a_day_and_invoiced_once() {
let base = [project("p1", Kind::Simple), project("b1", Kind::Business), log("l1", "b1", 600, "2026-11-02")];
assert_eq!(refusal(&base, log("l2", "p1", 60, "2026-11-02")).as_deref(), Some("only a business project logs time"));
assert_eq!(refusal(&base, log("l2", "b1", 0, "2026-11-02")).as_deref(), Some("time logged is 1 minute to 24 hours a day"));
assert_eq!(refusal(&base, log("l2", "b1", 841, "2026-11-02")).as_deref(), Some("time logged is 1 minute to 24 hours a day"));
assert_eq!(refusal(&base, log("l2", "b1", 840, "2026-11-02")), None, "exactly 24 hours");
assert_eq!(refusal(&base, log("l1", "b1", 60, "2026-11-03")).as_deref(), Some("a time entry with this id exists"));
assert_eq!(
refusal(&base, EventBody::TimeLogged { entry: "l2".into(), project: "b1".into(), task: Some("nope".into()), minutes: 60, on: d("2026-11-03"), rate: Haler(0), note: String::new() }).as_deref(),
Some("no such task in the project")
);
// An invoice for the project bills the entry once; billed time stays.
use fiscus_ledger::invoice::{Invoice, InvoiceLine, Language, Party, Supplier};
let party = |name: &str, ico: &str| Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some(ico.into()), dic: None };
let invoice = Invoice {
id: "i1".into(),
number: "20260001".into(),
issued: d("2026-11-05"),
due: d("2026-11-19"),
taxable: None,
customer: party("Pekárna Novák", "45244782"),
lines: vec![InvoiceLine { text: "Web".into(), quantity: 10_000, unit: "h".into(), unit_price: Haler(80_000), vat: None }],
budget: None,
language: Language::Cs,
};
let mut billed = base.to_vec();
billed.push(EventBody::SupplierSet { supplier: Supplier { party: party("Marek Novák", "27074358"), vat_payer: false, reserve_permille: 150, registration: None } });
billed.push(EventBody::InvoiceIssued { invoice });
assert_eq!(refusal(&billed, EventBody::InvoiceProjected { invoice: "i1".into(), project: "p1".into(), entries: vec![] }).as_deref(), Some("only a business project has invoices"));
assert_eq!(refusal(&billed, EventBody::InvoiceProjected { invoice: "i1".into(), project: "b1".into(), entries: vec!["l1".into(), "l1".into()] }).as_deref(), Some("a time entry appears twice"));
billed.push(EventBody::InvoiceProjected { invoice: "i1".into(), project: "b1".into(), entries: vec!["l1".into()] });
assert_eq!(refusal(&billed, EventBody::TimeRemoved { entry: "l1".into() }).as_deref(), Some("this time is invoiced"));
assert_eq!(refusal(&billed, EventBody::InvoiceProjected { invoice: "i1".into(), project: "b1".into(), entries: vec![] }).as_deref(), Some("this invoice is in a project already"));
}
#[test]
fn weeks_start_on_monday_and_time_rounds_once() {
assert_eq!(week_of(d("2026-11-11")), d("2026-11-09"));
assert_eq!(week_of(d("2026-11-09")), d("2026-11-09"));
assert_eq!(week_of(d("2026-11-15")), d("2026-11-09"));
assert_eq!(week_of(d("1970-01-01")), d("1969-12-29"));
let s = State::replay(&[
ev("a", project("b1", Kind::Business)),
ev("b", EventBody::TimeLogged { entry: "l".into(), project: "b1".into(), task: None, minutes: 25, on: d("2026-11-02"), rate: Haler(65_050), note: String::new() }),
]);
// 25 min at 650,50 Kč/h = 271,0416… Kč → 271,04 Kč.
assert_eq!(s.projects.time["l"].amount(), Haler(27_104));
}
#[test]
fn hostile_projects_do_not_parse() {
for bad in [
r#"{"id":"x","at":0,"type":"project.created","project":"p","name":"A","kind":"empire","template":null,"starts":null,"ends":null,"colour":"teal","rate":null}"#,
r#"{"id":"x","at":0,"type":"project.created","project":"p","name":"A","kind":"simple","template":null,"starts":null,"ends":null,"colour":"teal","rate":10.5}"#,
r#"{"id":"x","at":0,"type":"task.created","task":"t","project":"p","fields":{"title":"A","phase":null,"due":null,"estimate":null,"line":null,"assignee":null,"milestone":false,"secret":1}}"#,
r#"{"id":"x","at":0,"type":"time.logged","entry":"e","project":"p","task":null,"minutes":-5,"on":"2026-11-02","rate":0,"note":""}"#,
r#"{"id":"x","at":0,"type":"task.status_set","task":"t","status":"abandoned","on":"2026-11-02"}"#,
] {
assert!(serde_json::from_str::<Event>(bad).is_err(), "{bad}");
}
}
+111
View File
@@ -0,0 +1,111 @@
//! A receipt attached to a payment (`payment.receipt_attached`, docs/07_receipts.md): checked on the way in,
//! visible on the payment (either half of a confirmed pair), the latest one wins; a known shop comes from your
//! latest receipt with its IČO; a receipt fills in exactly one payment or none.
use fiscus_ledger::import::{plan_import, StatementLine};
use fiscus_ledger::{Category, Date, Event, EventBody, Haler, ReceiptInfo, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
fn ev(id: &str, body: EventBody) -> Event {
Event::new(id, Timestamp(0), body)
}
fn added(id: &str, amount: i64, date: &str, merchant: &str) -> EventBody {
EventBody::PaymentAdded { payment: id.into(), amount: Haler(amount), date: d(date), merchant: merchant.into(), category: None, note: None }
}
fn captured(id: &str, amount: i64, date: &str) -> EventBody {
EventBody::PaymentCaptured { payment: id.into(), amount: Haler(amount), date: d(date), merchant: "ALBERT HM 4410".into(), card: None }
}
fn info(shop: &str, ico: Option<&str>) -> ReceiptInfo {
ReceiptInfo { shop: shop.into(), ico: ico.map(Into::into), dic: ico.map(|i| format!("CZ{i}")) }
}
fn attach(payment: &str, r: ReceiptInfo) -> EventBody {
EventBody::ReceiptAttached { payment: payment.into(), receipt: r }
}
fn state(bodies: Vec<EventBody>) -> State {
let mut s = State::default();
for (i, b) in bodies.into_iter().enumerate() {
s.apply(&ev(&format!("e{i}"), b));
}
s
}
#[test]
fn a_receipt_is_checked_and_sits_on_its_payment_which_keeps_its_merchant() {
let s = state(vec![captured("p1", -128_490, "2026-11-16"), attach("p1", info("Albert Hypermarket", Some("25672541")))]);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
let p = s.effective_payment("p1").unwrap();
assert_eq!(p.receipt.unwrap().shop, "Albert Hypermarket");
assert_eq!(p.merchant, "ALBERT HM 4410", "the merchant and its rules stay");
for (bad, why) in [
(attach("nope", info("A", None)), "no such payment"),
(attach("p1", info("", None)), "1-100 characters"),
(attach("p1", info(" Albert", None)), "trimmed"),
(attach("p1", info(&"x".repeat(101), None)), "1-100"),
(attach("p1", info("Albert", Some("25672542"))), "IČO"),
(attach("p1", ReceiptInfo { shop: "Albert".into(), ico: None, dic: Some("SK2020123456".into()) }), "DIČ"),
] {
let mut s = state(vec![captured("p1", -128_490, "2026-11-16")]);
let before = s.effective_payment("p1");
s.apply(&ev("bad", bad));
assert!(s.rejected.last().is_some_and(|r| r.reason.contains(why)), "{why}: {:?}", s.rejected);
assert_eq!(s.effective_payment("p1"), before, "a refusal changes nothing");
}
}
#[test]
fn on_a_confirmed_pair_the_receipt_shows_and_the_later_one_wins() {
let mut s = state(vec![captured("p1", -128_490, "2026-11-16"), attach("p1", info("Albert", Some("25672541")))]);
let line = StatementLine { bank: "test".into(), account: "1/0000".into(), booked: d("2026-11-17"), amount: Haler(-128_490), merchant: "ALBERT HM".into(), counterparty: None, variable_symbol: None, message: None, bank_ref: None };
let mut n = 0;
let plan = plan_import(&s, &[line], &mut || {
n += 1;
format!("i{n}")
}, Timestamp(1));
for e in plan.events.iter().chain(&plan.confirmations) {
s.apply(e);
}
let p = s.effective_payment("p1").unwrap();
assert!(p.line.is_some(), "confirmed by its line");
assert_eq!(p.receipt.as_ref().unwrap().shop, "Albert");
s.apply(&ev("later", attach("p1", info("Albert Hypermarket", Some("25672541")))));
assert_eq!(s.effective_payment("p1").unwrap().receipt.unwrap().shop, "Albert Hypermarket");
}
#[test]
fn a_known_shop_is_your_latest_receipt_with_its_ico() {
let s = state(vec![
added("a", -10_000, "2026-11-01", "x"),
EventBody::PaymentCategorised { payment: "a".into(), category: Category::from("groceries") },
attach("a", info("Albert", Some("25672541"))),
added("b", -20_000, "2026-11-05", "y"),
attach("b", info("Albert Hypermarket", Some("25672541"))),
added("c", -30_000, "2026-11-06", "z"),
attach("c", info("Lékárna", None)),
]);
let k = s.known_shop("25672541").unwrap();
assert_eq!((k.name.as_str(), k.payment.as_str()), ("Albert Hypermarket", "b"));
assert!(s.known_shop("61774031").is_none());
}
#[test]
fn a_receipt_fills_in_exactly_one_payment_or_none() {
let base = vec![captured("p1", -128_490, "2026-11-16"), added("p2", -128_490, "2026-11-30", "x"), added("p3", -9_900, "2026-11-16", "y")];
let s = state(base.clone());
assert_eq!(s.receipt_match(Haler(128_490), d("2026-11-18")).as_deref(), Some("p1"), "same amount, two days later");
assert_eq!(s.receipt_match(Haler(128_490), d("2026-11-20")), None, "four days is too far");
assert_eq!(s.receipt_match(Haler(128_400), d("2026-11-16")), None, "another amount");
let mut two = base.clone();
two.push(added("p4", -128_490, "2026-11-15", "z"));
assert_eq!(state(two).receipt_match(Haler(128_490), d("2026-11-16")), None, "two candidates: nothing guessed");
let mut done = base;
done.push(attach("p1", info("Albert", None)));
assert_eq!(state(done).receipt_match(Haler(128_490), d("2026-11-16")), None, "it has its receipt already");
}
+1
View File
@@ -34,6 +34,7 @@ recorded in `state.rejected` and changes nothing else. Corrections are new event
| `payment.categorised` | an explicit category for one payment | | `payment.categorised` | an explicit category for one payment |
| `payment.assigned` | puts a payment into a budget | | `payment.assigned` | puts a payment into a budget |
| `payment.trial_marked` | "this is a trial", with its end date | | `payment.trial_marked` | "this is a trial", with its end date |
| `payment.receipt_attached` | a receipt for the payment: the shop's name, its IČO and DIČ (docs/07_receipts.md); the payment keeps its merchant |
| `budget.created` / `budget.limit_set` | a monthly budget and its limit | | `budget.created` / `budget.limit_set` | a monthly budget and its limit |
| `rule.created` | "always <merchant> → <category>" | | `rule.created` | "always <merchant> → <category>" |
| `subscription.decided` | keep or cancel, for a merchant, at the amount seen when deciding | | `subscription.decided` | keep or cancel, for a merchant, at the amount seen when deciding |
+3
View File
@@ -50,6 +50,9 @@ with exactly `amount`, `merchant`, `card`, `time`, plus an optional `currency`.
- `merchant`: 1–200 characters, no control characters. `card`: 0–60 characters. - `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. - `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. - At most 4 KiB.
- **A receipt read on the Android phone** (docs/07_receipts.md) comes the same way, with `"source": "receipt"`, the
shop's name as `merchant`, an empty `card`, and optionally `ico` (8 digits with its check digit) and `dic` (`CZ`
and 8–10 digits). An `ico` or `dic` without `"source": "receipt"`, or another `source`, is an error.
*(assumption)* Apple's exact `amount` text is checked against the first real post. *(assumption)* Apple's exact `amount` text is checked against the first real post.
**Android bank notifications.** `recognise(app, title, text, selected)`: **Android bank notifications.** `recognise(app, title, text, selected)`:
+65
View File
@@ -0,0 +1,65 @@
# 06: Projects (v0.7.0)
Projects plan and track a piece of work: a renovation or a trip (**simple**), or a side business or client work
(**business**). A project is a **second label on payments**: a payment in a project still counts in its budget and
its month, so nothing is counted twice. Projects live in the personal log, and the sharing boundary (`share.rs`)
still builds only `payment.shared`.
## Events (`fiscus-ledger::project`)
| Event | What |
|:--|:--|
| `project.created { project, name, kind, template?, starts?, ends?, colour, rate? }` | simple or business; a template id the app knows; an hourly rate for a business |
| `project.changed { … }` | the latest counts. Once a project has phases or time it stays business |
| `project.status_set { project, status, on }` | planning, active, on hold, done (`on` is the day) |
| `project.line_set { project, line, name, planned }` | a budget line; a planned amount of 0 removes it |
| `project.phase_set` / `project.phase_removed` | a business project's phase with dates; one still holding tasks is not removed |
| `payment.projected { payment, project, line? }` / `payment.unprojected` | one project per payment, into an open project |
| `project.rule_set { merchant_key, project? }` | "always this merchant → this project": payments within the project's dates, while it is open |
| `task.created { task, project, fields }` / `task.changed` / `task.status_set` | title, phase, due, estimate, line, assignee, milestone; to do, doing, done (with the day) |
| `time.logged { entry, project, task?, minutes, on, rate, note }` / `time.removed` | business only; invoiced time is not removed |
| `invoice.projected { invoice, project, entries }` | an invoice for a business project, and the time entries it bills (each once) |
| `project.shared { project, budget }` / `project.unshared { project }` | shared with a shared budget's members, one budget at a time; the app mirrors the name, dates, status, lines, phases and tasks through that budget's log, never time, invoices or project rules. Unshared, the members keep their copy |
**What each event accepts:**
- names: 1–60 characters, task titles 1–120, assignees 1–40;
- amounts: 0–100 000 000 Kč;
- hourly rates: 0–100 000 Kč;
- dates: a project or phase cannot end before it starts;
- at most 50 projects open, 100 budget lines, 50 phases and 200 open tasks per project;
- time: at most 24 hours a day across all projects.
Every refusal changes nothing.
**Time** is minutes × the rate per hour, rounded half up to the haléř once per entry. Weeks start on Monday
(`project::week_of`).
## A project's numbers (`fiscus-insight::projects`)
`projects(state, today)` returns a summary per project: the open projects in the order they were made, then the
done ones, the latest first. `project(state, id, today)` adds the details.
**What a summary holds:**
- **planned**: all budget lines together.
- **spent**: money out of the payments in the project, positive; transfers do not count.
- **unplanned**: spent outside any line.
- **lines**: planned, spent, left and over for each.
- **income** (business):
- paid invoices of the project, without VAT;
- money in put into the project, except a statement line that paid one of the project's invoices: that line
*is* the invoice, so it counts once.
If an invoice is marked paid by hand, its money in stays out of the project.
- **profit**: income − spent. **margin**: profit of income, in thousandths.
- **progress**: tasks done, by their estimates when every task has one, else by count.
- **forecast**: spent + the open tasks' estimates.
- **over budget**: spent or the forecast above the plan. One line over is not the project over.
- **late**: an open task past its due date, or the project past its end with tasks open. A done project is never
late.
- **time**:
- minutes, billable and unbilled;
- time by task, and by week.
**Medals** (`rewards`), for a project that is done:
- *Project on budget*: it had a plan, and it spent no more;
- *Finished on time*: it had an end date, and it was done by it.
Both are earned on the day it was done.
+40
View File
@@ -0,0 +1,40 @@
# 07 · Receipts
A receipt becomes a payment, or fills in one you have. The image is read by an OCR outside the core (Lector, on
the PC or the phone, in the app); the core gets its words and reads the fields, and keeps the result.
## Reading (`fiscus_capture::receipt`)
Input: the OCR's lines of words, each word with its box (pixels of the upright image) and its confidence in
**thousandths** (0–1000; the app converts, so no float enters the core). Output: a `Receipt` with the fields it
found, each with its boxes and `sure` (every word read with confidence ≥ 800).
What every Czech receipt must show, found **by its label, never by a shop's layout**:
| Field | How |
|:--|:--|
| total | the rightmost amount on a line labelled `K úhradě`, `Částka k úhradě`, `Celkem k úhradě` (best), `Celkem`, `Celková částka`, `Celkem Kč` (next), `Suma`, `Total`; or alone on the line after the label. A line with `DPH`, `Základ`, `Sazba`, `Mezisoučet`, `Zaokrouhlení` or `Vráceno` is never the total. Among equals, the larger. `1 284,90`, `1284.90`, groups split over words; read from text into haléře; over 10 000 000 Kč is refused whole, never read as its tail |
| date, time | `16.11.2026`, `16. 11. 2026`, `16.11.26`, `2026-11-16`, `16/11/2026` (years 2000–2100); `14:32[:05]`. A date with a time on its line first |
| IČO | 8 digits after `IČ`/`IČO`, with the weighted mod-11 check digit (`invoice::ico_ok`); else from a company DIČ (`CZ` + the IČO) |
| DIČ | `CZ` and 8–10 digits, in one word or two |
| shop | the first line from the top with three letters or more, more letters than twice its digits, and no label (`IČ`, `DIČ`, `Tel`, a web or email address…), above the IČO's line (or among the first six). All capitals become Title Case. **Always `sure: false`**: you check it |
Nothing found is an empty `Receipt`, not an error. Hostile input is bounded: at most 600 lines, 120 words a line,
80 characters a word (else `TooLarge`); control characters are dropped. A proptest feeds random text.
**No shop templates.** As with bank statements, no rule specific to one shop's receipts is written without real
samples of them (`fixtures/receipts/`, none yet).
## In the ledger
- `payment.receipt_attached { payment, receipt: { shop, ico, dic } }` attaches it to any payment (captured, imported,
added; on a confirmed pair it shows on the one payment). Checked: the shop 1–100 characters, trimmed, no control
characters; a valid IČO and DIČ. A later one replaces it.
- **The payment keeps its merchant and merchant key**, so the rules that bring a category stay as they are; the
apps show the shop's name from the receipt.
- `State::known_shop(ico)`: your latest receipt with that IČO, its name and that payment's category. A shop you have
confirmed once is named and categorised from then on.
- `State::receipt_match(total, date)`: the one outflow of exactly that amount within 3 days (`MATCH_DAYS`) that has
no receipt yet. Two or more, or none: `None`, and the receipt is a payment of its own. Nothing is guessed.
## From the phone
The Android app reads the receipt itself and posts only the fields, as the iPhone Shortcut's post with
`"source": "receipt"` and optional `ico` and `dic` (docs/02_capture_sharing.md). The photo never leaves the phone.
+14
View File
@@ -0,0 +1,14 @@
# Receipt samples
Real receipts, **redacted**, as the OCR read them: never the photo (no binaries in git). For each receipt:
```
fixtures/receipts/<shop>-<n>.ocr.json # the OCR's lines of words: [[{"text","confidence","bbox":{x,y,w,h}}]]
fixtures/receipts/<shop>-<n>.expected.json # what fiscus_capture::receipt::read must find
```
Black out card numbers, loyalty numbers and anything personal on the photo **before** it is read; keep the rest
as printed. The photos themselves stay outside git. A rule specific to one shop is written only from its samples
here.
None yet.