Compare commits

...

23 Commits

Author SHA1 Message Date
mnovak 03dc2061f9 [insight] Plans and statistics: category plans, categories of your own, one definition of spending, the month in numbers; v0.5.0
- category.planned (carries forward, zero removes it; spending categories only) and category.created
- fiscus-insight: spending (outflows, inflow, largest-remainder thousandths that add up to 1000), plan (the
  month against its plan with the pace, a suggested plan from the last three months), stats (pie slices, in,
  out, net, six months, same day last month, top merchants, subscriptions' share)
- docs/04_plans_stats.md; 11 new tests
2026-11-06 13:02:39 +01:00
mnovak 4e8e80efb4 [repo] Merge: feature/invoice-language (Czech or English per invoice, PR #6) 2026-11-05 15:06:34 +01:00
mnovak 0f93d0ecb5 [ledger] Invoices: the print language, Czech or English per invoice (Czech when absent); v0.4.1 2026-11-05 15:06:31 +01:00
mnovak 95a8a8965b [repo] Merge: feature/invoices (invoices and the tax reserve, PR #5) 2026-11-05 14:44:44 +01:00
mnovak 0068d4b69a [ledger] Invoices: supplier, invoice numbers as variable symbols, VAT per rate, paid by a matching statement line, the tax reserve; v0.4.0 2026-11-05 14:44:22 +01:00
mnovak deb31374ea [repo] Merge: feature/household (member names, the subscription-names opt-in, PR #4) 2026-11-04 16:17:45 +01:00
mnovak 235f290412 [ledger] Household: profile.named, household.sharing_set, member.named, subscriptions.shared; shared_names sends only service keys; v0.3.0 2026-11-04 16:17:14 +01:00
mnovak 11a4070151 [repo] Merge: fix/explicit-sharing (only an explicit assignment shares a payment, PR #3) 2026-11-03 23:36:10 +01:00
mnovak 64917a9a89 [ledger] Sharing: budget.shared (never the default budget); shared_payment needs an explicit payment.assigned 2026-11-03 23:36:07 +01:00
mnovak f21aef9859 [tests] Sharing: only an explicit assignment shares a payment; a shared budget is never the default 2026-11-03 23:36:07 +01:00
mnovak 101073f853 [repo] Merge: feature/phones-sharing (day 2: capture, splits, share links, QR Platba, PR #2) 2026-11-03 23:28:08 +01:00
mnovak 701f15840a [insight] Household duplicates from shared subscription names 2026-11-03 23:27:26 +01:00
mnovak 2e07d37e86 [capture] Phones: strict Shortcut post and bank-notification templates (registry empty until real samples) 2026-11-03 23:27:26 +01:00
mnovak 241c924d26 [ledger] Sharing: payment.shared/unshared, splits that always add up, share links, capture tokens, account; QR Platba with checked IBAN 2026-11-03 23:27:26 +01:00
mnovak b4474f288e [tests] Day 2: splits, share links, sharing boundary, QR Platba, Shortcut posts, bank notifications, household duplicates 2026-11-03 23:27:26 +01:00
mnovak 8e085bafc3 [docs] Capture and sharing: design note for day 2 (events, capture parsing, splits, QR Platba) 2026-11-03 23:27:26 +01:00
mnovak 2bda5dbbec [repo] Merge: feature/core (day 1: ledger, statements, subscriptions, forecast, PR #1) 2026-11-03 19:55:30 +01:00
mnovak bb7353ce57 [repo] Lockfile 2026-11-03 18:52:43 +01:00
mnovak 9edbae37c1 [insight] Subscriptions: cadence, price change, trials, review, cancel kit; seeded month-end forecast 2026-11-03 18:52:36 +01:00
mnovak 397f9ff00e [statement] Parsing: strict CSV, amount and date fields, decoding; no bank until real samples arrive 2026-11-03 18:52:36 +01:00
mnovak 6572f31b1d [ledger] Core: haléře, dates, the event log and apply(), merchant keys and rules, one-to-one matching, import planning 2026-11-03 18:52:36 +01:00
mnovak da672b132e [repo] Workspace: three crates, MPL-2.0, fixtures/ for real samples 2026-11-03 18:52:36 +01:00
mnovak 9989e954dc [docs] Core: design note for day 1 (ledger, matching, statements, subscriptions, forecast) 2026-11-03 18:52:36 +01:00
62 changed files with 7937 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
target/
Generated
+560
View File
@@ -0,0 +1,560 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bit-set"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269"
dependencies = [
"borsh",
"serde",
]
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "borsh"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
dependencies = [
"borsh-derive",
"bytes",
"cfg_aliases",
]
[[package]]
name = "borsh-derive"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"
dependencies = [
"once_cell",
"proc-macro-crate",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "bytes"
version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures",
"rand_core",
]
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "encoding_rs"
version = "0.8.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5"
dependencies = [
"cfg-if",
"core_detect",
"multiversion_no_op",
"rustversion",
"scopeguard",
"simdutf8",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fiscus-capture"
version = "0.5.0"
dependencies = [
"fiscus-ledger",
"proptest",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "fiscus-insight"
version = "0.5.0"
dependencies = [
"fiscus-ledger",
"serde",
"serde_json",
]
[[package]]
name = "fiscus-ledger"
version = "0.5.0"
dependencies = [
"proptest",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "fiscus-statement"
version = "0.5.0"
dependencies = [
"encoding_rs",
"fiscus-ledger",
"proptest",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"rand_core",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "multiversion_no_op"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "proptest"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
dependencies = [
"bit-set",
"bit-vec",
"bitflags",
"chacha20",
"core_detect",
"num-traits",
"rand",
"rand_xorshift",
"regex-syntax",
"rusty-fork",
"tempfile",
"unarray",
]
[[package]]
name = "quick-error"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"getrandom",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_xorshift"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
dependencies = [
"rand_core",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rustix"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "rusty-fork"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
dependencies = [
"fnv",
"quick-error",
"tempfile",
"wait-timeout",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "toml_datetime"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.17+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
dependencies = [
"winnow",
]
[[package]]
name = "unarray"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "winnow"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
dependencies = [
"memchr",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+15
View File
@@ -0,0 +1,15 @@
[workspace]
resolver = "2"
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight", "crates/fiscus-capture"]
[workspace.package]
version = "0.5.0"
edition = "2021"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/FiscusPublic"
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
proptest = "1"
+373
View File
@@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+15
View File
@@ -0,0 +1,15 @@
# FiscusPublic
The pure core of **Fiscus Domi**, a household money app: money in whole haléře, the append-only event log
and the state derived from it, merchant rules, capture ↔ statement matching, strict statement parsing,
subscription / price-change / trial detection and a seeded month-end forecast. No I/O, no clock, no floats.
| Crate | |
|:--|:--|
| `fiscus-ledger` | `Haler`, `Date`, events, `State::apply`, merchant keys, matching, import planning, invoices, category plans |
| `fiscus-statement` | strict CSV, Czech amount and date fields, decoding; bank parsers only from real samples |
| `fiscus-insight` | subscriptions, cancel kits, the forecast, spending, the month against its plan, the month in numbers |
Design: [docs/01_core.md](docs/01_core.md), [02](docs/02_capture_sharing.md), [03 invoices](docs/03_invoices.md), [04 plans and statistics](docs/04_plans_stats.md). Tests: `cargo test --workspace`.
Licence: MPL-2.0.
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "fiscus-capture"
description = "Fiscus Domi: what the phones send (the iPhone Shortcut post, Android bank notifications), parsed strictly"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
fiscus-ledger = { path = "../fiscus-ledger" }
serde.workspace = true
serde_json = { workspace = true, features = ["raw_value"] }
thiserror.workspace = true
[dev-dependencies]
proptest.workspace = true
+26
View File
@@ -0,0 +1,26 @@
//! An amount as a phone writes it: `129`, `129,50`, `1 234,50 Kč`, `CZK 129.00`. Read from its text with
//! `Haler::parse_czk`, never through a float.
use fiscus_ledger::Haler;
/// The largest single card payment Fiscus believes: 10 000 000 CZK.
pub const MAX: Haler = Haler(1_000_000_000);
/// A positive amount in CZK, with an optional `Kč` or `CZK` before or after it. A no-break space (U+00A0) or
/// narrow no-break space (U+202F) between thousands counts as a space.
pub fn parse_positive(text: &str) -> Option<Haler> {
let t: String = text.chars().map(|c| if c == '\u{a0}' || c == '\u{202f}' { ' ' } else { c }).collect();
let mut t = t.trim();
for unit in ["Kč", "CZK"] {
if let Some(rest) = t.strip_suffix(unit) {
t = rest.trim_end();
break;
}
if let Some(rest) = t.strip_prefix(unit) {
t = rest.trim_start();
break;
}
}
let h = Haler::parse_czk(t).ok()?;
(h.0 > 0 && h <= MAX).then_some(h)
}
+28
View File
@@ -0,0 +1,28 @@
//! Fiscus Domi's capture: what the phones send, parsed strictly. Both are hostile input: a post or a
//! notification becomes one [`Capture`] or nothing, never a partial payment. Pure: times are parameters.
pub mod amount;
pub mod notification;
pub mod shortcut;
use fiscus_ledger::{Date, Haler, Timestamp};
/// One card payment a phone saw: an outflow, so `amount` is negative.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Capture {
pub amount: Haler,
pub date: Date,
pub at: Timestamp,
pub merchant: String,
pub card: Option<String>,
}
/// 1–200 characters, no control characters.
pub(crate) fn merchant_ok(s: &str) -> bool {
!s.trim().is_empty() && s.chars().count() <= 200 && !s.chars().any(|c| c.is_control())
}
/// 0–60 characters, no control characters.
pub(crate) fn card_ok(s: &str) -> bool {
s.chars().count() <= 60 && !s.chars().any(|c| c.is_control())
}
+179
View File
@@ -0,0 +1,179 @@
//! Android bank notifications. A notification is read only if it comes from a bank app the person selected,
//! and becomes a payment only if a template **written from real samples** matches it exactly. Anything else
//! is `Unknown`: counted by the app, never guessed.
use crate::{amount, card_ok, merchant_ok, Capture};
use fiscus_ledger::{Date, Timestamp};
/// One notification format of one bank app. `text` (and `title`, if given) are literal text with holes:
/// `{amount}`, `{merchant}`, `{card}` and `{_}` (anything, ignored). Each hole matches at least one character.
#[derive(Clone, Copy, Debug)]
pub struct Template {
/// The Android package name of the bank app.
pub app: &'static str,
/// The bank, as `fixtures/notifications/<bank>/` names it.
pub bank: &'static str,
pub title: Option<&'static str>,
pub text: &'static str,
}
/// The registry. Empty: no bank notification samples exist yet (`fixtures/notifications/README.md`).
pub const TEMPLATES: &[Template] = &[];
/// Notifications longer than this are not read.
pub const MAX_TEXT: usize = 1000;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Recognised {
/// From an app the person did not select: not read at all.
NotSelected,
/// From a selected app, but no template matches (or two readings disagree).
Unknown,
Payment(Capture),
}
/// [`recognise_with`] over the registry.
pub fn recognise(app: &str, title: &str, text: &str, date: Date, at: Timestamp, selected: &[&str]) -> Recognised {
recognise_with(TEMPLATES, app, title, text, date, at, selected)
}
/// `date` and `at` are when the notification was posted (the phone's local date and the instant).
pub fn recognise_with(
templates: &[Template],
app: &str,
title: &str,
text: &str,
date: Date,
at: Timestamp,
selected: &[&str],
) -> Recognised {
if !selected.contains(&app) {
return Recognised::NotSelected;
}
if text.chars().count() > MAX_TEXT || title.chars().count() > MAX_TEXT {
return Recognised::Unknown;
}
let mut found: Option<Capture> = None;
for t in templates.iter().filter(|t| t.app == app) {
if t.title.is_some_and(|pat| matches(pat, title).is_empty()) {
continue;
}
let all = matches(t.text, text);
if all.len() > MAX_READINGS {
return Recognised::Unknown;
}
for fields in all {
let Some(c) = capture(&fields, date, at) else { continue };
match &found {
None => found = Some(c),
Some(prev) if *prev == c => {}
Some(_) => return Recognised::Unknown,
}
}
}
found.map(Recognised::Payment).unwrap_or(Recognised::Unknown)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Hole {
Amount,
Merchant,
Card,
Any,
}
#[derive(Debug)]
enum Piece<'a> {
Lit(&'a str),
Hole(Hole),
}
fn pieces(pattern: &str) -> Vec<Piece<'_>> {
let mut out = Vec::new();
let mut rest = pattern;
while let Some(i) = rest.find('{') {
let Some(j) = rest[i..].find('}') else { break };
let hole = match &rest[i + 1..i + j] {
"amount" => Some(Hole::Amount),
"merchant" => Some(Hole::Merchant),
"card" => Some(Hole::Card),
"_" => Some(Hole::Any),
_ => None,
};
match hole {
Some(h) => {
if i > 0 {
out.push(Piece::Lit(&rest[..i]));
}
out.push(Piece::Hole(h));
}
None => out.push(Piece::Lit(&rest[..i + j + 1])),
}
rest = &rest[i + j + 1..];
}
if !rest.is_empty() {
out.push(Piece::Lit(rest));
}
out
}
type Fields<'a> = Vec<(Hole, &'a str)>;
/// More readings than this of one notification is not a format, it is noise.
const MAX_READINGS: usize = 16;
/// Every way `text` matches `pattern` exactly, as the text of each hole.
fn matches<'a>(pattern: &str, text: &'a str) -> Vec<Fields<'a>> {
let ps = pieces(pattern);
let mut out = Vec::new();
walk(&ps, text, Vec::new(), &mut out);
out
}
fn walk<'a>(ps: &[Piece], text: &'a str, acc: Fields<'a>, out: &mut Vec<Fields<'a>>) {
if out.len() > MAX_READINGS {
return; // the caller treats this many readings as unknown
}
match ps.first() {
None => {
if text.is_empty() {
out.push(acc);
}
}
Some(Piece::Lit(l)) => {
if let Some(rest) = text.strip_prefix(l) {
walk(&ps[1..], rest, acc, out);
}
}
Some(Piece::Hole(h)) => {
// The hole takes 1.. characters; with nothing after it, all the rest.
let ends: Vec<usize> = match ps.get(1) {
None => vec![text.len()],
Some(Piece::Lit(l)) => text.match_indices(l).map(|(i, _)| i).filter(|i| *i > 0).collect(),
Some(Piece::Hole(_)) => text.char_indices().map(|(i, _)| i).skip(1).chain([text.len()]).collect(),
};
for end in ends {
if end == 0 {
continue;
}
let mut next = acc.clone();
next.push((*h, &text[..end]));
walk(&ps[1..], &text[end..], next, out);
}
}
}
}
fn capture(fields: &Fields, date: Date, at: Timestamp) -> Option<Capture> {
let get = |h: Hole| fields.iter().find(|(k, _)| *k == h).map(|(_, v)| v.trim());
let amount = amount::parse_positive(get(Hole::Amount)?)?.checked_neg().ok()?;
let merchant = get(Hole::Merchant)?;
if !merchant_ok(merchant) {
return None;
}
let card = get(Hole::Card);
if card.is_some_and(|c| !card_ok(c)) {
return None;
}
Some(Capture { amount, date, at, merchant: merchant.to_string(), card: card.filter(|c| !c.is_empty()).map(str::to_string) })
}
+120
View File
@@ -0,0 +1,120 @@
//! The iPhone Shortcut post (`POST /inbox`). We write the Shortcut, so the shape is ours:
//! `{"amount", "merchant", "card", "time"}` and an optional `"currency": "CZK"`, nothing else.
use crate::{amount, card_ok, merchant_ok, Capture};
use fiscus_ledger::{Date, Timestamp};
use serde::Deserialize;
use serde_json::value::RawValue;
/// The largest body the inbox reads.
pub const MAX_BODY: usize = 4096;
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum CaptureError {
#[error("the post is larger than 4 KiB")]
TooLarge,
#[error("the post is not a JSON object with exactly amount, merchant, card and time")]
Malformed,
#[error("the amount is not a positive amount in CZK")]
Amount,
#[error("the currency is not CZK")]
Currency,
#[error("the merchant must be 1-200 characters without control characters")]
Merchant,
#[error("the card name must be at most 60 characters without control characters")]
Card,
#[error("the time is not ISO 8601 with an offset (2026-11-03T14:05:00+01:00)")]
Time,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Post<'a> {
#[serde(borrow)]
amount: &'a RawValue,
merchant: String,
card: String,
time: String,
currency: Option<String>,
}
/// One post → one capture, or the first thing wrong with it.
pub fn parse(body: &[u8]) -> Result<Capture, CaptureError> {
if body.len() > MAX_BODY {
return Err(CaptureError::TooLarge);
}
let post: Post = serde_json::from_slice(body).map_err(|_| CaptureError::Malformed)?;
let raw = post.amount.get();
let text: String = if raw.starts_with('"') {
serde_json::from_str(raw).map_err(|_| CaptureError::Amount)?
} else if raw.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
raw.to_string()
} else {
return Err(CaptureError::Amount);
};
let amount = amount::parse_positive(&text).ok_or(CaptureError::Amount)?;
if post.currency.as_deref().is_some_and(|c| c != "CZK") {
return Err(CaptureError::Currency);
}
if !merchant_ok(&post.merchant) {
return Err(CaptureError::Merchant);
}
if !card_ok(&post.card) {
return Err(CaptureError::Card);
}
let (date, at) = parse_time(&post.time).ok_or(CaptureError::Time)?;
let card = post.card.trim();
Ok(Capture {
amount: amount.checked_neg().map_err(|_| CaptureError::Amount)?,
date,
at,
merchant: post.merchant.trim().to_string(),
card: (!card.is_empty()).then(|| card.to_string()),
})
}
fn num(s: &str) -> Option<u32> {
(!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok()).flatten()
}
/// `YYYY-MM-DDTHH:MM[:SS[.fff]](Z|±HH:MM)` → the local date written in it, and the instant.
pub fn parse_time(s: &str) -> Option<(Date, Timestamp)> {
let (date, rest) = s.split_once('T')?;
if date.len() != 10 || &date[4..5] != "-" || &date[7..8] != "-" {
return None;
}
let day = Date::from_ymd(num(&date[..4])? as i32, num(&date[5..7])?, num(&date[8..])?)?;
let (clock, offset_min) = if let Some(c) = rest.strip_suffix('Z') {
(c, 0i64)
} else {
let i = rest.rfind(['+', '-'])?;
let (c, off) = rest.split_at(i);
let sign = if off.starts_with('-') { -1 } else { 1 };
let off = &off[1..];
if off.len() != 5 || &off[2..3] != ":" {
return None;
}
let (h, m) = (num(&off[..2])?, num(&off[3..])?);
if h > 14 || m > 59 {
return None;
}
(c, sign * (h as i64 * 60 + m as i64))
};
let (hms, millis) = match clock.split_once('.') {
Some((hms, frac)) if (1..=3).contains(&frac.len()) => (hms, num(frac)? as i64 * 10i64.pow(3 - frac.len() as u32)),
Some(_) => return None,
None => (clock, 0),
};
let parts: Vec<&str> = hms.split(':').collect();
if !(2..=3).contains(&parts.len()) || parts.iter().any(|p| p.len() != 2) {
return None;
}
let (h, m) = (num(parts[0])?, num(parts[1])?);
let sec = if parts.len() == 3 { num(parts[2])? } else { 0 };
if h > 23 || m > 59 || sec > 59 {
return None;
}
let local_s = day.days() as i64 * 86_400 + h as i64 * 3600 + m as i64 * 60 + sec as i64;
let utc_ms = (local_s - offset_min * 60) * 1000 + millis;
Some((day, Timestamp(utc_ms)))
}
+133
View File
@@ -0,0 +1,133 @@
//! Day-2 mandatory test: Android bank notifications. Every real fixture parses; a notification from an app
//! the person did not select is never read; an unknown format is ignored, never guessed.
//!
//! The registry has no templates until real samples exist, so the engine is tested here with SYNTHETIC
//! templates that live only in this file. They are not any bank's format.
use fiscus_capture::notification::{recognise, recognise_with, Recognised, Template, TEMPLATES};
use fiscus_ledger::{Date, Haler, Timestamp};
use serde::Deserialize;
use std::path::{Path, PathBuf};
const APP: &str = "test.synthetic.bank";
const SYNTHETIC: &[Template] = &[
Template { app: APP, bank: "synthetic", title: Some("Card payment"), text: "Paid {amount} at {merchant} with card {card}." },
Template { app: APP, bank: "synthetic", title: None, text: "{_}: {amount} - {merchant}" },
];
fn day() -> Date {
"2026-11-03".parse().unwrap()
}
fn at() -> Timestamp {
Timestamp(1_793_711_100_000)
}
fn run(app: &str, title: &str, text: &str, selected: &[&str]) -> Recognised {
recognise_with(SYNTHETIC, app, title, text, day(), at(), selected)
}
#[test]
fn a_notification_matching_a_template_is_a_payment() {
match run(APP, "Card payment", "Paid 129,50 Kč at Albert Praha with card *1234.", &[APP]) {
Recognised::Payment(c) => {
assert_eq!(c.amount, Haler(-12_950));
assert_eq!(c.merchant, "Albert Praha");
assert_eq!(c.card.as_deref(), Some("*1234"));
assert_eq!((c.date, c.at), (day(), at()));
}
other => panic!("{other:?}"),
}
assert!(matches!(run(APP, "anything", "Debit: 1 234,00 CZK - Shell", &[APP]), Recognised::Payment(c) if c.amount == Haler(-123_400) && c.merchant == "Shell"));
}
#[test]
fn an_app_that_was_not_selected_is_never_read() {
// Even text that a template would match: the app decides first.
assert_eq!(run(APP, "Card payment", "Paid 129,50 Kč at Albert with card *1234.", &[]), Recognised::NotSelected);
assert_eq!(run(APP, "Card payment", "Paid 129,50 Kč at Albert with card *1234.", &["other.bank"]), Recognised::NotSelected);
assert_eq!(run("com.chat.app", "Card payment", "Paid 129,50 Kč at Albert with card *1234.", &[APP]), Recognised::NotSelected);
}
#[test]
fn an_unknown_format_is_ignored_never_guessed() {
for (title, text) in [
("Card payment", "Paid 129,50 Kč at Albert with card *1234"), // the final full stop is missing
("Card payment", "Paid around 129,50 Kč at Albert with card *1234."),
("Card payment", "Paid 129,50 EUR at Albert with card *1234."),
("Card payment", "Paid 0 Kč at Albert with card *1234."),
("Balance", "Your balance is 12 000 Kč"),
("Card payment", ""),
] {
assert_eq!(run(APP, title, text, &[APP]), Recognised::Unknown, "{text}");
}
let long = format!("Debit: {} - Shell", "1".repeat(5000));
assert_eq!(run(APP, "x", &long, &[APP]), Recognised::Unknown);
}
#[test]
fn an_ambiguous_match_is_unknown() {
// `{_}: {amount} - {merchant}` matches "A: 1 - B: 2 - C" two ways with different amounts.
assert_eq!(run(APP, "x", "A: 1 - B: 2 - C", &[APP]), Recognised::Unknown);
}
#[test]
fn the_real_registry_is_used_by_recognise() {
// With no templates for an app, a selected app's notification is unknown, never a payment.
for t in TEMPLATES {
assert!(!t.app.is_empty() && !t.bank.is_empty() && !t.text.is_empty());
}
assert_eq!(recognise(APP, "Card payment", "Paid 129,50 Kč at Albert with card *1234.", day(), at(), &[APP]), Recognised::Unknown);
}
/// A real, redacted notification and what it must become (`fixtures/notifications/<bank>/*.json`).
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Sample {
app: String,
title: String,
text: String,
/// `null` for a notification that is not a payment (a balance, a login) and must stay unknown.
expected: Option<Expected>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Expected {
amount: i64,
merchant: String,
card: Option<String>,
}
fn samples() -> Vec<PathBuf> {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/notifications");
let mut out = Vec::new();
let Ok(banks) = std::fs::read_dir(&root) else { return out };
for bank in banks.flatten().filter(|e| e.path().is_dir()) {
for f in std::fs::read_dir(bank.path()).unwrap().flatten() {
if f.path().extension().is_some_and(|e| e == "json") {
out.push(f.path());
}
}
}
out.sort();
out
}
#[test]
fn every_real_fixture_parses_to_what_it_must() {
let all = samples();
eprintln!("notification fixtures: {}", all.len());
for path in all {
let s: Sample = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
let got = recognise(&s.app, &s.title, &s.text, day(), at(), &[s.app.as_str()]);
match (&s.expected, got) {
(None, Recognised::Unknown) => {}
(Some(e), Recognised::Payment(c)) => {
assert_eq!((c.amount, c.merchant.as_str(), c.card.as_deref()), (Haler(e.amount), e.merchant.as_str(), e.card.as_deref()), "{}", path.display());
}
(_, got) => panic!("{}: {got:?}", path.display()),
}
}
}
+92
View File
@@ -0,0 +1,92 @@
//! Day-2 mandatory test (the inbox's half in the core): the iPhone Shortcut post is hostile input. A malformed,
//! oversized or ambiguous body is an error with a reason, never a partial payment.
use fiscus_capture::shortcut::{parse, CaptureError, MAX_BODY};
use fiscus_ledger::{Date, Haler, Timestamp};
use proptest::prelude::*;
/// 2026-11-03T13:05:00Z in milliseconds.
const AT: i64 = 1_793_711_100_000;
fn post(amount: &str) -> String {
format!(r#"{{"amount":{amount},"merchant":"ALBERT HYPERMARKET","card":"Apple Card","time":"2026-11-03T14:05:00+01:00"}}"#)
}
#[test]
fn a_good_post_becomes_one_outflow() {
let c = parse(post("129.5").as_bytes()).unwrap();
assert_eq!(c.amount, Haler(-12_950));
assert_eq!(c.merchant, "ALBERT HYPERMARKET");
assert_eq!(c.card.as_deref(), Some("Apple Card"));
assert_eq!(c.date, "2026-11-03".parse::<Date>().unwrap());
// 14:05 at +01:00 is 13:05 UTC.
assert_eq!(c.at, Timestamp(AT));
}
#[test]
fn the_amount_forms_shortcuts_writes_are_read_from_text_never_as_a_float() {
for (text, want) in [
("129", 12_900),
("129.00", 12_900),
("0.1", 10),
(r#""129,50""#, 12_950),
(r#""129,50 Kč""#, 12_950),
(r#""Kč 129,50""#, 12_950),
(r#""CZK 1 234,50""#, 123_450),
("\"1\u{a0}234,50\u{a0}Kč\"", 123_450),
("\"1\u{202f}234,50 CZK\"", 123_450),
] {
assert_eq!(parse(post(text).as_bytes()).map(|c| c.amount), Ok(Haler(-want)), "{text}");
}
for text in ["0", "-129", "1e3", "129.555", "\"\"", "\"abc\"", "\"$129\"", "\"129 EUR\"", "null", "true", "[129]", "99999999999"] {
assert_eq!(parse(post(text).as_bytes()).map(|c| c.amount), Err(CaptureError::Amount), "{text}");
}
}
#[test]
fn every_field_is_checked() {
let ok = r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z"}"#;
assert!(parse(ok.as_bytes()).is_ok());
let cases: &[(&str, CaptureError)] = &[
(r#"{"merchant":"M","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Malformed),
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z","extra":1}"#, CaptureError::Malformed),
(r#"{"amount":1,"amount":2,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Malformed),
(r#"{"amount":1,"merchant":"","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Merchant),
(r#"{"amount":1,"merchant":"a\u0000b","card":"","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Merchant),
(r#"{"amount":1,"merchant":"M","card":"a\nb","time":"2026-11-03T14:05:00Z"}"#, CaptureError::Card),
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03 14:05"}"#, CaptureError::Time),
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-02-30T14:05:00Z"}"#, CaptureError::Time),
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T24:05:00Z"}"#, CaptureError::Time),
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00"}"#, CaptureError::Time),
(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z","currency":"EUR"}"#, CaptureError::Currency),
(r#"[1,2]"#, CaptureError::Malformed),
("", CaptureError::Malformed),
];
for (body, want) in cases {
assert_eq!(parse(body.as_bytes()).err().as_ref(), Some(want), "{body}");
}
let long = format!(r#"{{"amount":1,"merchant":"{}","card":"","time":"2026-11-03T14:05:00Z"}}"#, "m".repeat(201));
assert_eq!(parse(long.as_bytes()).err(), Some(CaptureError::Merchant));
assert!(parse(r#"{"amount":1,"merchant":"M","card":"","time":"2026-11-03T14:05:00Z","currency":"CZK"}"#.as_bytes()).is_ok());
}
#[test]
fn an_oversized_body_is_refused_before_parsing() {
let mut big = post("1").into_bytes();
big.resize(MAX_BODY + 1, b' ');
assert_eq!(parse(&big).err(), Some(CaptureError::TooLarge));
}
proptest! {
#[test]
fn random_bytes_never_panic_and_never_half_parse(bytes in proptest::collection::vec(any::<u8>(), 0..600)) {
let _ = parse(&bytes);
}
#[test]
fn every_truncation_of_a_good_post_is_an_error(cut in 0usize..90) {
let full = post("\"129,50 Kč\"");
let cut = cut.min(full.len() - 1);
prop_assert!(parse(&full.as_bytes()[..cut]).is_err());
}
}
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "fiscus-insight"
description = "Fiscus Domi: subscriptions, price creep, trials, cancel kits, the month-end forecast"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
fiscus-ledger = { path = "../fiscus-ledger" }
serde.workspace = true
[dev-dependencies]
serde_json.workspace = true
+69
View File
@@ -0,0 +1,69 @@
//! The cancel kit: where to cancel a known provider, and a polite email to send when there is no page.
use crate::subscriptions::Subscription;
use serde::{Deserialize, Serialize};
/// `(a word in the merchant key, provider, the page where its subscription is cancelled)`.
/// Kept short on purpose: only pages that are the provider's own account or cancel page.
const PROVIDERS: &[(&str, &str, &str)] = &[
("netflix", "Netflix", "https://www.netflix.com/cancelplan"),
("spotify", "Spotify", "https://www.spotify.com/account/subscription/"),
("youtube", "YouTube", "https://www.youtube.com/paid_memberships"),
("disney", "Disney+", "https://www.disneyplus.com/account"),
("apple", "Apple", "https://apps.apple.com/account/subscriptions"),
("google", "Google Play", "https://play.google.com/store/account/subscriptions"),
("microsoft", "Microsoft", "https://account.microsoft.com/services"),
("xbox", "Microsoft", "https://account.microsoft.com/services"),
("adobe", "Adobe", "https://account.adobe.com/plans"),
];
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelKit {
pub provider: Option<String>,
pub url: Option<String>,
pub email_subject: String,
pub email_body: String,
}
impl CancelKit {
/// A `mailto:` link with the subject and body filled in and no recipient (the user adds the provider's
/// address).
pub fn mailto(&self) -> String {
format!("mailto:?subject={}&body={}", percent(&self.email_subject), percent(&self.email_body))
}
}
fn percent(s: &str) -> String {
let mut out = String::with_capacity(s.len() * 3);
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
pub fn cancel_kit(sub: &Subscription) -> CancelKit {
let words: Vec<&str> = sub.merchant_key.split(' ').collect();
let known = PROVIDERS.iter().find(|(w, _, _)| words.contains(w));
let name = known.map(|(_, p, _)| p.to_string()).unwrap_or_else(|| sub.merchant.clone());
let cadence = match sub.cadence {
crate::subscriptions::Cadence::Monthly => "monthly",
crate::subscriptions::Cadence::Yearly => "yearly",
};
let last = sub.charges.last().map(|c| c.date.to_string()).unwrap_or_default();
CancelKit {
provider: known.map(|(_, p, _)| p.to_string()),
url: known.map(|(_, _, u)| u.to_string()),
email_subject: format!("Cancel my {name} subscription"),
email_body: format!(
"Hello,\n\nplease cancel my {name} subscription ({cadence}, {} CZK, last charged on {last}) \
with effect from the end of the current period, and confirm the cancellation by email.\n\n\
Please do not charge my card again.\n\nThank you.",
sub.cost.to_czk()
),
}
}
+154
View File
@@ -0,0 +1,154 @@
//! The month-end forecast: a seeded bootstrap Monte Carlo over past daily spending, integers only.
//! Same inputs and seed → the same output, on every machine.
use crate::subscriptions::{Insight, Status};
use fiscus_ledger::{Date, Haler, State};
use serde::{Deserialize, Serialize};
/// Days of history the forecast draws from.
pub const HISTORY_DAYS: i32 = 90;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ForecastInput {
/// Spending (positive) on each past day; a day with nothing is a zero.
pub history: Vec<Haler>,
/// Spent so far this month.
pub spent: Haler,
/// Days after today until the month ends.
pub days_left: u32,
pub limit: Haler,
/// Known charges still due this month (subscriptions).
pub known: Haler,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Forecast {
/// The chance to stay at or under the limit, in basis points (10 000 = certain).
pub chance_bp: u32,
pub p10: Haler,
pub p50: Haler,
pub p90: Haler,
pub runs: u32,
pub history_days: u32,
}
/// xoshiro256** seeded through SplitMix64: small, fast, and fixed here so no dependency can change it.
struct Rng([u64; 4]);
impl Rng {
fn new(seed: u64) -> Rng {
let mut x = seed;
let mut next = || {
x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = x;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
};
Rng([next(), next(), next(), next()])
}
fn next(&mut self) -> u64 {
let s = &mut self.0;
let result = s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9);
let t = s[1] << 17;
s[2] ^= s[0];
s[3] ^= s[1];
s[1] ^= s[2];
s[0] ^= s[3];
s[2] ^= t;
s[3] = s[3].rotate_left(45);
result
}
/// Uniform in `0..n` without modulo bias (Lemire).
fn below(&mut self, n: u64) -> u64 {
let threshold = n.wrapping_neg() % n;
loop {
let m = (self.next() as u128) * (n as u128);
if (m as u64) >= threshold {
return (m >> 64) as u64;
}
}
}
}
pub fn forecast(input: &ForecastInput, seed: u64, runs: u32) -> Forecast {
let runs = runs.max(1);
let base = input.spent.0.saturating_add(input.known.0);
let mut rng = Rng::new(seed);
let mut ends: Vec<i64> = (0..runs)
.map(|_| {
let mut total = base;
if !input.history.is_empty() {
for _ in 0..input.days_left {
let i = rng.below(input.history.len() as u64) as usize;
total = total.saturating_add(input.history[i].0);
}
}
total
})
.collect();
ends.sort_unstable();
let under = ends.iter().filter(|e| **e <= input.limit.0).count() as u64;
let at = |pct: usize| Haler(ends[(ends.len() - 1) * pct / 100]);
Forecast {
chance_bp: (under * 10_000 / runs as u64) as u32,
p10: at(10),
p50: at(50),
p90: at(90),
runs,
history_days: input.history.len() as u32,
}
}
/// The forecast for one budget this month. Subscription charges are taken out of the history and added back
/// as known charges on their due dates, so they are neither missed nor counted twice.
pub fn budget_forecast(state: &State, insight: &Insight, budget: &str, today: Date, seed: u64, runs: u32) -> Option<Forecast> {
let limit = state.budgets.get(budget)?.limit;
let subscription_payments: std::collections::BTreeSet<&str> =
insight.subscriptions.iter().flat_map(|s| s.charges.iter().map(|c| c.payment.as_str())).collect();
let mine: Vec<_> = state
.effective_payments()
.into_iter()
.filter(|p| p.budget.as_deref() == Some(budget) && p.amount.0 < 0)
.collect();
let cost = |p: &fiscus_ledger::EffectivePayment| -p.amount.0;
let month_start = today.month_start();
let spent = Haler(mine.iter().filter(|p| p.date >= month_start && p.date <= today).map(cost).sum());
let first = mine.iter().map(|p| p.date).min();
let window_start = match first {
Some(f) if f > today.add_days(-HISTORY_DAYS) => f,
_ => today.add_days(-HISTORY_DAYS),
};
let days = window_start.days_until(today).max(0) as usize; // days before today
let mut history = vec![0i64; days];
for p in mine.iter().filter(|p| !subscription_payments.contains(p.id.as_str())) {
let i = window_start.days_until(p.date);
if i >= 0 && (i as usize) < days {
history[i as usize] += cost(p);
}
}
let month_end = today.month_end();
let known = Haler(
insight
.subscriptions
.iter()
.filter(|s| s.status == Status::Active && s.budget.as_deref() == Some(budget))
.filter(|s| s.next_charge > today && s.next_charge <= month_end)
.map(|s| s.cost.0)
.sum(),
);
let input = ForecastInput {
history: history.into_iter().map(Haler).collect(),
spent,
days_left: today.days_until(month_end).max(0) as u32,
limit,
known,
};
Some(forecast(&input, seed, runs))
}
+51
View File
@@ -0,0 +1,51 @@
//! Household duplicates: two or more members paying for the same service ("You both pay Spotify"). Runs only
//! on the subscription names members chose to share into the household budget.
use crate::subscriptions::{analyse, Status};
use fiscus_ledger::merchant::merchant_key;
use fiscus_ledger::{Date, State};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Duplicate {
/// The service: the first word of the merchant key (`PAYPAL *SPOTIFY`, `Spotify AB` → `spotify`).
pub key: String,
/// Who pays it, sorted.
pub members: Vec<String>,
}
/// The first word of the merchant key, if it is at least three letters long.
pub fn service_key(name: &str) -> Option<String> {
let key = merchant_key(name);
let first = key.split(' ').next()?;
(first.chars().count() >= 3).then(|| first.to_string())
}
/// `(member, the subscription names they shared)` → every service two or more members pay, by key.
pub fn household_duplicates(shared: &[(String, Vec<String>)]) -> Vec<Duplicate> {
let mut by_key: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for (member, names) in shared {
for key in names.iter().filter_map(|n| service_key(n)) {
by_key.entry(key).or_default().insert(member.clone());
}
}
by_key
.into_iter()
.filter(|(_, m)| m.len() >= 2)
.map(|(key, m)| Duplicate { key, members: m.into_iter().collect() })
.collect()
}
/// What a member who opted in shares: the service key of every subscription they still pay (active, or charged
/// after a cancel), sorted, at most 100. Only the key leaves, never the merchant text with its references.
pub fn shared_names(state: &State, today: Date) -> Vec<String> {
let keys: BTreeSet<String> = analyse(state, today)
.subscriptions
.iter()
.filter(|s| matches!(s.status, Status::Active | Status::ChargedAfterCancel))
.filter_map(|s| service_key(&s.merchant))
.filter(|k| k.chars().count() <= 40)
.collect();
keys.into_iter().take(100).collect()
}
+11
View File
@@ -0,0 +1,11 @@
//! 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
//! your plan. Pure: "today" and seeds are parameters.
pub mod cancel;
pub mod forecast;
pub mod household;
pub mod plan;
pub mod spending;
pub mod stats;
pub mod subscriptions;
+129
View File
@@ -0,0 +1,129 @@
//! The month against your plan: for each category, what you meant to spend (`category.planned`), what you
//! spent, what is left, and whether you are ahead of the pace the plan allows by today. Only your own payments
//! count, as in the forecast; what other members of a shared budget spend is theirs.
use crate::spending::{between, outflows};
use fiscus_ledger::categories::{self, NOT_PLANNABLE};
use fiscus_ledger::date::days_in_month;
use fiscus_ledger::{Category, Date, Haler, State};
use serde::Serialize;
/// How a planned category is doing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum Pace {
/// Below 90 % of what the plan allows by today (or, for a past month, within the plan).
Under,
OnPace,
/// Above 110 % of what the plan allows by today, not over the plan yet.
Ahead,
/// More than the whole month's plan.
Over,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct PlanRow {
pub category: Category,
pub planned: Option<Haler>,
pub spent: Haler,
/// Planned less spent; negative when over. `None` without a plan.
pub left: Option<Haler>,
/// Spent of the plan in thousandths, capped at 1000 (for a bar); 0 without a plan.
pub permille: u32,
/// `None` without a plan, and for a month that has not begun.
pub pace: Option<Pace>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct MonthPlan {
/// The 1st of the month.
pub month: Date,
/// The categories with a plan this month, in the app's order, then those spent on without a plan, the
/// largest first.
pub rows: Vec<PlanRow>,
/// All the plans of the month together.
pub planned: Haler,
/// Everything spent this month.
pub spent: Haler,
/// Of that, spent in categories without a plan.
pub unplanned: Haler,
}
fn pace(planned: Haler, spent: Haler, month: Date, today: Date) -> Option<Pace> {
if today < month {
return None;
}
if spent > planned {
return Some(Pace::Over);
}
if today > month.month_end() {
return Some(Pace::Under);
}
let (y, m, day) = today.ymd();
let allowed = i128::from(planned.0) * i128::from(day) / i128::from(days_in_month(y, m));
let spent = i128::from(spent.0) * 100;
Some(if spent > allowed * 110 {
Pace::Ahead
} else if spent < allowed * 90 {
Pace::Under
} else {
Pace::OnPace
})
}
/// The month of `month` against its plans. For this month, what is spent up to `today`; a later month has
/// nothing spent yet. `None` when a sum would not fit.
pub fn month_plan(state: &State, month: Date, today: Date) -> Option<MonthPlan> {
let start = month.month_start();
let end = start.month_end().min(today);
let spent_by = if end < start { Default::default() } else { outflows(&between(state, start, end))? };
let spent_in = |c: &str| spent_by.get(c).copied().unwrap_or(Haler::ZERO);
let mut rows = Vec::new();
for (category, _) in state.categories() {
let Some(planned) = state.plan_for(&category, start) else { continue };
let spent = spent_in(&category);
let permille = (i128::from(spent.0) * 1000 / i128::from(planned.0)).clamp(0, 1000) as u32;
rows.push(PlanRow { left: Some(planned.checked_sub(spent).ok()?), planned: Some(planned), permille, pace: pace(planned, spent, start, today), spent, category });
}
let mut extra: Vec<(&Category, &Haler)> = spent_by.iter().filter(|(c, _)| state.plan_for(c, start).is_none()).collect();
extra.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
let unplanned = Haler::sum(extra.iter().map(|(_, a)| **a)).ok()?;
rows.extend(extra.into_iter().map(|(c, a)| PlanRow { category: c.clone(), planned: None, spent: *a, left: None, permille: 0, pace: None }));
Some(MonthPlan {
month: start,
planned: Haler::sum(rows.iter().filter_map(|r| r.planned)).ok()?,
spent: Haler::sum(spent_by.values().copied()).ok()?,
unplanned,
rows,
})
}
/// A plan from your history: for each category you can plan, the average of what you spent on it over the last
/// three complete months, rounded **up** to whole hundreds of crowns. Only months since your first payment
/// count, so a ledger a month old is not divided by three. Categories you spent nothing on are left out.
pub fn suggest(state: &State, today: Date) -> Vec<(Category, Haler)> {
let this_month = today.month_start();
let Some(first) = state.effective_payments().first().map(|p| p.date.month_start()) else { return Vec::new() };
let months: Vec<Date> = (1..=3).map(|n| this_month.add_months(-n)).filter(|m| *m >= first).collect();
let Some(oldest) = months.last().copied() else { return Vec::new() };
let Some(spent) = outflows(&between(state, oldest, this_month.add_days(-1))) else { return Vec::new() };
let hundred = 10_000i128;
let mut out = Vec::new();
for (category, _) in state.categories() {
if NOT_PLANNABLE.contains(&category.as_str()) {
continue;
}
let Some(total) = spent.get(&category).filter(|t| t.0 > 0) else { continue };
// Both are positive: rounding up is (a + b - 1) / b.
let n = months.len() as i128;
let avg = (i128::from(total.0) + n - 1) / n;
let up = (avg + hundred - 1) / hundred * hundred;
match i64::try_from(up) {
Ok(v) if Haler(v) <= categories::MAX_PLAN => out.push((category, Haler(v))),
_ => out.push((category, categories::MAX_PLAN)),
}
}
out
}
+81
View File
@@ -0,0 +1,81 @@
//! One definition of spending, for every screen: money out of your own payments, as positive amounts, by
//! category. Money between your own accounts (`transfers`) is not spending; a payment nobody categorised counts
//! as `uncategorised`. Every sum is checked: `None` when one would not fit, never a wrong number.
use fiscus_ledger::categories::{TRANSFERS, UNCATEGORISED};
use fiscus_ledger::{Category, Date, EffectivePayment, Haler, State};
use std::collections::BTreeMap;
/// The payments dated in `[from, to]`, a confirmed pair as one.
pub fn between(state: &State, from: Date, to: Date) -> Vec<EffectivePayment> {
state.effective_payments().into_iter().filter(|p| p.date >= from && p.date <= to).collect()
}
/// The category a payment counts under.
pub fn category_of(p: &EffectivePayment) -> &str {
p.category.as_deref().unwrap_or(UNCATEGORISED)
}
/// A payment that is spending: money out, not a transfer.
pub fn is_spending(p: &EffectivePayment) -> bool {
p.amount.0 < 0 && category_of(p) != TRANSFERS
}
/// Money out by category, positive.
pub fn outflows(payments: &[EffectivePayment]) -> Option<BTreeMap<Category, Haler>> {
let mut by: BTreeMap<Category, Haler> = BTreeMap::new();
for p in payments.iter().filter(|p| is_spending(p)) {
let slot = by.entry(category_of(p).to_string()).or_insert(Haler::ZERO);
*slot = slot.checked_add(p.amount.checked_neg().ok()?).ok()?;
}
Some(by)
}
/// Money in, not a transfer.
pub fn inflow(payments: &[EffectivePayment]) -> Option<Haler> {
Haler::sum(payments.iter().filter(|p| p.amount.0 > 0 && category_of(p) != TRANSFERS).map(|p| p.amount)).ok()
}
/// Each part's share of their sum in thousandths, by the largest remainder: the shares add up to exactly 1000
/// whenever the sum is above zero (all zeros otherwise). A tie goes to the earlier part, so callers order the
/// parts first. A negative part counts as zero.
pub fn permille(parts: &[Haler]) -> Vec<u32> {
let parts: Vec<i128> = parts.iter().map(|h| i128::from(h.0.max(0))).collect();
let total: i128 = parts.iter().sum();
if total <= 0 {
return vec![0; parts.len()];
}
let mut shares: Vec<u32> = parts.iter().map(|p| (p * 1000 / total) as u32).collect();
let mut left = 1000 - shares.iter().sum::<u32>();
let mut order: Vec<usize> = (0..parts.len()).collect();
// Largest remainder first; the earlier part on a tie (the sort is stable).
order.sort_by_key(|&i| std::cmp::Reverse(parts[i] * 1000 % total));
for i in order {
if left == 0 {
break;
}
shares[i] += 1;
left -= 1;
}
shares
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shares_always_add_up_to_a_thousand() {
let h = |v: &[i64]| v.iter().map(|&x| Haler(x)).collect::<Vec<_>>();
assert_eq!(permille(&h(&[1, 1, 1])), [334, 333, 333]);
assert_eq!(permille(&h(&[2, 1])), [667, 333]);
assert_eq!(permille(&h(&[0, 0])), [0, 0]);
assert_eq!(permille(&h(&[])), Vec::<u32>::new());
assert_eq!(permille(&h(&[i64::MAX, i64::MAX, 1])), [500, 500, 0]);
assert_eq!(permille(&h(&[5, -3])), [1000, 0]);
for n in 1..40i64 {
let parts: Vec<Haler> = (1..=n).map(|i| Haler(i * 7919 % 1013 + 1)).collect();
assert_eq!(permille(&parts).iter().sum::<u32>(), 1000, "{n} parts");
}
}
}
+143
View File
@@ -0,0 +1,143 @@
//! A month in numbers: where the money went (the slices of a pie, in thousandths that add up to 1000), money
//! in and out, the last six months, how far along you are compared with last month by the same day, the
//! merchants you paid most, and what the subscriptions took. Your own payments; transfers are not spending.
use crate::spending::{between, inflow, is_spending, outflows, permille};
use crate::subscriptions::Insight;
use fiscus_ledger::{Category, Date, Haler, State};
use serde::Serialize;
use std::collections::BTreeMap;
/// The pie shows this many categories; the rest are one slice.
pub const SLICES: usize = 7;
/// Months in the bars, this one included.
pub const MONTHS: i32 = 6;
pub const TOP_MERCHANTS: usize = 5;
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Slice {
/// `None`: every other category, together.
pub category: Option<Category>,
pub amount: Haler,
/// Its share of the month's spending; the slices add up to 1000.
pub permille: u32,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct MonthTotal {
/// The 1st of the month.
pub month: Date,
pub out: Haler,
pub inflow: Haler,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct MerchantTotal {
pub key: String,
/// As the latest payment to it wrote it.
pub merchant: String,
pub amount: Haler,
pub count: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct MonthStats {
/// The 1st of the month.
pub month: Date,
/// Largest first; at most [`SLICES`], then the rest.
pub slices: Vec<Slice>,
pub out: Haler,
pub inflow: Haler,
/// In less out; negative when more went out.
pub net: Haler,
/// The last [`MONTHS`] months, oldest first, ending with this one.
pub months: Vec<MonthTotal>,
/// Spent last month up to the same day of the month (all of last month for a past month).
pub same_day_last_month: Haler,
/// Largest first.
pub top_merchants: Vec<MerchantTotal>,
/// What the subscriptions charged this month.
pub subscriptions: Haler,
/// Their share of the month's spending, in thousandths (at most 1000).
pub subscriptions_permille: u32,
}
/// `[start, end]` of `month`, cut at `today`; `None` for a month that has not begun.
fn span(month: Date, today: Date) -> Option<(Date, Date)> {
let start = month.month_start();
(start <= today).then(|| (start, start.month_end().min(today)))
}
fn spent(state: &State, from: Date, to: Date) -> Option<Haler> {
Haler::sum(outflows(&between(state, from, to))?.into_values()).ok()
}
/// The month of `month`, up to `today`. `insight` is `analyse(state, today)`. `None` for a month that has not
/// begun, or when a sum would not fit.
pub fn month_stats(state: &State, insight: &Insight, month: Date, today: Date) -> Option<MonthStats> {
let (start, end) = span(month, today)?;
let payments = between(state, start, end);
let by = outflows(&payments)?;
let out = Haler::sum(by.values().copied()).ok()?;
let inflow = inflow(&payments)?;
let mut parts: Vec<(Category, Haler)> = by.into_iter().collect();
parts.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
let mut slices: Vec<(Option<Category>, Haler)> = parts.iter().take(SLICES).map(|(c, a)| (Some(c.clone()), *a)).collect();
if parts.len() > SLICES {
slices.push((None, Haler::sum(parts[SLICES..].iter().map(|(_, a)| *a)).ok()?));
}
let shares = permille(&slices.iter().map(|(_, a)| *a).collect::<Vec<_>>());
let mut months = Vec::new();
for n in (0..MONTHS).rev() {
let m = start.add_months(-n);
let (from, to) = span(m, today)?;
let ps = between(state, from, to);
months.push(MonthTotal { month: m, out: Haler::sum(outflows(&ps)?.into_values()).ok()?, inflow: crate::spending::inflow(&ps)? });
}
let last = start.add_months(-1);
let last_end = if end == start.month_end() { last.month_end() } else { last.add_days(end.ymd().2 as i32 - 1).min(last.month_end()) };
let same_day_last_month = spent(state, last, last_end)?;
let mut merchants: BTreeMap<&str, MerchantTotal> = BTreeMap::new();
for p in payments.iter().filter(|p| is_spending(p) && !p.merchant_key.is_empty()) {
let t = merchants.entry(&p.merchant_key).or_insert(MerchantTotal { key: p.merchant_key.clone(), merchant: String::new(), amount: Haler::ZERO, count: 0 });
t.merchant = p.merchant.clone();
t.amount = t.amount.checked_add(p.amount.checked_neg().ok()?).ok()?;
t.count += 1;
}
let mut top_merchants: Vec<MerchantTotal> = merchants.into_values().collect();
top_merchants.sort_by(|a, b| b.amount.cmp(&a.amount).then(a.key.cmp(&b.key)));
top_merchants.truncate(TOP_MERCHANTS);
// A subscription charge counts once, by the payment it was, and only when it is spending this month.
let spending_ids: BTreeMap<&str, Haler> = payments
.iter()
.filter(|p| is_spending(p))
.flat_map(|p| [Some(p.id.as_str()), p.line.as_deref(), p.captured.as_deref()].into_iter().flatten().map(move |id| (id, p.amount)))
.collect();
let mut charged = std::collections::BTreeSet::new();
let mut subscriptions = Haler::ZERO;
for c in insight.subscriptions.iter().flat_map(|s| &s.charges) {
let Some(paid) = spending_ids.get(c.payment.as_str()) else { continue };
if charged.insert(c.payment.as_str()) {
subscriptions = subscriptions.checked_add(paid.checked_neg().ok()?).ok()?;
}
}
let subscriptions_permille = if out.0 > 0 { (i128::from(subscriptions.0) * 1000 / i128::from(out.0)).clamp(0, 1000) as u32 } else { 0 };
Some(MonthStats {
month: start,
slices: slices.into_iter().zip(shares).map(|((category, amount), permille)| Slice { category, amount, permille }).collect(),
net: inflow.checked_sub(out).ok()?,
out,
inflow,
months,
same_day_last_month,
top_merchants,
subscriptions,
subscriptions_permille,
})
}
+245
View File
@@ -0,0 +1,245 @@
//! Subscriptions from the ledger: recurring charges at one merchant, their price changes, trials, the next
//! charge, and what the monthly keep-or-cancel review should ask.
use fiscus_ledger::state::DecisionRecord;
use fiscus_ledger::{Date, Decision, EffectivePayment, Haler, PaymentId, State};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// A charge of at most this much is a card check, not a payment for the service.
pub const TRIAL_MAX: Haler = Haler(1_000);
/// An automatically detected trial is assumed to end this many days after its card check.
pub const TRIAL_DAYS: i32 = 30;
/// A subscription that has not charged this many days after its due date has lapsed.
pub const GRACE_DAYS: i32 = 10;
/// Recurring payments in these categories (rent, energy, savings) are not subscriptions to review.
pub const NOT_SUBSCRIPTIONS: &[&str] = &["housing", "utilities", "transfers", "income"];
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Cadence {
Monthly,
Yearly,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Status {
Active,
/// Due more than [`GRACE_DAYS`] ago and no charge since.
Lapsed,
/// The last decision was "cancel" and it has not charged since.
Cancelled,
/// Cancelled, and charged anyway.
ChargedAfterCancel,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Charge {
pub payment: PaymentId,
pub date: Date,
/// What it cost (positive).
pub cost: Haler,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PriceChange {
pub from: Haler,
pub to: Haler,
pub on: Date,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Subscription {
/// Stable key for decisions: the merchant key, plus `#<first cost in CZK>` when one merchant bills
/// several subscriptions (iCloud and Apple Music both come from `APPLE.COM/BILL`).
pub key: String,
pub merchant: String,
pub merchant_key: String,
pub cadence: Cadence,
pub charges: Vec<Charge>,
/// The last charge.
pub cost: Haler,
/// The most recent change of price.
pub price_change: Option<PriceChange>,
/// The price changed and nobody has decided at the new price yet.
pub creep_alert: bool,
pub next_charge: Date,
pub status: Status,
pub decision: Option<DecisionRecord>,
/// Active and not decided this month (a yearly one: only in the 30 days before it charges).
pub needs_review: bool,
pub category: Option<String>,
pub budget: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Trial {
pub key: String,
pub merchant: String,
pub payment: PaymentId,
pub started: Date,
pub ends: Date,
/// `true` when the end is the 30-day guess, `false` when marked by hand.
pub estimated: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum UpcomingKind {
Charge,
TrialEnds,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Upcoming {
pub key: String,
pub merchant: String,
pub date: Date,
pub kind: UpcomingKind,
pub cost: Option<Haler>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Insight {
pub subscriptions: Vec<Subscription>,
pub trials: Vec<Trial>,
/// Charges and trial ends in `[today, today + 7]`, by date.
pub upcoming: Vec<Upcoming>,
}
/// `|a - b| ≤ 50 % of b`: a price rise stays with its subscription (Netflix went up 30 % at once).
fn near(a: Haler, b: Haler) -> bool {
(a.0 - b.0).unsigned_abs() * 2 <= b.0.unsigned_abs()
}
fn cadence_of(charges: &[&EffectivePayment]) -> Option<Cadence> {
if charges.len() < 2 {
return None;
}
let gaps: Vec<i32> = charges.windows(2).map(|w| w[0].date.days_until(w[1].date)).collect();
// Mostly one price: at most one change in every two steps (a shop's varying totals never pass).
let changes = charges.windows(2).filter(|w| w[0].amount != w[1].amount).count();
if changes * 2 > gaps.len() || (gaps.len() == 1 && changes == 1) {
return None;
}
if gaps.iter().all(|g| (26..=35).contains(g)) {
Some(Cadence::Monthly)
} else if gaps.iter().all(|g| (358..=373).contains(g)) {
Some(Cadence::Yearly)
} else {
None
}
}
pub fn analyse(state: &State, today: Date) -> Insight {
let payments = state.effective_payments();
let mut by_merchant: BTreeMap<&str, Vec<&EffectivePayment>> = BTreeMap::new();
for p in &payments {
let excluded = p.category.as_deref().is_some_and(|c| NOT_SUBSCRIPTIONS.contains(&c));
if p.amount.0 <= 0 && !p.merchant_key.is_empty() && !excluded {
by_merchant.entry(&p.merchant_key).or_default().push(p);
}
}
let mut insight = Insight::default();
for (key, charges) in &by_merchant {
let cost = |p: &EffectivePayment| Haler(-p.amount.0);
let full: Vec<&EffectivePayment> = charges.iter().copied().filter(|p| cost(p) > TRIAL_MAX).collect();
// Trials: the last card check with no full charge after it, or a payment marked by hand.
let last_check = charges.iter().filter(|p| cost(p) <= TRIAL_MAX).next_back();
for p in charges.iter().filter(|p| p.trial_ends.is_some() || Some(*p) == last_check) {
let converted = full.iter().any(|f| f.date > p.date && f.id != p.id);
let (ends, estimated) = match p.trial_ends {
Some(e) => (e, false),
None => (p.date.add_days(TRIAL_DAYS), true),
};
if !converted && ends >= today.add_days(-7) {
insight.trials.push(Trial { key: (*key).into(), merchant: p.merchant.clone(), payment: p.id.clone(), started: p.date, ends, estimated });
}
}
// Clusters of similar amounts, in date order: a price change stays in its cluster.
let mut clusters: Vec<Vec<&EffectivePayment>> = Vec::new();
for p in &full {
let last_cost = |c: &Vec<&EffectivePayment>| cost(c.last().expect("clusters are never empty"));
let best = clusters
.iter_mut()
.filter(|c| near(cost(p), last_cost(c)))
.min_by_key(|c| (cost(p).0 - last_cost(c).0).unsigned_abs());
match best {
Some(c) => c.push(p),
None => clusters.push(vec![p]),
}
}
let found: Vec<(Cadence, &Vec<&EffectivePayment>)> =
clusters.iter().filter_map(|c| cadence_of(c).map(|cad| (cad, c))).collect();
let several = found.len() > 1;
for (cadence, c) in found {
let first = c[0];
let last = c[c.len() - 1];
let sub_key = if several { format!("{key}#{}", cost(first).0 / 100) } else { (*key).to_string() };
let price_change = c
.windows(2)
.rev()
.find(|w| w[0].amount != w[1].amount)
.map(|w| PriceChange { from: cost(w[0]), to: cost(w[1]), on: w[1].date });
let decision = state.decisions.get(&sub_key).and_then(|d| d.last()).cloned();
let next_charge = match cadence {
Cadence::Monthly => last.date.add_months(1),
Cadence::Yearly => last.date.add_years(1),
};
let status = match &decision {
Some(d) if d.decision == Decision::Cancel => {
if c.iter().any(|p| p.date > d.on) {
Status::ChargedAfterCancel
} else {
Status::Cancelled
}
}
_ if today > next_charge.add_days(GRACE_DAYS) => Status::Lapsed,
_ => Status::Active,
};
let decided_at_cost = decision.as_ref().is_some_and(|d| d.amount == cost(last));
let decided_this_month = decision.as_ref().is_some_and(|d| d.on.month() == today.month());
let review_window = match cadence {
Cadence::Monthly => true,
Cadence::Yearly => today.days_until(next_charge) <= 30,
};
insight.subscriptions.push(Subscription {
key: sub_key,
merchant: last.merchant.clone(),
merchant_key: (*key).into(),
cadence,
charges: c.iter().map(|p| Charge { payment: p.id.clone(), date: p.date, cost: cost(p) }).collect(),
cost: cost(last),
creep_alert: price_change.is_some() && !decided_at_cost && status != Status::Cancelled,
price_change,
next_charge,
needs_review: status == Status::Active && !decided_this_month && review_window,
status,
decision,
category: last.category.clone(),
budget: last.budget.clone(),
});
}
}
let horizon = today.add_days(7);
for s in insight.subscriptions.iter().filter(|s| s.status == Status::Active) {
if (today..=horizon).contains(&s.next_charge) {
insight.upcoming.push(Upcoming { key: s.key.clone(), merchant: s.merchant.clone(), date: s.next_charge, kind: UpcomingKind::Charge, cost: Some(s.cost) });
}
}
for t in &insight.trials {
if (today..=horizon).contains(&t.ends) {
insight.upcoming.push(Upcoming { key: t.key.clone(), merchant: t.merchant.clone(), date: t.ends, kind: UpcomingKind::TrialEnds, cost: None });
}
}
insight.upcoming.sort_by(|a, b| a.date.cmp(&b.date).then(a.key.cmp(&b.key)));
insight.subscriptions.sort_by(|a, b| a.next_charge.cmp(&b.next_charge).then(a.key.cmp(&b.key)));
insight.trials.sort_by(|a, b| a.ends.cmp(&b.ends).then(a.key.cmp(&b.key)));
insight
}
+57
View File
@@ -0,0 +1,57 @@
//! Mandatory test 6: the forecast is a pure function of its inputs and seed.
use fiscus_insight::forecast::{forecast, ForecastInput};
use fiscus_ledger::Haler;
fn input() -> ForecastInput {
ForecastInput {
history: (0..90).map(|i| Haler(((i * 7919) % 120_000) as i64)).collect(),
spent: Haler(800_000),
days_left: 17,
limit: Haler(2_000_000),
known: Haler(19_900),
}
}
#[test]
fn same_seed_same_output() {
let a = forecast(&input(), 42, 5_000);
let b = forecast(&input(), 42, 5_000);
assert_eq!(a, b);
assert_eq!(format!("{a:?}"), format!("{b:?}"));
// Another seed is another sample (the chance moves a little, the shape not much).
let c = forecast(&input(), 43, 5_000);
assert_ne!((a.p10, a.p50, a.p90), (c.p10, c.p50, c.p90));
assert!(a.chance_bp.abs_diff(c.chance_bp) < 500);
}
#[test]
fn the_obvious_cases() {
// Every day costs exactly 100 CZK: ten days left from zero lands on 1 000 CZK in every run.
let flat = ForecastInput { history: vec![Haler(10_000); 30], spent: Haler(0), days_left: 10, limit: Haler(100_000), known: Haler(0) };
let f = forecast(&flat, 1, 1_000);
assert_eq!((f.chance_bp, f.p10, f.p50, f.p90), (10_000, Haler(100_000), Haler(100_000), Haler(100_000)));
let f = forecast(&ForecastInput { limit: Haler(99_999), ..flat.clone() }, 1, 1_000);
assert_eq!(f.chance_bp, 0);
// Already over the limit.
let over = ForecastInput { spent: Haler(200_000), ..flat.clone() };
assert_eq!(forecast(&over, 1, 1_000).chance_bp, 0);
// No history yet: what is spent plus what is known to come.
let fresh = ForecastInput { history: vec![], spent: Haler(50_000), days_left: 10, limit: Haler(60_000), known: Haler(5_000) };
let f = forecast(&fresh, 1, 100);
assert_eq!((f.chance_bp, f.p50, f.history_days), (10_000, Haler(55_000), 0));
// The last day of the month: nothing left to draw.
let last = ForecastInput { days_left: 0, ..flat };
assert_eq!(forecast(&last, 9, 10).p90, Haler(0));
}
#[test]
fn the_chance_tracks_the_limit() {
let mut prev = 0;
for limit in (1_000_000..4_000_000).step_by(250_000) {
let f = forecast(&ForecastInput { limit: Haler(limit), ..input() }, 7, 4_000);
assert!(f.chance_bp >= prev, "a higher limit is never less likely to hold");
prev = f.chance_bp;
}
assert_eq!(prev, 10_000);
}
@@ -0,0 +1,103 @@
# A synthetic household year (not any bank's format): date;amount in haléře;merchant;category
# Known: Spotify monthly (169 -> 199 in July, decided keep), Netflix monthly (199 -> 259 in October),
# iCloud and Apple Music under one merchant, YouTube after a converted 1 CZK check, WEDOS yearly,
# a Disney+ trial (1 CZK on 28 Oct), rent (housing, never a subscription), Albert weekly (never).
2025-03-10;-39900;WEDOS INTERNET A.S.;
2026-01-05;-16900;PAYPAL *SPOTIFY;
2026-01-12;-19900;NETFLIX.COM;
2026-01-08;-2500;APPLE.COM/BILL;
2026-01-20;-16900;APPLE.COM/BILL;
2026-01-01;-1500000;PRONAJEM BYTU;housing
2026-02-05;-16900;PAYPAL *SPOTIFY;
2026-02-12;-19900;NETFLIX.COM;
2026-02-08;-2500;APPLE.COM/BILL;
2026-02-20;-16900;APPLE.COM/BILL;
2026-02-01;-1500000;PRONAJEM BYTU;housing
2026-03-05;-16900;PAYPAL *SPOTIFY;
2026-03-12;-19900;NETFLIX.COM;
2026-03-08;-2500;APPLE.COM/BILL;
2026-03-20;-16900;APPLE.COM/BILL;
2026-03-01;-1500000;PRONAJEM BYTU;housing
2026-04-05;-16900;PAYPAL *SPOTIFY;
2026-04-12;-19900;NETFLIX.COM;
2026-04-08;-2500;APPLE.COM/BILL;
2026-04-20;-16900;APPLE.COM/BILL;
2026-04-01;-1500000;PRONAJEM BYTU;housing
2026-05-05;-16900;PAYPAL *SPOTIFY;
2026-05-12;-19900;NETFLIX.COM;
2026-05-08;-2500;APPLE.COM/BILL;
2026-05-20;-16900;APPLE.COM/BILL;
2026-05-01;-1500000;PRONAJEM BYTU;housing
2026-06-05;-16900;PAYPAL *SPOTIFY;
2026-06-12;-19900;NETFLIX.COM;
2026-06-08;-2500;APPLE.COM/BILL;
2026-06-20;-16900;APPLE.COM/BILL;
2026-06-01;-1500000;PRONAJEM BYTU;housing
2026-07-05;-19900;PAYPAL *SPOTIFY;
2026-07-12;-19900;NETFLIX.COM;
2026-07-08;-2500;APPLE.COM/BILL;
2026-07-20;-16900;APPLE.COM/BILL;
2026-07-01;-1500000;PRONAJEM BYTU;housing
2026-08-05;-19900;PAYPAL *SPOTIFY;
2026-08-12;-19900;NETFLIX.COM;
2026-08-08;-2500;APPLE.COM/BILL;
2026-08-20;-16900;APPLE.COM/BILL;
2026-08-01;-1500000;PRONAJEM BYTU;housing
2026-09-05;-19900;PAYPAL *SPOTIFY;
2026-09-12;-19900;NETFLIX.COM;
2026-09-08;-2500;APPLE.COM/BILL;
2026-09-20;-16900;APPLE.COM/BILL;
2026-09-01;-1500000;PRONAJEM BYTU;housing
2026-10-05;-19900;PAYPAL *SPOTIFY;
2026-10-12;-25900;NETFLIX.COM;
2026-10-08;-2500;APPLE.COM/BILL;
2026-10-20;-16900;APPLE.COM/BILL;
2026-10-01;-1500000;PRONAJEM BYTU;housing
2026-03-10;-39900;WEDOS INTERNET A.S.;
2026-08-01;-100;GOOGLE *YouTube Premium;
2026-09-01;-23900;GOOGLE *YouTube Premium;
2026-10-01;-23900;GOOGLE *YouTube Premium;
2026-10-28;-100;DISNEY PLUS;
2026-01-03;-31700;ALBERT 0412 PRAHA;groceries
2026-01-10;-135245;ALBERT 0412 PRAHA;groceries
2026-01-17;-126410;ALBERT 0412 PRAHA;groceries
2026-01-24;-39515;ALBERT 0412 PRAHA;groceries
2026-01-31;-64400;ALBERT 0412 PRAHA;groceries
2026-02-07;-145145;ALBERT 0412 PRAHA;groceries
2026-02-14;-132710;ALBERT 0412 PRAHA;groceries
2026-02-21;-32615;ALBERT 0412 PRAHA;groceries
2026-02-28;-49100;ALBERT 0412 PRAHA;groceries
2026-03-07;-59045;ALBERT 0412 PRAHA;groceries
2026-03-14;-67010;ALBERT 0412 PRAHA;groceries
2026-03-21;-121715;ALBERT 0412 PRAHA;groceries
2026-03-28;-105800;ALBERT 0412 PRAHA;groceries
2026-04-04;-116945;ALBERT 0412 PRAHA;groceries
2026-04-11;-49310;ALBERT 0412 PRAHA;groceries
2026-04-18;-66815;ALBERT 0412 PRAHA;groceries
2026-04-25;-114500;ALBERT 0412 PRAHA;groceries
2026-05-02;-78845;ALBERT 0412 PRAHA;groceries
2026-05-09;-79610;ALBERT 0412 PRAHA;groceries
2026-05-16;-107915;ALBERT 0412 PRAHA;groceries
2026-05-23;-75200;ALBERT 0412 PRAHA;groceries
2026-05-30;-64745;ALBERT 0412 PRAHA;groceries
2026-06-06;-37910;ALBERT 0412 PRAHA;groceries
2026-06-13;-125015;ALBERT 0412 PRAHA;groceries
2026-06-20;-107900;ALBERT 0412 PRAHA;groceries
2026-06-27;-74645;ALBERT 0412 PRAHA;groceries
2026-07-04;-44210;ALBERT 0412 PRAHA;groceries
2026-07-11;-118115;ALBERT 0412 PRAHA;groceries
2026-07-18;-92600;ALBERT 0412 PRAHA;groceries
2026-07-25;-108545;ALBERT 0412 PRAHA;groceries
2026-08-01;-98510;ALBERT 0412 PRAHA;groceries
2026-08-08;-87215;ALBERT 0412 PRAHA;groceries
2026-08-15;-149300;ALBERT 0412 PRAHA;groceries
2026-08-22;-46445;ALBERT 0412 PRAHA;groceries
2026-08-29;-80810;ALBERT 0412 PRAHA;groceries
2026-09-05;-32315;ALBERT 0412 PRAHA;groceries
2026-09-12;-38000;ALBERT 0412 PRAHA;groceries
2026-09-19;-128345;ALBERT 0412 PRAHA;groceries
2026-09-26;-111110;ALBERT 0412 PRAHA;groceries
2026-10-03;-73415;ALBERT 0412 PRAHA;groceries
2026-10-10;-118700;ALBERT 0412 PRAHA;groceries
2026-10-17;-114245;ALBERT 0412 PRAHA;groceries
2026-10-24;-69410;ALBERT 0412 PRAHA;groceries
+69
View File
@@ -0,0 +1,69 @@
//! Day 2: household duplicates ("you both pay Spotify"), only from names members chose to share.
use fiscus_insight::household::{household_duplicates, Duplicate};
fn names(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn two_members_paying_the_same_service_is_a_duplicate() {
let shared = vec![
("mark".to_string(), names(&["PAYPAL *SPOTIFY", "Netflix.com", "O2 Czech"])),
("jana".to_string(), names(&["Spotify AB", "Netflix"])),
("kid".to_string(), names(&["Spotify"])),
];
let d = household_duplicates(&shared);
assert_eq!(
d,
vec![
Duplicate { key: "netflix".into(), members: vec!["jana".into(), "mark".into()] },
Duplicate { key: "spotify".into(), members: vec!["jana".into(), "kid".into(), "mark".into()] },
]
);
}
#[test]
fn what_is_shared_is_the_service_key_of_each_subscription_still_paid() {
use fiscus_insight::household::shared_names;
use fiscus_ledger::{Date, Decision, Event, EventBody, Haler, State, Timestamp};
let d = |s: &str| s.parse::<Date>().unwrap();
let mut log = Vec::new();
for (i, m) in [1u32, 2, 3, 4].iter().enumerate() {
for (j, merchant) in ["PAYPAL *SPOTIFY 4029357733", "NETFLIX.COM", "WEDOS INTERNET A.S.", "TV"].iter().enumerate() {
log.push(Event::new(
format!("p{i}{j}"),
Timestamp(0),
EventBody::PaymentAdded {
payment: format!("p{i}{j}"),
amount: Haler(-19_900),
date: d(&format!("2026-{:02}-0{}", m + 6, j + 1)),
merchant: merchant.to_string(),
category: None,
note: None,
},
));
}
}
let today = d("2026-10-20");
let state = State::replay(&log);
// Only the first word of the merchant key, so a reference number never leaves; "TV" is too short to say anything.
assert_eq!(shared_names(&state, today), names(&["netflix", "spotify", "wedos"]));
log.push(Event::new(
"cancel",
Timestamp(0),
EventBody::SubscriptionDecided { subscription: "netflix com".into(), decision: Decision::Cancel, amount: Haler(19_900), on: d("2026-10-05") },
));
let state = State::replay(&log);
let key = fiscus_insight::subscriptions::analyse(&state, today).subscriptions.iter().find(|s| s.merchant.starts_with("NETFLIX")).map(|s| s.key.clone());
assert_eq!(key.as_deref(), Some("netflix com"), "the decision above names Netflix's subscription key");
assert_eq!(shared_names(&state, today), names(&["spotify", "wedos"]), "a cancelled one is not paid any more");
}
#[test]
fn one_member_alone_or_nobody_sharing_is_nothing() {
assert!(household_duplicates(&[]).is_empty());
let one = vec![("mark".to_string(), names(&["Spotify", "spotify", "PAYPAL *SPOTIFY"]))];
assert!(household_duplicates(&one).is_empty(), "the same member twice is not a duplicate");
}
+188
View File
@@ -0,0 +1,188 @@
//! Spending, the month against its plan, and a month in numbers: one definition of spending everywhere,
//! shares that always add up to 1000, the pace by today, and the suggested plan rounded up.
use fiscus_insight::plan::{month_plan, suggest, Pace};
use fiscus_insight::stats::{month_stats, SLICES};
use fiscus_insight::subscriptions::analyse;
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
/// A ledger from `(date, amount in haléře, merchant, category)` added by hand, then `extra` events.
fn ledger(payments: &[(&str, i64, &str, &str)], extra: Vec<EventBody>) -> State {
let mut log: Vec<Event> = payments
.iter()
.enumerate()
.map(|(i, (date, amount, merchant, category))| {
Event::new(
format!("e{i}"),
Timestamp(0),
EventBody::PaymentAdded {
payment: format!("p{i}"),
amount: Haler(*amount),
date: d(date),
merchant: merchant.to_string(),
category: (!category.is_empty()).then(|| category.to_string()),
note: None,
},
)
})
.collect();
log.extend(extra.into_iter().enumerate().map(|(i, b)| Event::new(format!("x{i}"), Timestamp(0), b)));
let s = State::replay(&log);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
s
}
fn planned(category: &str, amount: i64, from: &str) -> EventBody {
EventBody::CategoryPlanned { category: category.into(), amount: Haler(amount), from: d(from) }
}
#[test]
fn the_month_against_its_plan() {
let today = d("2026-11-15");
let s = ledger(
&[
("2026-11-02", -300_000, "Albert", "groceries"),
("2026-11-10", -150_000, "Lidl", "groceries"),
("2026-11-12", -250_000, "Lokál", "eating-out"),
("2026-11-14", -40_000, "Trafika", ""),
("2026-11-03", -1_000_000, "To savings", "transfers"),
("2026-11-05", 5_000_000, "Salary", "income"),
("2026-11-20", -90_000, "Albert", "groceries"),
("2026-10-30", -999_999, "Albert", "groceries"),
("2026-11-08", -60_000, "Shell", "transport"),
],
vec![planned("groceries", 1_000_000, "2026-10-01"), planned("eating-out", 200_000, "2026-11-01"), planned("transport", 400_000, "2026-11-01")],
);
let p = month_plan(&s, today, today).unwrap();
assert_eq!(p.month, d("2026-11-01"));
type Row<'a> = (&'a str, Option<i64>, i64, Option<i64>, u32, Option<Pace>);
let rows: Vec<Row> =
p.rows.iter().map(|r| (r.category.as_str(), r.planned.map(|x| x.0), r.spent.0, r.left.map(|x| x.0), r.permille, r.pace)).collect();
assert_eq!(
rows,
[
// Half the month gone (15 of 30 days): 4 500 of 10 000 is 90 % of the pace, on pace.
("groceries", Some(1_000_000), 450_000, Some(550_000), 450, Some(Pace::OnPace)),
("eating-out", Some(200_000), 250_000, Some(-50_000), 1000, Some(Pace::Over)),
("transport", Some(400_000), 60_000, Some(340_000), 150, Some(Pace::Under)),
// Spent with no plan: uncategorised. Transfers, income, the future and last month do not count.
("uncategorised", None, 40_000, None, 0, None),
]
);
assert_eq!((p.planned, p.spent, p.unplanned), (Haler(1_600_000), Haler(800_000), Haler(40_000)));
// A past month is done: within the plan is Under, past it Over. A month to come has nothing spent.
let oct = month_plan(&s, d("2026-10-01"), today).unwrap();
assert_eq!(oct.rows[0].pace, Some(Pace::Under));
assert_eq!(oct.rows[0].spent, Haler(999_999));
let dec = month_plan(&s, d("2026-12-01"), today).unwrap();
assert_eq!(dec.spent, Haler::ZERO);
assert!(dec.rows.iter().all(|r| r.pace.is_none()), "not begun");
}
#[test]
fn ahead_of_the_pace() {
let s = ledger(&[("2026-11-03", -500_000, "Albert", "groceries")], vec![planned("groceries", 1_000_000, "2026-11-01")]);
// 5 days of 30 allow 1 666,66; 5 000 is far ahead, but not over the month's 10 000.
assert_eq!(month_plan(&s, d("2026-11-05"), d("2026-11-05")).unwrap().rows[0].pace, Some(Pace::Ahead));
assert_eq!(month_plan(&s, d("2026-11-30"), d("2026-11-30")).unwrap().rows[0].pace, Some(Pace::Under));
}
#[test]
fn the_suggested_plan_is_the_average_rounded_up_to_hundreds() {
let s = ledger(
&[
("2026-08-10", -100_000, "Albert", "groceries"),
("2026-09-10", -200_000, "Albert", "groceries"),
("2026-10-10", -300_001, "Albert", "groceries"),
("2026-10-11", -12_345, "Lokál", "eating-out"),
("2026-10-12", -50_000, "To savings", "transfers"),
("2026-10-13", -7_000, "?", ""),
("2026-11-01", -999_999, "Albert", "groceries"),
("2026-07-01", -5_000_000, "Albert", "groceries"),
],
vec![],
);
// Aug, Sep, Oct (not this November, not July): 6 000,01 / 3 = 2 000,0034 → 2 100.
let got = suggest(&s, d("2026-11-15"));
assert_eq!(got, [("groceries".to_string(), Haler(210_000)), ("eating-out".to_string(), Haler(10_000))]);
// A ledger only a month old is not divided by three.
let young = ledger(&[("2026-10-10", -150_000, "Albert", "groceries")], vec![]);
assert_eq!(suggest(&young, d("2026-11-15")), [("groceries".to_string(), Haler(150_000))]);
assert!(suggest(&State::default(), d("2026-11-15")).is_empty());
}
#[test]
fn a_month_in_numbers() {
let today = d("2026-11-15");
let mut payments = vec![
("2026-11-02", -300_000, "Albert Praha", "groceries"),
("2026-11-09", -100_000, "ALBERT PRAHA", "groceries"),
("2026-11-03", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
("2026-11-04", -50_000, "Lokál", "eating-out"),
("2026-11-05", 4_000_000, "Salary", "income"),
("2026-11-06", -1_000_000, "To savings", "transfers"),
("2026-11-07", -33_100, "", "fun"),
("2026-10-02", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
("2026-09-02", -16_900, "PAYPAL *SPOTIFY", "subscriptions"),
("2026-10-10", -200_000, "Albert Praha", "groceries"),
("2026-10-20", -500_000, "Albert Praha", "groceries"),
("2026-11-20", -77_700, "Albert Praha", "groceries"),
];
// Eight more categories, so the pie has a slice for the rest.
let more = ["transport", "housing", "utilities", "shopping", "health", "kids", "travel", "gifts"];
for (i, c) in more.iter().enumerate() {
payments.push(("2026-11-10", -(1_000 + i as i64), "Shop", c));
}
let s = ledger(&payments, vec![]);
let st = month_stats(&s, &analyse(&s, today), today, today).unwrap();
assert_eq!(st.month, d("2026-11-01"));
let spent = 300_000 + 100_000 + 16_900 + 50_000 + 33_100 + (1_000..1_008).sum::<i64>();
assert_eq!((st.out, st.inflow, st.net), (Haler(spent), Haler(4_000_000), Haler(4_000_000 - spent)));
assert_eq!(st.slices.len(), SLICES + 1);
assert_eq!(st.slices.iter().map(|s| s.permille).sum::<u32>(), 1000, "the slices add up");
assert_eq!(st.slices[0].category.as_deref(), Some("groceries"));
assert_eq!(st.slices[0].amount, Haler(400_000));
assert!(st.slices.last().unwrap().category.is_none(), "the rest");
assert!(st.slices.windows(2).take(SLICES - 1).all(|w| w[0].amount >= w[1].amount), "largest first");
// Six months, oldest first; October in full, November up to today.
let months: Vec<(Date, i64)> = st.months.iter().map(|m| (m.month, m.out.0)).collect();
assert_eq!(months.len(), 6);
assert_eq!(months[0].0, d("2026-06-01"));
assert_eq!(months[4], (d("2026-10-01"), 716_900));
assert_eq!(months[5], (d("2026-11-01"), spent));
// By 15 October: the Spotify charge and the first Albert.
assert_eq!(st.same_day_last_month, Haler(216_900));
let top: Vec<(&str, i64, usize)> = st.top_merchants.iter().map(|m| (m.key.as_str(), m.amount.0, m.count)).collect();
assert_eq!(top[0], ("albert praha", 400_000, 2), "one merchant however the bank writes it");
assert!(top.iter().all(|(k, _, _)| !k.is_empty()), "a payment without a merchant is not a merchant");
assert!(top.len() <= 5);
assert_eq!(st.subscriptions, Haler(16_900));
assert_eq!(st.subscriptions_permille, (16_900 * 1000 / spent) as u32);
// A past month: whole, compared with all of the month before.
let oct = month_stats(&s, &analyse(&s, today), d("2026-10-31"), today).unwrap();
assert_eq!((oct.out, oct.same_day_last_month), (Haler(716_900), Haler(16_900)));
// A month to come has no numbers yet; an empty month is zeros, not nothing.
assert!(month_stats(&s, &analyse(&s, today), d("2026-12-01"), today).is_none());
let empty = month_stats(&s, &analyse(&s, today), d("2026-03-01"), today).unwrap();
assert!(empty.slices.is_empty());
assert_eq!((empty.out, empty.subscriptions_permille), (Haler::ZERO, 0));
}
#[test]
fn a_sum_that_would_not_fit_gives_no_numbers() {
let s = ledger(&[("2026-11-02", i64::MIN + 1, "A", "fun"), ("2026-11-03", i64::MIN + 1, "B", "fun")], vec![]);
let today = d("2026-11-15");
assert!(month_stats(&s, &analyse(&s, today), today, today).is_none());
assert!(month_plan(&s, today, today).is_none());
}
@@ -0,0 +1,225 @@
//! Mandatory test 5: on a fixture history, detection finds the known subscriptions, flags the known price
//! change and the known trial, and never calls the supermarket or the rent a subscription.
use fiscus_insight::cancel::cancel_kit;
use fiscus_insight::subscriptions::{analyse, Cadence, Status, UpcomingKind};
use fiscus_ledger::import::{plan_import, StatementLine};
use fiscus_ledger::{Date, Decision, Event, EventBody, Haler, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
fn household() -> State {
let text = include_str!("histories/household.txt");
let mut lines = Vec::new();
let mut categories = Vec::new();
for row in text.lines().filter(|l| !l.starts_with('#') && !l.trim().is_empty()) {
let f: Vec<&str> = row.split(';').collect();
lines.push(StatementLine {
bank: "test".into(),
account: "1/0000".into(),
booked: d(f[0]),
amount: Haler(f[1].parse().unwrap()),
merchant: f[2].into(),
counterparty: None,
variable_symbol: None,
message: None,
bank_ref: None,
});
categories.push(f[3].to_string());
}
let mut state = State::default();
let mut n = 0u64;
let plan = plan_import(&state, &lines, &mut || {
n += 1;
format!("i{n:05}")
}, Timestamp(0));
let mut log: Vec<Event> = plan.events.clone();
for (e, cat) in plan.events.iter().zip(&categories) {
if let (EventBody::PaymentImported { payment, .. }, false) = (&e.body, cat.is_empty()) {
n += 1;
log.push(Event::new(format!("c{n}"), Timestamp(0), EventBody::PaymentCategorised { payment: payment.clone(), category: cat.clone() }));
}
}
log.push(Event::new(
"decide-spotify",
Timestamp(0),
EventBody::SubscriptionDecided { subscription: "spotify".into(), decision: Decision::Keep, amount: Haler(19_900), on: d("2026-07-10") },
));
for e in &log {
state.apply(e);
}
assert!(state.rejected.is_empty(), "{:?}", state.rejected);
state
}
#[test]
fn finds_the_known_subscriptions_and_nothing_else() {
let insight = analyse(&household(), d("2026-11-03"));
let mut keys: Vec<(&str, Cadence)> = insight.subscriptions.iter().map(|s| (s.key.as_str(), s.cadence)).collect();
keys.sort();
assert_eq!(
keys,
vec![
("apple com bill#169", Cadence::Monthly),
("apple com bill#25", Cadence::Monthly),
("netflix com", Cadence::Monthly),
("spotify", Cadence::Monthly),
("wedos internet a s", Cadence::Yearly),
("youtube premium", Cadence::Monthly),
]
);
}
#[test]
fn flags_the_known_price_change_until_it_is_decided() {
let mut state = household();
let insight = analyse(&state, d("2026-11-03"));
let netflix = insight.subscriptions.iter().find(|s| s.key == "netflix com").unwrap();
let change = netflix.price_change.as_ref().unwrap();
assert_eq!((change.from, change.to, change.on), (Haler(19_900), Haler(25_900), d("2026-10-12")));
assert!(netflix.creep_alert);
// Spotify went up in July, and the change was decided: no alert.
let spotify = insight.subscriptions.iter().find(|s| s.key == "spotify").unwrap();
assert_eq!(spotify.price_change.as_ref().unwrap().to, Haler(19_900));
assert!(!spotify.creep_alert);
// Nobody else changed price.
assert_eq!(insight.subscriptions.iter().filter(|s| s.creep_alert).count(), 1);
state.apply(&Event::new(
"keep-netflix",
Timestamp(0),
EventBody::SubscriptionDecided { subscription: "netflix com".into(), decision: Decision::Keep, amount: Haler(25_900), on: d("2026-11-03") },
));
let after = analyse(&state, d("2026-11-03"));
let netflix = after.subscriptions.iter().find(|s| s.key == "netflix com").unwrap();
assert!(!netflix.creep_alert && !netflix.needs_review);
}
#[test]
fn flags_the_known_trial() {
let state = household();
let insight = analyse(&state, d("2026-11-03"));
assert_eq!(insight.trials.len(), 1, "{:#?}", insight.trials);
let t = &insight.trials[0];
assert_eq!(t.key, "disney plus");
assert_eq!((t.started, t.ends, t.estimated), (d("2026-10-28"), d("2026-11-27"), true));
// YouTube's 1 CZK check was followed by full charges: not a trial any more.
assert!(insight.trials.iter().all(|t| !t.key.starts_with("youtube")));
}
#[test]
fn a_trial_marked_by_hand_uses_its_end_date() {
let mut state = household();
let disney = state.effective_payments().into_iter().find(|p| p.merchant_key == "disney plus").unwrap();
state.apply(&Event::new("mark", Timestamp(0), EventBody::PaymentTrialMarked { payment: disney.id, ends: d("2026-11-07") }));
let insight = analyse(&state, d("2026-11-03"));
assert_eq!(insight.trials.len(), 1);
assert_eq!((insight.trials[0].ends, insight.trials[0].estimated), (d("2026-11-07"), false));
assert!(insight.upcoming.iter().any(|u| u.kind == UpcomingKind::TrialEnds && u.date == d("2026-11-07")));
}
#[test]
fn next_charges_and_the_seven_day_strip() {
let insight = analyse(&household(), d("2026-11-03"));
let next = |k: &str| insight.subscriptions.iter().find(|s| s.key == k).unwrap().next_charge;
assert_eq!(next("spotify"), d("2026-11-05"));
assert_eq!(next("wedos internet a s"), d("2027-03-10"));
let strip: Vec<(&str, Date)> = insight.upcoming.iter().map(|u| (u.key.as_str(), u.date)).collect();
assert_eq!(strip, vec![("spotify", d("2026-11-05")), ("apple com bill#25", d("2026-11-08"))]);
}
#[test]
fn monthly_review_and_cancel() {
let mut state = household();
let insight = analyse(&state, d("2026-11-03"));
assert!(insight.subscriptions.iter().filter(|s| s.status == Status::Active).all(|s| s.needs_review || s.cadence == Cadence::Yearly));
state.apply(&Event::new(
"cancel-yt",
Timestamp(0),
EventBody::SubscriptionDecided { subscription: "youtube premium".into(), decision: Decision::Cancel, amount: Haler(23_900), on: d("2026-10-15") },
));
let yt = |s: &State, today: &str| analyse(s, d(today)).subscriptions.into_iter().find(|s| s.key == "youtube premium").unwrap();
assert_eq!(yt(&state, "2026-11-03").status, Status::Cancelled);
// It charges again anyway.
let mut n = 0u64;
let line = StatementLine {
bank: "test".into(),
account: "1/0000".into(),
booked: d("2026-11-01"),
amount: Haler(-23_900),
merchant: "GOOGLE *YouTube Premium".into(),
counterparty: None,
variable_symbol: None,
message: None,
bank_ref: None,
};
let plan = plan_import(&state, &[line], &mut || {
n += 1;
format!("late{n}")
}, Timestamp(0));
for e in &plan.events {
state.apply(e);
}
assert_eq!(yt(&state, "2026-11-03").status, Status::ChargedAfterCancel);
}
#[test]
fn the_cancel_kit() {
let insight = analyse(&household(), d("2026-11-03"));
let netflix = insight.subscriptions.iter().find(|s| s.key == "netflix com").unwrap();
let kit = cancel_kit(netflix);
assert_eq!(kit.provider.as_deref(), Some("Netflix"));
assert_eq!(kit.url.as_deref(), Some("https://www.netflix.com/cancelplan"));
assert!(kit.email_subject.contains("Netflix"));
assert!(kit.email_body.contains("259,00"));
let wedos = insight.subscriptions.iter().find(|s| s.key == "wedos internet a s").unwrap();
let kit = cancel_kit(wedos);
assert_eq!(kit.url, None, "an unknown provider gets the email only");
assert!(kit.mailto().starts_with("mailto:?subject="));
}
#[test]
fn a_shop_visited_about_monthly_is_not_a_subscription() {
// Roughly monthly, different totals every time: the cadence fits, the price does not.
let visits = [("2026-01-10", -184_000), ("2026-02-09", -201_500), ("2026-03-11", -176_300), ("2026-04-10", -199_900), ("2026-05-09", -230_100)];
let lines: Vec<StatementLine> = visits
.iter()
.map(|(date, a)| StatementLine {
bank: "test".into(),
account: "1/0000".into(),
booked: d(date),
amount: Haler(*a),
merchant: "IKEA ZLICIN".into(),
counterparty: None,
variable_symbol: None,
message: None,
bank_ref: None,
})
.collect();
let mut state = State::default();
let mut n = 0u64;
for e in plan_import(&state.clone(), &lines, &mut || {
n += 1;
format!("k{n}")
}, Timestamp(0))
.events
{
state.apply(&e);
}
assert!(analyse(&state, d("2026-05-20")).subscriptions.is_empty());
}
#[test]
fn the_budget_forecast_runs_on_the_household() {
let mut state = household();
state.apply(&Event::new("b", Timestamp(0), EventBody::BudgetCreated { budget: "home".into(), name: "Home".into(), limit: Haler(5_000_000) }));
let today = d("2026-10-20");
let insight = analyse(&state, today);
let f = fiscus_insight::forecast::budget_forecast(&state, &insight, "home", today, 11, 2_000).unwrap();
assert_eq!(f, fiscus_insight::forecast::budget_forecast(&state, &insight, "home", today, 11, 2_000).unwrap());
assert_eq!(f.history_days, 90);
assert!(f.p10 <= f.p50 && f.p50 <= f.p90);
assert!(fiscus_insight::forecast::budget_forecast(&state, &insight, "nope", today, 11, 10).is_none());
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "fiscus-ledger"
description = "Fiscus Domi: money, dates, the event log and its state, merchant rules, matching"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
[dev-dependencies]
proptest.workspace = true
+41
View File
@@ -0,0 +1,41 @@
//! The categories the app offers. A category is an id; the label is what the app shows.
pub const UNCATEGORISED: &str = "uncategorised";
/// Money between your own accounts: never spending.
pub const TRANSFERS: &str = "transfers";
pub const INCOME: &str = "income";
/// Categories a monthly plan cannot be for: money in, money moved, and money not yet sorted.
pub const NOT_PLANNABLE: [&str; 3] = [INCOME, TRANSFERS, UNCATEGORISED];
/// The most a category's monthly plan can be: 100 000 000 CZK, far from any sum overflowing.
pub const MAX_PLAN: crate::money::Haler = crate::money::Haler(10_000_000_000);
/// `(id, label)` in the order the app lists them.
pub const DEFAULT: &[(&str, &str)] = &[
("groceries", "Groceries"),
("eating-out", "Eating out"),
("transport", "Transport"),
("housing", "Housing"),
("utilities", "Utilities"),
("subscriptions", "Subscriptions"),
("shopping", "Shopping"),
("health", "Health"),
("kids", "Kids"),
("fun", "Fun"),
("travel", "Travel"),
("gifts", "Gifts"),
(INCOME, "Income"),
(TRANSFERS, "Transfers"),
("other", "Other"),
(UNCATEGORISED, "Uncategorised"),
];
/// A category id is lowercase ASCII letters, digits and `-`, 1–40 characters.
pub fn is_valid(id: &str) -> bool {
(1..=40).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
pub fn label(id: &str) -> &str {
DEFAULT.iter().find(|(i, _)| *i == id).map(|(_, l)| *l).unwrap_or(id)
}
+192
View File
@@ -0,0 +1,192 @@
//! Civil dates as days since 1970-01-01 (proleptic Gregorian), and timestamps the app hands in.
//! There is no clock here: "today" is always a parameter.
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::str::FromStr;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Date(i32);
/// Milliseconds since the Unix epoch, as given by the app.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Timestamp(pub i64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("not a date (expected YYYY-MM-DD)")]
pub struct DateError;
const MIN_YEAR: i32 = 1900;
const MAX_YEAR: i32 = 2200;
pub fn is_leap(y: i32) -> bool {
(y % 4 == 0 && y % 100 != 0) || y % 400 == 0
}
pub fn days_in_month(y: i32, m: u32) -> u32 {
match m {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if is_leap(y) => 29,
2 => 28,
_ => 0,
}
}
impl Date {
/// `None` for an impossible date or a year outside 1900–2200.
pub fn from_ymd(y: i32, m: u32, d: u32) -> Option<Date> {
if !(MIN_YEAR..=MAX_YEAR).contains(&y) || !(1..=12).contains(&m) || d == 0 || d > days_in_month(y, m) {
return None;
}
// Howard Hinnant's days_from_civil.
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = (m as i32 + 9) % 12;
let doy = (153 * mp + 2) / 5 + d as i32 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
Some(Date(era * 146_097 + doe - 719_468))
}
pub fn from_days(days: i32) -> Date {
Date(days)
}
pub fn days(self) -> i32 {
self.0
}
pub fn ymd(self) -> (i32, u32, u32) {
let z = self.0 + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
pub fn add_days(self, n: i32) -> Date {
Date(self.0 + n)
}
/// Days from `self` to `other` (positive when `other` is later).
pub fn days_until(self, other: Date) -> i32 {
other.0 - self.0
}
/// The same day `n` months later, clamped to the month's last day (31 Jan + 1 = 28/29 Feb).
pub fn add_months(self, n: i32) -> Date {
let (y, m, d) = self.ymd();
let idx = y * 12 + (m as i32 - 1) + n;
let (ny, nm) = (idx.div_euclid(12), (idx.rem_euclid(12) + 1) as u32);
let nd = d.min(days_in_month(ny, nm));
Date::from_ymd(ny, nm, nd).unwrap_or(self)
}
pub fn add_years(self, n: i32) -> Date {
self.add_months(n * 12)
}
pub fn month_start(self) -> Date {
let (y, m, _) = self.ymd();
Date::from_ymd(y, m, 1).unwrap_or(self)
}
pub fn month_end(self) -> Date {
let (y, m, _) = self.ymd();
Date::from_ymd(y, m, days_in_month(y, m)).unwrap_or(self)
}
/// `(year, month)` — the key of a monthly budget period.
pub fn month(self) -> (i32, u32) {
let (y, m, _) = self.ymd();
(y, m)
}
/// The civil date of a timestamp in UTC. The app passes local "today" as a `Date`; this is for the log.
pub fn from_timestamp_utc(t: Timestamp) -> Date {
Date(t.0.div_euclid(86_400_000) as i32)
}
}
impl fmt::Display for Date {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (y, m, d) = self.ymd();
write!(f, "{y:04}-{m:02}-{d:02}")
}
}
impl FromStr for Date {
type Err = DateError;
fn from_str(s: &str) -> Result<Date, DateError> {
let b = s.as_bytes();
if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
return Err(DateError);
}
let num = |r: std::ops::Range<usize>| -> Result<u32, DateError> {
let part = &s[r];
if !part.bytes().all(|c| c.is_ascii_digit()) {
return Err(DateError);
}
part.parse().map_err(|_| DateError)
};
Date::from_ymd(num(0..4)? as i32, num(5..7)?, num(8..10)?).ok_or(DateError)
}
}
impl Serialize for Date {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Date {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Date, D::Error> {
let s = String::deserialize(d)?;
s.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_every_day_for_three_centuries() {
let start = Date::from_ymd(1900, 1, 1).unwrap();
let end = Date::from_ymd(2200, 12, 31).unwrap();
let mut day = start;
while day <= end {
let (y, m, d) = day.ymd();
assert_eq!(Date::from_ymd(y, m, d), Some(day));
assert_eq!(day.to_string().parse::<Date>(), Ok(day));
day = day.add_days(1);
}
assert_eq!(Date::from_ymd(1970, 1, 1).unwrap().days(), 0);
}
#[test]
fn months_clamp() {
let d = |s: &str| s.parse::<Date>().unwrap();
assert_eq!(d("2026-01-31").add_months(1), d("2026-02-28"));
assert_eq!(d("2028-01-31").add_months(1), d("2028-02-29"));
assert_eq!(d("2026-12-15").add_months(1), d("2027-01-15"));
assert_eq!(d("2026-03-31").add_months(-1), d("2026-02-28"));
assert_eq!(d("2028-02-29").add_years(1), d("2029-02-28"));
assert_eq!(d("2026-11-03").month_end(), d("2026-11-30"));
}
#[test]
fn refuses_what_is_not_a_date() {
for bad in ["2026-02-29", "2026-13-01", "2026-00-10", "26-01-01", "2026-1-01", "2026-01-01T", "+026-01-01", "1899-12-31"] {
assert!(bad.parse::<Date>().is_err(), "{bad}");
}
}
}
+168
View File
@@ -0,0 +1,168 @@
//! The event log. Append only: a correction is a new event, nothing is ever edited or removed.
use crate::date::{Date, Timestamp};
use crate::import::StatementLine;
use crate::invoice::{Invoice, InvoiceId, Supplier};
use crate::money::Haler;
use crate::split::Share;
use crate::state::Glyph;
use serde::{Deserialize, Serialize};
/// Ids are opaque strings the app generates (random, unguessable); the core never makes one up.
pub type EventId = String;
pub type PaymentId = String;
pub type BudgetId = String;
pub type RuleId = String;
pub type SplitId = String;
/// A category id, e.g. `groceries` (see [`crate::categories`]).
pub type Category = String;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Event {
pub id: EventId,
/// When the event was written (the app's clock), for display and sync; never for ordering.
pub at: Timestamp,
#[serde(flatten)]
pub body: EventBody,
}
impl Event {
pub fn new(id: impl Into<EventId>, at: Timestamp, body: EventBody) -> Event {
Event { id: id.into(), at, body }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Decision {
Keep,
Cancel,
}
/// How a share of a split was settled.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Settlement {
/// Paid by QR Platba.
Qr,
/// Marked paid by hand (cash, another way).
Marked,
}
/// Which phone a capture token is for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CaptureKind {
Iphone,
Android,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum EventBody {
/// A phone saw a card payment (○).
#[serde(rename = "payment.captured")]
PaymentCaptured { payment: PaymentId, amount: Haler, date: Date, merchant: String, card: Option<String> },
/// One statement line (●). `line_key` identifies the line across imports.
#[serde(rename = "payment.imported")]
PaymentImported { payment: PaymentId, line: StatementLine, line_key: String },
/// Added by hand (◆). The merchant may be empty (cash, "groceries").
#[serde(rename = "payment.added")]
PaymentAdded {
payment: PaymentId,
amount: Haler,
date: Date,
merchant: String,
category: Option<Category>,
note: Option<String>,
},
/// A captured or hand-added payment and the statement line that confirms it are one payment.
#[serde(rename = "payment.confirmed")]
PaymentConfirmed { payment: PaymentId, line: PaymentId },
#[serde(rename = "payment.categorised")]
PaymentCategorised { payment: PaymentId, category: Category },
#[serde(rename = "payment.assigned")]
PaymentAssigned { payment: PaymentId, budget: BudgetId },
#[serde(rename = "payment.trial_marked")]
PaymentTrialMarked { payment: PaymentId, ends: Date },
#[serde(rename = "budget.created")]
BudgetCreated { budget: BudgetId, name: String, limit: Haler },
/// A shared budget in a personal log (created here or joined): like `budget.created`, but never the
/// default budget, so unassigned payments never fall into a budget other people see.
#[serde(rename = "budget.shared")]
BudgetShared { budget: BudgetId, name: String, limit: Haler },
#[serde(rename = "budget.limit_set")]
BudgetLimitSet { budget: BudgetId, limit: Haler },
/// "Always <merchant key> → <category>".
#[serde(rename = "rule.created")]
RuleCreated { rule: RuleId, merchant_key: String, category: Category },
/// Keep or cancel a subscription (by its key), seen at `amount` (a positive cost) on `on`.
#[serde(rename = "subscription.decided")]
SubscriptionDecided { subscription: String, decision: Decision, amount: Haler, on: Date },
/// A shared budget's log: a member put this payment (as they see it) into the budget.
#[serde(rename = "payment.shared")]
PaymentShared {
payment: PaymentId,
budget: BudgetId,
amount: Haler,
date: Date,
merchant: String,
category: Option<Category>,
glyph: Glyph,
},
/// A shared budget's log: the payment is taken out of the budget again.
#[serde(rename = "payment.unshared")]
PaymentUnshared { payment: PaymentId, budget: BudgetId },
/// The payment's amount, split among people (see [`crate::split::split_equal`]).
#[serde(rename = "split.created")]
SplitCreated { split: SplitId, payment: PaymentId, payer: String, shares: Vec<Share> },
#[serde(rename = "split.settled")]
SplitSettled { split: SplitId, person: String, how: Settlement },
/// A phone's capture token: only its SHA-256 in lowercase hex. The token itself lives in Custos.
#[serde(rename = "capture.token_added")]
CaptureTokenAdded { token: String, name: String, kind: CaptureKind },
#[serde(rename = "capture.token_revoked")]
CaptureTokenRevoked { token: String },
/// A share link for one person of a split: only the SHA-256 of the link's token, in lowercase hex.
#[serde(rename = "share.link_created")]
ShareLinkCreated { link: String, split: SplitId, person: String, expires: Date },
/// The account people pay back to by QR Platba.
#[serde(rename = "account.set")]
AccountSet { iban: String, name: String },
/// The name this person shows to the members of their shared budgets (the personal log).
#[serde(rename = "profile.named")]
ProfileNamed { name: String },
/// Share my subscription names with this shared budget's members, or stop (the personal log).
#[serde(rename = "household.sharing_set")]
HouseholdSharingSet { budget: BudgetId, on: bool },
/// A shared budget's log: the name its author shows there. The latest per author counts.
#[serde(rename = "member.named")]
MemberNamed { budget: BudgetId, name: String },
/// A shared budget's log: every subscription its author pays, as service keys (`spotify`). The latest per
/// author replaces the earlier ones; an empty list withdraws them.
#[serde(rename = "subscriptions.shared")]
SubscriptionsShared { budget: BudgetId, names: Vec<String> },
/// Who issues invoices from this ledger, and what share of each paid one is set aside for tax. The latest
/// counts from then on; an invoice keeps the supplier it was issued under.
#[serde(rename = "supplier.set")]
SupplierSet { supplier: Supplier },
#[serde(rename = "invoice.issued")]
InvoiceIssued { invoice: Invoice },
/// Paid: by `payment` (a statement line whose amount and variable symbol match), or marked paid by hand
/// (`None`: cash, another account). The reserve is set aside then.
#[serde(rename = "invoice.paid")]
InvoicePaid { invoice: InvoiceId, payment: Option<PaymentId>, on: Date },
/// Cancelled before it was paid.
#[serde(rename = "invoice.cancelled")]
InvoiceCancelled { invoice: InvoiceId },
/// Money taken out of the tax reserve (the tax or insurance paid from it).
#[serde(rename = "reserve.withdrawn")]
ReserveWithdrawn { withdrawal: String, amount: Haler, on: Date, note: String },
/// The most you mean to spend on one category in a month, from the month of `from` (its 1st) on, until a
/// later plan for that category replaces it. Zero removes the plan. Personal log only.
#[serde(rename = "category.planned")]
CategoryPlanned { category: Category, amount: Haler, from: Date },
/// A category of your own (an id as [`crate::categories::is_valid`]) and the name the app shows for it.
#[serde(rename = "category.created")]
CategoryCreated { category: Category, label: String },
}
+109
View File
@@ -0,0 +1,109 @@
//! Turning parsed statement lines into events: new lines only, then the matches they make.
use crate::date::{Date, Timestamp};
use crate::event::{Event, EventBody};
use crate::matching::{find_matches, MatchReport};
use crate::money::Haler;
use crate::state::State;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
/// One line of a bank statement, as a bank parser produced it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatementLine {
/// The parser's bank id, e.g. `fio`.
pub bank: String,
/// The statement's own account, as the bank writes it.
pub account: String,
pub booked: Date,
pub amount: Haler,
/// The merchant or payee text; may be empty.
pub merchant: String,
pub counterparty: Option<String>,
pub variable_symbol: Option<String>,
pub message: Option<String>,
/// The bank's own id for the transaction, when the format has one.
pub bank_ref: Option<String>,
}
impl StatementLine {
/// No control characters and nothing over 500 characters, in any text field.
pub fn is_clean(&self) -> bool {
let ok = |s: &str| s.chars().count() <= 500 && !s.chars().any(|c| c.is_control());
[&self.bank, &self.account, &self.merchant].iter().all(|s| ok(s))
&& [&self.counterparty, &self.variable_symbol, &self.message, &self.bank_ref]
.iter()
.all(|s| s.as_deref().is_none_or(ok))
}
}
/// The identity of each line across imports. With the bank's own id: bank|account|id. Without one: the line's
/// fields plus how many identical lines came before it in this file, so two identical coffees stay two lines
/// and the same file imported again gives the same keys.
pub fn line_keys(lines: &[StatementLine]) -> Vec<String> {
let mut seen: BTreeMap<String, u32> = BTreeMap::new();
lines
.iter()
.map(|l| {
let base = match &l.bank_ref {
Some(r) => format!("{}|{}|ref:{}", l.bank, l.account, r),
None => format!(
"{}|{}|{}|{}|{}|{}|{}|{}",
l.bank,
l.account,
l.booked,
l.amount.0,
l.merchant,
l.counterparty.as_deref().unwrap_or(""),
l.variable_symbol.as_deref().unwrap_or(""),
l.message.as_deref().unwrap_or("")
),
};
let n = seen.entry(base.clone()).or_insert(0);
*n += 1;
if l.bank_ref.is_some() {
base
} else {
format!("{base}#{n}")
}
})
.collect()
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImportPlan {
/// One `payment.imported` per new line, in file order.
pub events: Vec<Event>,
/// One `payment.confirmed` per certain match, to append after `events` when the user confirms.
pub confirmations: Vec<Event>,
/// Lines already in the ledger (or repeated in the file under the same bank id), skipped.
pub duplicates: usize,
/// The matches as they would be with the new lines in.
pub report: MatchReport,
}
/// Plans an import. Nothing is applied: the app appends `events`, then `confirmations`.
/// `ids` gives fresh ids: for each new line its payment id then its event id, then one per confirmation.
pub fn plan_import(state: &State, lines: &[StatementLine], ids: &mut dyn FnMut() -> String, at: Timestamp) -> ImportPlan {
let mut sim = state.clone();
let mut plan = ImportPlan::default();
let mut batch: BTreeSet<String> = BTreeSet::new();
for (line, key) in lines.iter().zip(line_keys(lines)) {
if state.line_keys.contains_key(&key) || !batch.insert(key.clone()) {
plan.duplicates += 1;
continue;
}
let payment = ids();
let event = Event::new(ids(), at, EventBody::PaymentImported { payment, line: line.clone(), line_key: key });
sim.apply(&event);
plan.events.push(event);
}
plan.report = find_matches(&sim);
plan.confirmations = plan
.report
.pairs
.iter()
.map(|(payment, line)| Event::new(ids(), at, EventBody::PaymentConfirmed { payment: payment.clone(), line: line.clone() }))
.collect();
plan
}
+343
View File
@@ -0,0 +1,343 @@
//! Invoices (faktury): the supplier, the customer, the lines and their totals, the number that is also the
//! variable symbol, and the tax reserve set aside when one is paid. Money in haléře; quantities in thousandths.
//!
//! - A line's amount is `quantity × unit price`, rounded half away from zero to the haléř.
//! - A VAT invoice (the supplier is a VAT payer): the base of each rate is the sum of its lines; the VAT of a rate
//! is `base × rate / 100`, rounded the same way, once per rate (§ 37 ZDPH: from the base, per rate).
//! - A non-VAT invoice has no rates, no taxable-supply date, and says the supplier is not a VAT payer.
//! - The number is `YYYYNNNN`: the year it was issued and the invoice's place in that year. The same digits are
//! the variable symbol, so a payment is matched by them.
use crate::date::{Date, Timestamp};
use crate::event::{Event, EventBody};
use crate::money::Haler;
use crate::pay::MAX_AMOUNT;
use crate::state::{CategorySource, EffectivePayment, InvoiceRecord, State};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
pub type InvoiceId = String;
/// The VAT rates in force in Czechia (from 2024): 21 %, 12 %, and 0 % for exempt supplies.
pub const VAT_RATES: [u8; 3] = [21, 12, 0];
/// At most this many lines on one invoice.
pub const MAX_LINES: usize = 50;
/// A quantity, in thousandths: from 0,001 to 1 000 000.
pub const MAX_QUANTITY: i64 = 1_000_000_000;
/// The share of a paid invoice set aside for tax, in thousandths: at most 60 %.
pub const MAX_RESERVE_PERMILLE: u16 = 600;
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum InvoiceError {
#[error("a name must be 1-100 characters")]
Name,
#[error("an address has 1-4 lines of at most 100 characters")]
Address,
#[error("not a valid IČO (8 digits with a check digit)")]
Ico,
#[error("not a valid DIČ (CZ and 8-10 digits)")]
Dic,
#[error("an invoice has 1-50 lines")]
Lines,
#[error("a line's text must be 1-200 characters, its unit at most 10")]
LineText,
#[error("a quantity is between 0,001 and 1 000 000")]
Quantity,
#[error("a unit price is between 0,01 and 9 999 999,99 CZK")]
Price,
#[error("a VAT rate is 21, 12 or 0 %")]
Rate,
#[error("a VAT invoice gives every line a rate; an invoice without VAT gives none")]
RateUse,
#[error("the total must be between 0,01 and 9 999 999,99 CZK")]
Total,
#[error("an invoice number is the year and 4 digits, e.g. 20260001")]
Number,
#[error("the due date is before the issue date")]
Due,
#[error("a VAT invoice needs the date of the taxable supply; one without VAT has none")]
Taxable,
#[error("a VAT payer has a DIČ")]
PayerDic,
#[error("the reserve is 0-60 %")]
Reserve,
}
/// Someone on an invoice: the supplier or the customer.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Party {
pub name: String,
/// Street, town and postcode, country: 1-4 lines.
pub address: Vec<String>,
pub ico: Option<String>,
pub dic: Option<String>,
}
/// The person issuing invoices from this ledger.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Supplier {
pub party: Party,
pub vat_payer: bool,
/// Of each paid invoice's amount without VAT, this many thousandths are set aside for income tax and
/// insurance (a VAT payer's VAT is always set aside in full, on top).
pub reserve_permille: u16,
/// A line printed on the invoice, such as the trade register entry. Optional.
pub registration: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvoiceLine {
pub text: String,
/// Thousandths: 1 500 is 1,5.
pub quantity: i64,
/// `ks`, `h`, …; may be empty.
pub unit: String,
/// Per unit, without VAT on a VAT invoice.
pub unit_price: Haler,
/// The VAT rate in percent on a VAT invoice; `None` on an invoice without VAT.
pub vat: Option<u8>,
}
/// The language an invoice is printed in, chosen per invoice.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Language {
#[default]
Cs,
En,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Invoice {
pub id: InvoiceId,
/// `YYYYNNNN`, also the variable symbol.
pub number: String,
pub issued: Date,
pub due: Date,
/// The date of the taxable supply (DUZP), on a VAT invoice only.
pub taxable: Option<Date>,
pub customer: Party,
pub lines: Vec<InvoiceLine>,
/// The budget the payment goes into when it arrives; `None`: the default budget.
pub budget: Option<String>,
/// What the printed invoice is in. Absent in an event: Czech.
#[serde(default)]
pub language: Language,
}
/// What an invoice adds up to.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Totals {
/// Each line's amount, in order.
pub lines: Vec<Haler>,
/// Rate → (base, VAT), highest rate first. Empty on an invoice without VAT.
pub rates: Vec<(u8, Haler, Haler)>,
/// Without VAT.
pub net: Haler,
pub vat: Haler,
/// What the customer pays.
pub total: Haler,
}
/// `a × b / d`, rounded half away from zero, or `None` when it does not fit an `i64`.
fn mul_div_round(a: i64, b: i64, d: i64) -> Option<i64> {
let n = i128::from(a) * i128::from(b);
let d = i128::from(d);
let q = n / d;
let r = n % d;
let q = if 2 * r.abs() >= d { q + n.signum() } else { q };
i64::try_from(q).ok()
}
fn text_ok(s: &str, min: usize, max: usize) -> bool {
let n = s.trim().chars().count();
(min..=max).contains(&n) && s.chars().count() <= max + 20 && !s.chars().any(|c| c.is_control())
}
/// An IČO: 8 digits whose last is the weighted mod-11 check of the first seven.
pub fn ico_ok(s: &str) -> bool {
if s.len() != 8 || !s.bytes().all(|b| b.is_ascii_digit()) {
return false;
}
let d: Vec<u32> = s.bytes().map(|b| u32::from(b - b'0')).collect();
let sum: u32 = (0..7).map(|i| d[i] * (8 - i as u32)).sum();
let check = (11 - sum % 11) % 10;
d[7] == check
}
/// A Czech DIČ: `CZ` and 8-10 digits.
pub fn dic_ok(s: &str) -> bool {
s.len() >= 10 && s.len() <= 12 && s.starts_with("CZ") && s[2..].bytes().all(|b| b.is_ascii_digit())
}
impl Party {
pub fn check(&self) -> Result<(), InvoiceError> {
if !text_ok(&self.name, 1, 100) {
return Err(InvoiceError::Name);
}
if self.address.is_empty() || self.address.len() > 4 || !self.address.iter().all(|l| text_ok(l, 1, 100)) {
return Err(InvoiceError::Address);
}
if self.ico.as_deref().is_some_and(|i| !ico_ok(i)) {
return Err(InvoiceError::Ico);
}
if self.dic.as_deref().is_some_and(|d| !dic_ok(d)) {
return Err(InvoiceError::Dic);
}
Ok(())
}
}
impl Supplier {
pub fn check(&self) -> Result<(), InvoiceError> {
self.party.check()?;
if self.vat_payer && self.party.dic.is_none() {
return Err(InvoiceError::PayerDic);
}
if self.reserve_permille > MAX_RESERVE_PERMILLE {
return Err(InvoiceError::Reserve);
}
if self.registration.as_deref().is_some_and(|r| !text_ok(r, 1, 200)) {
return Err(InvoiceError::Name);
}
Ok(())
}
/// What is set aside when an invoice with these totals is paid: all of its VAT, and the reserve share of
/// the rest.
pub fn reserve_for(&self, t: &Totals) -> Haler {
let share = mul_div_round(t.net.0, i64::from(self.reserve_permille), 1000).unwrap_or(0);
Haler(t.vat.0.saturating_add(share))
}
}
/// The amount of one line.
pub fn line_amount(quantity: i64, unit_price: Haler) -> Result<Haler, InvoiceError> {
if !(1..=MAX_QUANTITY).contains(&quantity) {
return Err(InvoiceError::Quantity);
}
if unit_price.0 <= 0 || unit_price > MAX_AMOUNT {
return Err(InvoiceError::Price);
}
mul_div_round(quantity, unit_price.0, 1000).map(Haler).ok_or(InvoiceError::Total)
}
/// The totals of `lines`, for a VAT payer or not. Checks every line.
pub fn totals(lines: &[InvoiceLine], vat_payer: bool) -> Result<Totals, InvoiceError> {
if lines.is_empty() || lines.len() > MAX_LINES {
return Err(InvoiceError::Lines);
}
let mut amounts = Vec::with_capacity(lines.len());
let mut bases: BTreeMap<u8, i64> = BTreeMap::new();
let mut net: i64 = 0;
for l in lines {
if !text_ok(&l.text, 1, 200) || !text_ok(&l.unit, 0, 10) {
return Err(InvoiceError::LineText);
}
match (vat_payer, l.vat) {
(true, Some(r)) if VAT_RATES.contains(&r) => {}
(true, Some(_)) => return Err(InvoiceError::Rate),
(false, None) => {}
_ => return Err(InvoiceError::RateUse),
}
let a = line_amount(l.quantity, l.unit_price)?;
amounts.push(a);
net = net.checked_add(a.0).ok_or(InvoiceError::Total)?;
if let Some(r) = l.vat {
let b = bases.entry(r).or_default();
*b = b.checked_add(a.0).ok_or(InvoiceError::Total)?;
}
}
let mut rates = Vec::new();
let mut vat: i64 = 0;
for (r, base) in bases.into_iter().rev() {
let v = mul_div_round(base, i64::from(r), 100).ok_or(InvoiceError::Total)?;
vat = vat.checked_add(v).ok_or(InvoiceError::Total)?;
rates.push((r, Haler(base), Haler(v)));
}
let total = net.checked_add(vat).ok_or(InvoiceError::Total)?;
if total <= 0 || Haler(total) > MAX_AMOUNT {
return Err(InvoiceError::Total);
}
Ok(Totals { lines: amounts, rates, net: Haler(net), vat: Haler(vat), total: Haler(total) })
}
/// The number of the `seq`-th invoice of `year`: `20260001`.
pub fn invoice_number(year: i32, seq: u32) -> Result<String, InvoiceError> {
if !(2000..=9999).contains(&year) || !(1..=9999).contains(&seq) {
return Err(InvoiceError::Number);
}
Ok(format!("{year}{seq:04}"))
}
impl Invoice {
/// Everything about the invoice that does not depend on the ledger; the totals when it is sound.
pub fn check(&self, supplier: &Supplier) -> Result<Totals, InvoiceError> {
let (year, _, _) = self.issued.ymd();
let n = &self.number;
if n.len() != 8 || !n.bytes().all(|b| b.is_ascii_digit()) || n[..4] != year.to_string() || &n[4..] == "0000" {
return Err(InvoiceError::Number);
}
if self.due < self.issued {
return Err(InvoiceError::Due);
}
if supplier.vat_payer != self.taxable.is_some() {
return Err(InvoiceError::Taxable);
}
self.customer.check()?;
totals(&self.lines, supplier.vat_payer)
}
}
/// A variable symbol as banks write it, compared without leading zeros (`0020260001` is `20260001`).
pub fn same_vs(a: &str, b: &str) -> bool {
let t = |s: &str| s.trim().trim_start_matches('0').to_string();
!t(a).is_empty() && t(a) == t(b)
}
/// The events that record invoices paid by statement lines. A line pays an unpaid invoice when its amount is the
/// invoice's total and its variable symbol is the invoice's number; the earliest such line wins, and a line pays
/// one invoice only. The line becomes income, in the invoice's budget. Nothing is guessed: a line of another
/// amount, or without the symbol, stays for the person to look at.
pub fn plan_invoice_payments(state: &State, ids: &mut dyn FnMut() -> String, at: Timestamp) -> Vec<Event> {
let mut open: Vec<&InvoiceRecord> = state.invoices.values().filter(|r| r.paid.is_none() && !r.cancelled).collect();
open.sort_by_key(|r| r.seq);
let lines: Vec<EffectivePayment> = state.effective_payments().into_iter().filter(|p| p.line.is_some() && p.amount.0 > 0).collect();
let mut taken: BTreeSet<String> = state.invoice_payments.keys().cloned().collect();
let mut out = Vec::new();
for r in open {
let found = lines.iter().find(|p| {
let line = p.line.as_deref().unwrap_or_default();
p.amount == r.totals.total
&& p.date >= r.invoice.issued
&& p.variable_symbol.as_deref().is_some_and(|vs| same_vs(vs, &r.invoice.number))
&& !taken.contains(line)
&& !taken.contains(&p.id)
});
let Some(p) = found else { continue };
let line = p.line.clone().unwrap_or_default();
taken.insert(line.clone());
taken.insert(p.id.clone());
out.push(Event::new(ids(), at, EventBody::InvoicePaid { invoice: r.invoice.id.clone(), payment: Some(line.clone()), on: p.date }));
if p.category_source != CategorySource::Explicit {
out.push(Event::new(ids(), at, EventBody::PaymentCategorised { payment: line.clone(), category: "income".into() }));
}
if let Some(b) = &r.invoice.budget {
out.push(Event::new(ids(), at, EventBody::PaymentAssigned { payment: line, budget: b.clone() }));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rounding_is_half_away_from_zero() {
assert_eq!(mul_div_round(1, 5, 10), Some(1));
assert_eq!(mul_div_round(1, 4, 10), Some(0));
assert_eq!(mul_div_round(-1, 5, 10), Some(-1));
assert_eq!(mul_div_round(i64::MAX, i64::MAX, 1), None);
}
}
+21
View File
@@ -0,0 +1,21 @@
//! Fiscus Domi's ledger: money in haléře, civil dates, the append-only event log and the state derived from
//! it, merchant keys and rules, capture ↔ statement matching, splits and QR Platba. Pure: no I/O, no clock, no
//! randomness.
pub mod categories;
pub mod date;
pub mod event;
pub mod import;
pub mod invoice;
pub mod matching;
pub mod merchant;
pub mod money;
pub mod pay;
pub mod share;
pub mod split;
pub mod state;
pub use date::{Date, Timestamp};
pub use event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, Settlement, SplitId};
pub use money::Haler;
pub use state::{EffectivePayment, Glyph, Origin, ShareView, State};
+114
View File
@@ -0,0 +1,114 @@
//! Capture ↔ statement matching. One to one, never a guess: a pair is matched only when each side is the
//! other's single best candidate; everything else is reported for the user.
use crate::event::PaymentId;
use crate::merchant::compatible;
use crate::state::{Origin, PaymentRecord, State};
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
/// A statement line may be booked this many days before the capture …
pub const WINDOW_BEFORE: i32 = 1;
/// … and this many days after it.
pub const WINDOW_AFTER: i32 = 5;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ambiguity {
/// The captured or hand-added payment.
pub payment: PaymentId,
/// Statement lines it could be, best first.
pub candidates: Vec<PaymentId>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MatchReport {
/// `(captured or hand-added, statement line)`, matched with certainty.
pub pairs: Vec<(PaymentId, PaymentId)>,
/// Unmatched payments that have possible lines: the user picks.
pub ambiguous: Vec<Ambiguity>,
/// Every captured or hand-added payment not in `pairs`.
pub unmatched_captured: Vec<PaymentId>,
/// Every statement line not in `pairs`.
pub unmatched_lines: Vec<PaymentId>,
}
/// How well a line fits a payment. `None`: it cannot be the same payment.
/// `Some((strong, exact, -gap))`, compared as a tuple; only strong fits are ever matched automatically.
fn fit(p: &PaymentRecord, l: &PaymentRecord) -> Option<(bool, bool, i32)> {
if p.amount != l.amount {
return None;
}
let gap = p.date.days_until(l.date);
if !(-WINDOW_BEFORE..=WINDOW_AFTER).contains(&gap) {
return None;
}
if p.merchant_key.is_empty() || l.merchant_key.is_empty() {
return Some((false, false, -gap.abs()));
}
if !compatible(&p.merchant_key, &l.merchant_key) {
return None;
}
Some((true, p.merchant_key == l.merchant_key, -gap.abs()))
}
/// The single best candidate, if it is strictly better than the second.
fn unique_best<'a>(cands: impl Iterator<Item = (&'a PaymentId, (bool, bool, i32))>) -> Option<&'a PaymentId> {
let mut v: Vec<_> = cands.filter(|(_, s)| s.0).collect();
v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
match v.as_slice() {
[] => None,
[only] => Some(only.0),
[first, second, ..] if first.1 > second.1 => Some(first.0),
_ => None,
}
}
pub fn find_matches(state: &State) -> MatchReport {
let mut left: Vec<&PaymentRecord> =
state.payments.values().filter(|p| p.origin != Origin::Imported && p.partner.is_none()).collect();
let mut right: Vec<&PaymentRecord> =
state.payments.values().filter(|p| p.origin == Origin::Imported && p.partner.is_none()).collect();
left.sort_by_key(|p| p.seq);
right.sort_by_key(|p| p.seq);
let mut done_l: BTreeSet<&PaymentId> = BTreeSet::new();
let mut done_r: BTreeSet<&PaymentId> = BTreeSet::new();
let mut pairs: Vec<(u64, PaymentId, PaymentId)> = Vec::new();
loop {
let mut found = Vec::new();
for p in left.iter().filter(|p| !done_l.contains(&p.id)) {
let open_r = right.iter().filter(|l| !done_r.contains(&l.id));
let Some(best) = unique_best(open_r.filter_map(|l| fit(p, l).map(|s| (&l.id, s)))) else { continue };
let line = right.iter().find(|l| &l.id == best).expect("best comes from right");
let open_l = left.iter().filter(|q| !done_l.contains(&q.id));
if unique_best(open_l.filter_map(|q| fit(q, line).map(|s| (&q.id, s)))) == Some(&p.id) {
found.push((p.seq, &p.id, &line.id));
}
}
if found.is_empty() {
break;
}
for (seq, p, l) in found {
done_l.insert(p);
done_r.insert(l);
pairs.push((seq, p.clone(), l.clone()));
}
}
pairs.sort();
let mut report = MatchReport { pairs: pairs.into_iter().map(|(_, p, l)| (p, l)).collect(), ..Default::default() };
for p in left.iter().filter(|p| !done_l.contains(&p.id)) {
report.unmatched_captured.push(p.id.clone());
let mut cands: Vec<_> = right
.iter()
.filter(|l| !done_r.contains(&l.id))
.filter_map(|l| fit(p, l).map(|s| (s, &l.id)))
.collect();
cands.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1)));
if !cands.is_empty() {
report.ambiguous.push(Ambiguity { payment: p.id.clone(), candidates: cands.into_iter().map(|(_, id)| id.clone()).collect() });
}
}
report.unmatched_lines = right.iter().filter(|l| !done_r.contains(&l.id)).map(|l| l.id.clone()).collect();
report
}
+107
View File
@@ -0,0 +1,107 @@
//! Merchant keys: the same shop written differently by a phone, a bank and a person becomes one key.
//! Rules and subscriptions are keyed on it.
/// `PAYPAL *SPOTIFY P1234` → `spotify`; `ALBERT 1234 PRAHA 4 CZ` → `albert praha`; `Žabka` → `zabka`.
pub fn merchant_key(raw: &str) -> String {
let folded: String = raw.chars().flat_map(fold).collect::<String>().to_lowercase();
// A processor's prefix before `*`: "paypal *spotify", "sumup *kavarna", "sq *bistro".
let rest = match folded.split_once('*') {
Some((head, tail)) if !tail.trim().is_empty() && head.trim().split_whitespace().count() <= 2 => tail,
_ => folded.as_str(),
};
let cleaned: String = rest.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { ' ' }).collect();
let mut words: Vec<&str> = cleaned
.split_whitespace()
.filter(|w| !w.bytes().any(|b| b.is_ascii_digit()))
.collect();
while words.len() > 1 && matches!(words.last(), Some(&"cz") | Some(&"cze") | Some(&"czech")) {
words.pop();
}
words.join(" ")
}
/// Whether two merchant keys can be the same shop: equal, one inside the other, or the same first word of
/// at least three letters. An empty key is never compatible.
pub fn compatible(a: &str, b: &str) -> bool {
if a.is_empty() || b.is_empty() {
return false;
}
if a == b || contains_words(a, b) || contains_words(b, a) {
return true;
}
match (a.split(' ').next(), b.split(' ').next()) {
(Some(x), Some(y)) => x == y && x.len() >= 3,
_ => false,
}
}
/// `needle`'s words appear in `hay` as a run of whole words.
fn contains_words(hay: &str, needle: &str) -> bool {
let h: Vec<&str> = hay.split(' ').collect();
let n: Vec<&str> = needle.split(' ').collect();
n.len() <= h.len() && h.windows(n.len()).any(|w| w == n.as_slice())
}
/// ASCII folding of the Latin letters a Czech (or Slovak, German, Polish) shop name uses.
fn fold(c: char) -> std::iter::Once<char> {
let r = match c {
'á' | 'ä' | 'à' | 'â' | 'ą' => 'a',
'Á' | 'Ä' | 'À' | 'Â' | 'Ą' => 'A',
'č' | 'ć' | 'ç' => 'c',
'Č' | 'Ć' | 'Ç' => 'C',
'ď' => 'd',
'Ď' => 'D',
'é' | 'ě' | 'ë' | 'è' | 'ê' | 'ę' => 'e',
'É' | 'Ě' | 'Ë' | 'È' | 'Ê' | 'Ę' => 'E',
'í' | 'ï' | 'î' => 'i',
'Í' | 'Ï' | 'Î' => 'I',
'ľ' | 'ĺ' | 'ł' => 'l',
'Ľ' | 'Ĺ' | 'Ł' => 'L',
'ň' | 'ń' => 'n',
'Ň' | 'Ń' => 'N',
'ó' | 'ö' | 'ô' | 'ő' => 'o',
'Ó' | 'Ö' | 'Ô' | 'Ő' => 'O',
'ř' | 'ŕ' => 'r',
'Ř' | 'Ŕ' => 'R',
'š' | 'ś' => 's',
'Š' | 'Ś' => 'S',
'ť' => 't',
'Ť' => 'T',
'ú' | 'ů' | 'ü' | 'ű' => 'u',
'Ú' | 'Ů' | 'Ü' | 'Ű' => 'U',
'ý' | 'ÿ' => 'y',
'Ý' => 'Y',
'ž' | 'ź' | 'ż' => 'z',
'Ž' | 'Ź' | 'Ż' => 'Z',
'ß' => 's',
other => other,
};
std::iter::once(r)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys() {
assert_eq!(merchant_key("PAYPAL *SPOTIFY P1234"), "spotify");
assert_eq!(merchant_key("ALBERT 1234 PRAHA 4 CZ"), "albert praha");
assert_eq!(merchant_key("Žabka"), "zabka");
assert_eq!(merchant_key("NETFLIX.COM"), "netflix com");
assert_eq!(merchant_key("SumUp *Kavárna Dobrá"), "kavarna dobra");
assert_eq!(merchant_key(" "), "");
assert_eq!(merchant_key("123 456"), "");
assert_eq!(merchant_key("Kč * "), "kc");
}
#[test]
fn compatibility() {
assert!(compatible("albert", "albert praha"));
assert!(compatible("albert praha", "albert brno"));
assert!(compatible("netflix com", "netflix"));
assert!(!compatible("lidl", "albert"));
assert!(!compatible("", "albert"));
assert!(!compatible("od praha", "od brno"), "a two-letter first word is not enough");
}
}
+143
View File
@@ -0,0 +1,143 @@
//! Money: whole haléře in an `i64`. Outflows are negative, as on a statement. Every operation is checked.
use serde::{Deserialize, Serialize};
use std::fmt;
/// An amount in haléře (1 CZK = 100 haléřů).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Haler(pub i64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum MoneyError {
#[error("the amount is too large")]
Overflow,
#[error("there is nobody to split between")]
NoWeight,
#[error("not an amount in CZK")]
NotAnAmount,
}
impl Haler {
pub const ZERO: Haler = Haler(0);
pub fn checked_add(self, other: Haler) -> Result<Haler, MoneyError> {
self.0.checked_add(other.0).map(Haler).ok_or(MoneyError::Overflow)
}
pub fn checked_sub(self, other: Haler) -> Result<Haler, MoneyError> {
self.0.checked_sub(other.0).map(Haler).ok_or(MoneyError::Overflow)
}
pub fn checked_neg(self) -> Result<Haler, MoneyError> {
self.0.checked_neg().map(Haler).ok_or(MoneyError::Overflow)
}
pub fn is_outflow(self) -> bool {
self.0 < 0
}
/// The sum, or `Overflow`. Integer addition is associative, so the order never matters.
pub fn sum<I: IntoIterator<Item = Haler>>(items: I) -> Result<Haler, MoneyError> {
items.into_iter().try_fold(Haler::ZERO, Haler::checked_add)
}
/// `-1 234,50`: a space between thousands, a decimal comma, always two decimals, no currency.
pub fn to_czk(self) -> String {
let neg = self.0 < 0;
let abs = self.0.unsigned_abs();
let whole = (abs / 100).to_string();
let mut grouped = String::with_capacity(whole.len() + whole.len() / 3);
for (i, c) in whole.chars().enumerate() {
if i > 0 && (whole.len() - i) % 3 == 0 {
grouped.push(' ');
}
grouped.push(c);
}
format!("{}{},{:02}", if neg { "-" } else { "" }, grouped, abs % 100)
}
/// The inverse of [`Haler::to_czk`], also taking a plain `1234`, `1234,5` or `1234.50` as typed by hand.
/// Strict: one optional leading minus, ASCII digits, spaces only between groups of three, at most two
/// decimals after one `,` or `.`.
pub fn parse_czk(text: &str) -> Result<Haler, MoneyError> {
let t = text.trim();
let (neg, t) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t),
};
let (int, frac) = match t.find([',', '.']) {
Some(i) => (&t[..i], Some(&t[i + 1..])),
None => (t, None),
};
let groups: Vec<&str> = int.split(' ').collect();
if groups.iter().any(|g| g.is_empty() || !g.bytes().all(|b| b.is_ascii_digit()))
|| groups.iter().skip(1).any(|g| g.len() != 3)
|| (groups.len() > 1 && groups[0].len() > 3)
{
return Err(MoneyError::NotAnAmount);
}
let digits: String = groups.concat();
let cents = match frac {
None => 0,
Some(f) if (1..=2).contains(&f.len()) && f.bytes().all(|b| b.is_ascii_digit()) => {
let v: i64 = f.parse().map_err(|_| MoneyError::NotAnAmount)?;
if f.len() == 1 {
v * 10
} else {
v
}
}
Some(_) => return Err(MoneyError::NotAnAmount),
};
let whole: i64 = digits.parse().map_err(|_| MoneyError::Overflow)?;
let abs = whole.checked_mul(100).and_then(|w| w.checked_add(cents)).ok_or(MoneyError::Overflow)?;
Ok(Haler(if neg { -abs } else { abs }))
}
}
impl fmt::Display for Haler {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} Kč", self.to_czk())
}
}
/// Splits `total` by `weights` so that the shares always sum to `total` exactly.
///
/// Largest remainder: each share is `floor(|total|·w/Σw)`; the haléře left over go one each to the largest
/// remainders, ties to the lower index. A negative total is split as its absolute value, then mirrored.
pub fn split(total: Haler, weights: &[u64]) -> Result<Vec<Haler>, MoneyError> {
let sum_w: u128 = weights.iter().map(|w| *w as u128).sum();
if sum_w == 0 {
return Err(MoneyError::NoWeight);
}
let abs = total.0.unsigned_abs() as u128;
let mut shares: Vec<u128> = Vec::with_capacity(weights.len());
let mut rems: Vec<(u128, usize)> = Vec::with_capacity(weights.len());
for (i, w) in weights.iter().enumerate() {
let num = abs * (*w as u128);
shares.push(num / sum_w);
rems.push((num % sum_w, i));
}
let given: u128 = shares.iter().sum();
let mut left = abs - given; // < weights.len()
// Largest remainder first; equal remainders by index.
rems.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
for (rem, i) in rems {
if left == 0 {
break;
}
if rem == 0 && weights[i] == 0 {
continue;
}
shares[i] += 1;
left -= 1;
}
shares
.into_iter()
.map(|s| {
let s = i64::try_from(s).map_err(|_| MoneyError::Overflow)?;
Ok(Haler(if total.0 < 0 { -s } else { s }))
})
.collect()
}
+148
View File
@@ -0,0 +1,148 @@
//! QR Platba: a checked Czech IBAN and the SPAYD 1.0 string a banking app scans.
use crate::money::Haler;
use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum PayError {
#[error("not a valid Czech account number or IBAN")]
Account,
#[error("the amount must be between 0,01 and 9 999 999,99 CZK")]
Amount,
#[error("a variable symbol is 1-10 digits")]
VariableSymbol,
#[error("a text has control characters")]
Text,
}
/// A Czech IBAN (`CZ` + 22 digits) whose check digits are right.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Iban(String);
/// The largest amount QR Platba carries: 9 999 999,99 CZK.
pub const MAX_AMOUNT: Haler = Haler(999_999_999);
/// The remainder mod 97 of a string of digits and letters (A = 10 … Z = 35), as IBAN check digits use.
fn mod97(s: &str) -> Option<u32> {
let mut r: u32 = 0;
for c in s.chars() {
let v = c.to_digit(36)?;
r = if v < 10 { (r * 10 + v) % 97 } else { (r * 100 + v) % 97 };
}
Some(r)
}
/// The Czech weighted mod-11 check of an account prefix or number, right-aligned to the weights.
fn mod11(digits: &str, weights: &[u32]) -> bool {
if digits.len() > weights.len() {
return false;
}
let pad = weights.len() - digits.len();
let sum: u32 = digits.bytes().enumerate().map(|(i, b)| u32::from(b - b'0') * weights[pad + i]).sum();
sum.is_multiple_of(11)
}
const PREFIX_WEIGHTS: [u32; 6] = [10, 5, 8, 4, 2, 1];
const NUMBER_WEIGHTS: [u32; 10] = [6, 3, 7, 9, 10, 5, 8, 4, 2, 1];
fn all_digits(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}
impl Iban {
/// `CZ65 0800 0000 1920 0014 5399` (spaces and case do not matter) or a Czech account
/// `[prefix-]number/bank` such as `19-2000145399/0800`.
pub fn parse(text: &str) -> Result<Iban, PayError> {
let t = text.trim();
if let Some((account, bank)) = t.split_once('/') {
return Iban::from_czech(account.trim(), bank.trim());
}
let compact: String = t.chars().filter(|c| *c != ' ').collect::<String>().to_ascii_uppercase();
if compact.len() != 24 || !compact.starts_with("CZ") || !all_digits(&compact[2..]) {
return Err(PayError::Account);
}
let rearranged = format!("{}{}", &compact[4..], &compact[..4]);
if mod97(&rearranged) != Some(1) {
return Err(PayError::Account);
}
// The BBAN inside must itself be a valid Czech account.
let (prefix, number) = (&compact[8..14], &compact[14..]);
if !mod11(prefix, &PREFIX_WEIGHTS) || !mod11(number, &NUMBER_WEIGHTS) {
return Err(PayError::Account);
}
Ok(Iban(compact))
}
fn from_czech(account: &str, bank: &str) -> Result<Iban, PayError> {
let (prefix, number) = account.split_once('-').unwrap_or(("", account));
let ok = (prefix.is_empty() || (all_digits(prefix) && prefix.len() <= 6))
&& all_digits(number)
&& (2..=10).contains(&number.len())
&& bank.len() == 4
&& all_digits(bank)
&& mod11(prefix, &PREFIX_WEIGHTS)
&& mod11(number, &NUMBER_WEIGHTS);
if !ok {
return Err(PayError::Account);
}
let bban = format!("{bank}{prefix:0>6}{number:0>10}");
let check = 98 - mod97(&format!("{bban}CZ00")).ok_or(PayError::Account)?;
Iban::parse(&format!("CZ{check:02}{bban}"))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for Iban {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
/// A SPAYD text value: `*` written as `%2A`, cut to `max` characters without splitting an escape.
fn text(value: &str, max: usize) -> Result<String, PayError> {
if value.chars().any(|c| c.is_control()) {
return Err(PayError::Text);
}
let mut out = String::new();
let mut count = 0;
for c in value.trim().chars() {
let piece = if c == '*' { "%2A".to_string() } else { c.to_string() };
let n = piece.chars().count();
if count + n > max {
break;
}
out.push_str(&piece);
count += n;
}
Ok(out)
}
/// `SPD*1.0*ACC:<IBAN>*AM:<amount>*CC:CZK[*RN:<name>]*MSG:<message>[*X-VS:<vs>]`.
/// The amount is positive and written from haléře (`450.00`); the name is cut to 35 characters and the
/// message to 60.
pub fn spayd(iban: &Iban, amount: Haler, name: Option<&str>, message: &str, vs: Option<&str>) -> Result<String, PayError> {
if amount.0 <= 0 || amount > MAX_AMOUNT {
return Err(PayError::Amount);
}
let mut s = format!("SPD*1.0*ACC:{}*AM:{}.{:02}*CC:CZK", iban.0, amount.0 / 100, amount.0 % 100);
if let Some(name) = name {
let rn = text(name, 35)?;
if !rn.is_empty() {
s.push_str(&format!("*RN:{rn}"));
}
}
let msg = text(message, 60)?;
if !msg.is_empty() {
s.push_str(&format!("*MSG:{msg}"));
}
if let Some(vs) = vs {
if !all_digits(vs) || vs.len() > 10 {
return Err(PayError::VariableSymbol);
}
s.push_str(&format!("*X-VS:{vs}"));
}
Ok(s)
}
+30
View File
@@ -0,0 +1,30 @@
//! What a shared budget may receive from a personal log: one payment, as its owner sees it, and only once it
//! is assigned to that budget. Its card, note, statement details, rules and origin events stay home.
use crate::event::EventBody;
use crate::state::State;
/// `payment.shared` for `payment` into `budget`, or `None` unless that payment was **explicitly** assigned to
/// that budget (`payment.assigned`, the latest on either half of a confirmed pair). Falling into a budget as
/// the default never shares a payment.
pub fn shared_payment(state: &State, payment: &str, budget: &str) -> Option<EventBody> {
let p = state.effective_payment(payment)?;
let explicit = [p.captured.as_deref(), p.line.as_deref()]
.into_iter()
.flatten()
.filter_map(|id| state.payments.get(id).and_then(|r| r.budget.as_ref()))
.max_by_key(|stamp| stamp.seq)
.map(|stamp| stamp.value.as_str());
if explicit != Some(budget) {
return None;
}
Some(EventBody::PaymentShared {
payment: p.id,
budget: budget.into(),
amount: p.amount,
date: p.date,
merchant: p.merchant,
category: p.category,
glyph: p.glyph,
})
}
+34
View File
@@ -0,0 +1,34 @@
//! Splitting one payment among people: shares in haléře that always sum to the payment's amount.
use crate::money::{split, Haler, MoneyError};
use serde::{Deserialize, Serialize};
/// Someone a payment can be split with: an app user (their id is their Tessera root) or a contact.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Person {
pub id: String,
pub name: String,
}
/// One person's part of a split. Same sign as the payment (an outflow's shares are negative).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Share {
pub person: String,
pub name: String,
pub amount: Haler,
}
/// Equal shares. The people are sorted by id and deduplicated first, so every device gets the same shares
/// whatever order they were picked in; the leftover haléře go to the first people in that order (the day-1
/// largest-remainder [`split`]).
pub fn split_equal(total: Haler, people: &[Person]) -> Result<Vec<Share>, MoneyError> {
let mut sorted: Vec<&Person> = people.iter().collect();
sorted.sort_by(|a, b| a.id.cmp(&b.id));
sorted.dedup_by(|a, b| a.id == b.id);
let amounts = split(total, &vec![1; sorted.len()])?;
Ok(sorted
.into_iter()
.zip(amounts)
.map(|(p, amount)| Share { person: p.id.clone(), name: p.name.clone(), amount })
.collect())
}
+926
View File
@@ -0,0 +1,926 @@
//! State = `apply()` folded over the log. Deterministic: every collection is ordered, nothing depends on a
//! clock or a hash seed, and `apply()` is total (an event that does not fit is recorded as rejected).
use crate::categories;
use crate::date::Date;
use crate::event::{BudgetId, CaptureKind, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId, Settlement, SplitId};
use crate::import::StatementLine;
use crate::invoice::{Invoice, InvoiceId, Supplier, Totals};
use crate::merchant::merchant_key;
use crate::money::Haler;
use crate::pay::{spayd, Iban};
use crate::split::Share;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
const MAX_TEXT: usize = 500;
/// Where a payment record came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Origin {
Captured,
Imported,
Added,
}
/// What the app shows next to a payment: ○ captured, ● on a statement, ◆ added by hand.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Glyph {
Captured,
Confirmed,
Hand,
}
impl Glyph {
pub fn symbol(self) -> char {
match self {
Glyph::Captured => '○',
Glyph::Confirmed => '●',
Glyph::Hand => '◆',
}
}
}
/// A value and the position in the log that set it: the later one wins.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Stamped<T> {
pub seq: u64,
pub value: T,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaymentRecord {
pub id: PaymentId,
pub origin: Origin,
pub seq: u64,
pub amount: Haler,
pub date: Date,
pub merchant: String,
pub merchant_key: String,
pub card: Option<String>,
pub note: Option<String>,
pub line: Option<StatementLine>,
pub category: Option<Stamped<Category>>,
pub budget: Option<Stamped<BudgetId>>,
pub trial_ends: Option<Stamped<Date>>,
/// The other half of a confirmed pair.
pub partner: Option<PaymentId>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Budget {
pub id: BudgetId,
pub name: String,
pub limit: Haler,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rule {
pub id: RuleId,
pub category: Category,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DecisionRecord {
pub decision: Decision,
pub amount: Haler,
pub on: Date,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Settled {
pub how: Settlement,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Split {
pub id: SplitId,
pub payment: PaymentId,
pub payer: String,
pub shares: Vec<Share>,
/// Person → how they settled. The payer never appears here.
pub settled: BTreeMap<String, Settled>,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CaptureToken {
pub name: String,
pub kind: CaptureKind,
pub revoked: bool,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareLink {
pub split: SplitId,
pub person: String,
pub expires: Date,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Account {
pub iban: String,
pub name: String,
}
/// Everything a share-link page shows: one person's share of one payment, and how to pay it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareView {
pub name: String,
/// What they owe, positive.
pub amount: Haler,
pub merchant: String,
pub date: Date,
/// QR Platba, when an account is set.
pub spayd: Option<String>,
}
/// An issued invoice, its totals, and what became of it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvoiceRecord {
pub invoice: Invoice,
/// The supplier as it was when the invoice was issued.
pub supplier: Supplier,
pub totals: Totals,
pub paid: Option<Paid>,
pub cancelled: bool,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Paid {
/// The statement line that paid it; `None` when marked paid by hand.
pub payment: Option<PaymentId>,
pub on: Date,
/// Set aside for tax: the VAT, and the reserve share of the rest.
pub reserve: Haler,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlanRecord {
/// The 1st of the month the plan counts from.
pub from: Date,
/// Positive; zero removes the plan.
pub amount: Haler,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Withdrawal {
pub id: String,
pub amount: Haler,
pub on: Date,
pub note: String,
pub seq: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rejection {
pub event: EventId,
pub seq: u64,
pub reason: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct State {
/// Events seen, accepted or not.
pub seq: u64,
pub events: BTreeSet<EventId>,
pub payments: BTreeMap<PaymentId, PaymentRecord>,
pub line_keys: BTreeMap<String, PaymentId>,
pub budgets: BTreeMap<BudgetId, Budget>,
/// The first budget created (never a shared one): where a payment goes when nobody assigned it.
pub default_budget: Option<BudgetId>,
/// Merchant key → the latest rule for it.
pub rules: BTreeMap<String, Rule>,
/// Subscription key → its decisions, oldest first.
pub decisions: BTreeMap<String, Vec<DecisionRecord>>,
/// Payments that came into this log by `payment.shared` (a shared budget's log).
pub shared: BTreeSet<PaymentId>,
pub splits: BTreeMap<SplitId, Split>,
/// SHA-256 (hex) of a phone's capture token → the token's record.
pub capture_tokens: BTreeMap<String, CaptureToken>,
/// SHA-256 (hex) of a share link's token → the link.
pub share_links: BTreeMap<String, ShareLink>,
pub account: Option<Account>,
/// The name shown to the members of my shared budgets (`profile.named`).
pub profile_name: Option<String>,
/// The shared budgets I share my subscription names with (`household.sharing_set`).
pub household_sharing: BTreeSet<BudgetId>,
pub supplier: Option<Supplier>,
pub invoices: BTreeMap<InvoiceId, InvoiceRecord>,
/// Invoice number → invoice.
pub invoice_numbers: BTreeMap<String, InvoiceId>,
/// A statement line → the invoice it paid.
pub invoice_payments: BTreeMap<PaymentId, InvoiceId>,
pub withdrawals: Vec<Withdrawal>,
/// Category → its monthly plans, in log order (`category.planned`).
pub category_plans: BTreeMap<Category, Vec<PlanRecord>>,
/// Your own categories: id → the name shown (`category.created`).
pub custom_categories: BTreeMap<Category, String>,
pub rejected: Vec<Rejection>,
}
/// Why a category is what it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CategorySource {
Explicit,
Rule,
None,
}
/// One payment as the user sees it: a confirmed pair is one payment.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EffectivePayment {
/// The captured or hand-added id when there is one (so a row keeps its id when confirmed), else the line's.
pub id: PaymentId,
pub captured: Option<PaymentId>,
pub line: Option<PaymentId>,
pub glyph: Glyph,
pub origin: Origin,
pub seq: u64,
pub amount: Haler,
pub date: Date,
pub merchant: String,
pub merchant_key: String,
pub card: Option<String>,
pub note: Option<String>,
pub counterparty: Option<String>,
pub variable_symbol: Option<String>,
pub message: Option<String>,
pub category: Option<Category>,
pub category_source: CategorySource,
pub budget: Option<BudgetId>,
pub trial_ends: Option<Date>,
}
/// A person's name, or one shared subscription name.
const MAX_PERSON: usize = 40;
const MAX_SHARED_NAMES: usize = 100;
fn text_ok(s: &str) -> bool {
s.chars().count() <= MAX_TEXT && !s.chars().any(|c| c.is_control())
}
fn opt_text_ok(s: &Option<String>) -> bool {
s.as_deref().is_none_or(text_ok)
}
fn name_ok(s: &str, max: usize) -> bool {
!s.trim().is_empty() && s.chars().count() <= max && text_ok(s)
}
fn id_ok(s: &str) -> bool {
!s.is_empty() && s.len() <= 100 && text_ok(s)
}
/// A SHA-256 in lowercase hex.
fn hash_ok(s: &str) -> bool {
s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
fn latest<T: Clone>(a: &Option<Stamped<T>>, b: Option<&Option<Stamped<T>>>) -> Option<T> {
let b = b.and_then(|b| b.as_ref());
match (a.as_ref(), b) {
(Some(x), Some(y)) => Some(if x.seq >= y.seq { x.value.clone() } else { y.value.clone() }),
(Some(x), None) => Some(x.value.clone()),
(None, Some(y)) => Some(y.value.clone()),
(None, None) => None,
}
}
impl State {
pub fn replay<'a, I: IntoIterator<Item = &'a Event>>(log: I) -> State {
let mut s = State::default();
for e in log {
s.apply(e);
}
s
}
/// Applies one event. Never panics; an event that does not fit is recorded in `rejected`.
pub fn apply(&mut self, e: &Event) {
self.seq += 1;
let seq = self.seq;
if !self.events.insert(e.id.clone()) {
self.reject(e, "the same event twice");
return;
}
if let Err(reason) = self.try_apply(&e.body, seq) {
self.reject(e, reason);
}
}
fn reject(&mut self, e: &Event, reason: &str) {
self.rejected.push(Rejection { event: e.id.clone(), seq: self.seq, reason: reason.into() });
}
fn new_payment(&self, id: &PaymentId, amount: Haler) -> Result<(), &'static str> {
if id.is_empty() || id.len() > 100 {
return Err("a payment id must be 1-100 characters");
}
if self.payments.contains_key(id) {
return Err("a payment with this id exists");
}
if amount == Haler::ZERO {
return Err("a payment of zero");
}
Ok(())
}
fn payment_mut(&mut self, id: &PaymentId) -> Result<&mut PaymentRecord, &'static str> {
self.payments.get_mut(id).ok_or("no such payment")
}
fn try_apply(&mut self, body: &EventBody, seq: u64) -> Result<(), &'static str> {
match body {
EventBody::PaymentCaptured { payment, amount, date, merchant, card } => {
self.new_payment(payment, *amount)?;
if !text_ok(merchant) || !opt_text_ok(card) {
return Err("a text field is too long or has control characters");
}
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin: Origin::Captured,
seq,
amount: *amount,
date: *date,
merchant: merchant.clone(),
merchant_key: merchant_key(merchant),
card: card.clone(),
note: None,
line: None,
category: None,
budget: None,
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentImported { payment, line, line_key } => {
// A zero line (a card check) is still a line: allowed, unlike a zero capture.
self.new_payment(payment, Haler(1))?;
if line_key.is_empty() || self.line_keys.contains_key(line_key) {
return Err("this statement line was imported before");
}
if !line.is_clean() {
return Err("a text field is too long or has control characters");
}
self.line_keys.insert(line_key.clone(), payment.clone());
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin: Origin::Imported,
seq,
amount: line.amount,
date: line.booked,
merchant: line.merchant.clone(),
merchant_key: merchant_key(&line.merchant),
card: None,
note: None,
line: Some(line.clone()),
category: None,
budget: None,
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentAdded { payment, amount, date, merchant, category, note } => {
self.new_payment(payment, *amount)?;
if !text_ok(merchant) || !opt_text_ok(note) {
return Err("a text field is too long or has control characters");
}
if category.as_deref().is_some_and(|c| !categories::is_valid(c)) {
return Err("not a category id");
}
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin: Origin::Added,
seq,
amount: *amount,
date: *date,
merchant: merchant.clone(),
merchant_key: merchant_key(merchant),
card: None,
note: note.clone(),
line: None,
category: category.clone().map(|value| Stamped { seq, value }),
budget: None,
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentConfirmed { payment, line } => {
let p = self.payments.get(payment).ok_or("no such payment")?;
let l = self.payments.get(line).ok_or("no such statement line")?;
if p.origin == Origin::Imported || l.origin != Origin::Imported {
return Err("a confirmation ties a captured or hand-added payment to a statement line");
}
if p.partner.is_some() || l.partner.is_some() {
return Err("already confirmed");
}
if p.amount != l.amount {
return Err("the amounts differ");
}
self.payment_mut(payment)?.partner = Some(line.clone());
self.payment_mut(line)?.partner = Some(payment.clone());
}
EventBody::PaymentCategorised { payment, category } => {
if !categories::is_valid(category) {
return Err("not a category id");
}
self.payment_mut(payment)?.category = Some(Stamped { seq, value: category.clone() });
}
EventBody::PaymentAssigned { payment, budget } => {
if !self.budgets.contains_key(budget) {
return Err("no such budget");
}
self.payment_mut(payment)?.budget = Some(Stamped { seq, value: budget.clone() });
}
EventBody::PaymentTrialMarked { payment, ends } => {
self.payment_mut(payment)?.trial_ends = Some(Stamped { seq, value: *ends });
}
EventBody::BudgetCreated { budget, name, limit } | EventBody::BudgetShared { budget, name, limit } => {
if budget.is_empty() || self.budgets.contains_key(budget) {
return Err("a budget with this id exists");
}
let name = name.trim();
if name.is_empty() || name.chars().count() > 60 || !text_ok(name) {
return Err("a budget name must be 1-60 characters");
}
if limit.0 < 0 {
return Err("a limit cannot be negative");
}
self.budgets.insert(budget.clone(), Budget { id: budget.clone(), name: name.into(), limit: *limit, seq });
if self.default_budget.is_none() && matches!(body, EventBody::BudgetCreated { .. }) {
self.default_budget = Some(budget.clone());
}
}
EventBody::BudgetLimitSet { budget, limit } => {
if limit.0 < 0 {
return Err("a limit cannot be negative");
}
self.budgets.get_mut(budget).ok_or("no such budget")?.limit = *limit;
}
EventBody::RuleCreated { rule, merchant_key: key, category } => {
if key.is_empty() || merchant_key(key) != *key {
return Err("not a merchant key");
}
if !categories::is_valid(category) {
return Err("not a category id");
}
self.rules.insert(key.clone(), Rule { id: rule.clone(), category: category.clone(), seq });
}
EventBody::SubscriptionDecided { subscription, decision, amount, on } => {
if subscription.is_empty() || !text_ok(subscription) {
return Err("not a subscription key");
}
if amount.0 < 0 {
return Err("a subscription's amount is a cost, not negative");
}
self.decisions
.entry(subscription.clone())
.or_default()
.push(DecisionRecord { decision: *decision, amount: *amount, on: *on, seq });
}
EventBody::PaymentShared { payment, budget, amount, date, merchant, category, glyph } => {
if !self.budgets.contains_key(budget) {
return Err("no such budget");
}
if self.payments.contains_key(payment) && !self.shared.contains(payment) {
return Err("a payment with this id exists");
}
if !id_ok(payment) || *amount == Haler::ZERO {
return Err("a payment needs an id and an amount");
}
if !text_ok(merchant) {
return Err("a text field is too long or has control characters");
}
if category.as_deref().is_some_and(|c| !categories::is_valid(c)) {
return Err("not a category id");
}
let origin = match glyph {
Glyph::Captured => Origin::Captured,
Glyph::Confirmed => Origin::Imported,
Glyph::Hand => Origin::Added,
};
self.shared.insert(payment.clone());
self.payments.insert(
payment.clone(),
PaymentRecord {
id: payment.clone(),
origin,
seq,
amount: *amount,
date: *date,
merchant: merchant.clone(),
merchant_key: merchant_key(merchant),
card: None,
note: None,
line: None,
category: category.clone().map(|value| Stamped { seq, value }),
budget: Some(Stamped { seq, value: budget.clone() }),
trial_ends: None,
partner: None,
},
);
}
EventBody::PaymentUnshared { payment, budget } => {
if !self.shared.contains(payment) {
return Err("this payment was not shared here");
}
if self.payments.get(payment).and_then(|p| p.budget.as_ref()).map(|b| &b.value) != Some(budget) {
return Err("this payment is not in that budget");
}
if self.splits.values().any(|sp| sp.payment == *payment) {
return Err("this payment is split; it stays shared");
}
self.shared.remove(payment);
self.payments.remove(payment);
}
EventBody::SplitCreated { split, payment, payer, shares } => {
if !id_ok(split) || self.splits.contains_key(split) {
return Err("a split needs a new id");
}
let total = self.effective_payment(payment).ok_or("no such payment")?.amount;
if !total.is_outflow() {
return Err("only a payment out can be split");
}
if shares.is_empty() || shares.len() > 50 {
return Err("a split is among 1-50 people");
}
let people: BTreeSet<&str> = shares.iter().map(|s| s.person.as_str()).collect();
if people.len() != shares.len() {
return Err("a person appears twice in the split");
}
if shares.iter().any(|s| !id_ok(&s.person) || !name_ok(&s.name, 60)) {
return Err("every share needs a person and a name");
}
if !people.contains(payer.as_str()) {
return Err("the payer must be one of the people");
}
if shares.iter().any(|s| s.amount.0 > 0) {
return Err("a share has the wrong sign");
}
if Haler::sum(shares.iter().map(|s| s.amount)) != Ok(total) {
return Err("the shares do not add up to the payment");
}
self.splits.insert(
split.clone(),
Split {
id: split.clone(),
payment: payment.clone(),
payer: payer.clone(),
shares: shares.clone(),
settled: BTreeMap::new(),
seq,
},
);
}
EventBody::SplitSettled { split, person, how } => {
let sp = self.splits.get_mut(split).ok_or("no such split")?;
if !sp.shares.iter().any(|s| s.person == *person) {
return Err("this person is not in the split");
}
if sp.payer == *person {
return Err("the payer owes nothing");
}
if sp.settled.contains_key(person) {
return Err("already settled");
}
sp.settled.insert(person.clone(), Settled { how: *how, seq });
}
EventBody::CaptureTokenAdded { token, name, kind } => {
if !hash_ok(token) {
return Err("a capture token is stored only as its SHA-256");
}
if self.capture_tokens.contains_key(token) {
return Err("this capture token exists");
}
if !name_ok(name, 60) {
return Err("a phone's name must be 1-60 characters");
}
self.capture_tokens.insert(token.clone(), CaptureToken { name: name.trim().into(), kind: *kind, revoked: false, seq });
}
EventBody::CaptureTokenRevoked { token } => {
let t = self.capture_tokens.get_mut(token).ok_or("no such capture token")?;
if t.revoked {
return Err("already revoked");
}
t.revoked = true;
}
EventBody::ShareLinkCreated { link, split, person, expires } => {
if !hash_ok(link) {
return Err("a share link is stored only as its SHA-256");
}
if self.share_links.contains_key(link) {
return Err("this share link exists");
}
let sp = self.splits.get(split).ok_or("no such split")?;
if sp.payer == *person || !sp.shares.iter().any(|s| s.person == *person) {
return Err("a share link is for someone who owes a share");
}
self.share_links.insert(link.clone(), ShareLink { split: split.clone(), person: person.clone(), expires: *expires, seq });
}
EventBody::AccountSet { iban, name } => {
let iban = Iban::parse(iban).map_err(|_| "not a valid Czech account")?;
if !name_ok(name, 70) {
return Err("an account name must be 1-70 characters");
}
self.account = Some(Account { iban: iban.as_str().into(), name: name.trim().into() });
}
EventBody::ProfileNamed { name } => {
if !name_ok(name, MAX_PERSON) {
return Err("a name must be 1-40 characters");
}
self.profile_name = Some(name.trim().into());
}
EventBody::HouseholdSharingSet { budget, on } => {
if !self.budgets.contains_key(budget) || self.default_budget.as_ref() == Some(budget) {
return Err("subscription names are shared only with a shared budget");
}
if *on {
self.household_sharing.insert(budget.clone());
} else {
self.household_sharing.remove(budget);
}
}
EventBody::MemberNamed { budget, name } => {
if !self.budgets.contains_key(budget) {
return Err("no such budget");
}
if !name_ok(name, MAX_PERSON) {
return Err("a name must be 1-40 characters");
}
}
EventBody::SupplierSet { supplier } => {
supplier.check().map_err(|_| "not a valid supplier")?;
self.supplier = Some(supplier.clone());
}
EventBody::InvoiceIssued { invoice } => {
let supplier = self.supplier.clone().ok_or("set the supplier before issuing an invoice")?;
if !id_ok(&invoice.id) || self.invoices.contains_key(&invoice.id) {
return Err("an invoice with this id exists");
}
if self.invoice_numbers.contains_key(&invoice.number) {
return Err("an invoice with this number exists");
}
if invoice.budget.as_ref().is_some_and(|b| !self.budgets.contains_key(b)) {
return Err("no such budget");
}
let totals = invoice.check(&supplier).map_err(|_| "not a valid invoice")?;
self.invoice_numbers.insert(invoice.number.clone(), invoice.id.clone());
self.invoices.insert(invoice.id.clone(), InvoiceRecord { invoice: invoice.clone(), supplier, totals, paid: None, cancelled: false, seq });
}
EventBody::InvoicePaid { invoice, payment, on } => {
let rec = self.invoices.get(invoice).ok_or("no such invoice")?;
if rec.cancelled || rec.paid.is_some() {
return Err("the invoice is cancelled or paid already");
}
if *on < rec.invoice.issued {
return Err("paid before it was issued");
}
if let Some(p) = payment {
if self.invoice_payments.contains_key(p) {
return Err("this payment paid another invoice");
}
let e = self.effective_payment(p).ok_or("no such payment")?;
if e.line.is_none() || e.amount != rec.totals.total {
return Err("the payment is not a statement line of the invoice's amount");
}
}
let reserve = rec.supplier.reserve_for(&rec.totals);
if let Some(p) = payment {
self.invoice_payments.insert(p.clone(), invoice.clone());
}
let rec = self.invoices.get_mut(invoice).ok_or("no such invoice")?;
rec.paid = Some(Paid { payment: payment.clone(), on: *on, reserve, seq });
}
EventBody::InvoiceCancelled { invoice } => {
let rec = self.invoices.get_mut(invoice).ok_or("no such invoice")?;
if rec.paid.is_some() || rec.cancelled {
return Err("only an unpaid invoice can be cancelled");
}
rec.cancelled = true;
}
EventBody::ReserveWithdrawn { withdrawal, amount, on, note } => {
if !id_ok(withdrawal) || self.withdrawals.iter().any(|w| &w.id == withdrawal) {
return Err("a withdrawal with this id exists");
}
if amount.0 <= 0 || *amount > self.reserve_balance() {
return Err("more than the reserve holds");
}
if note.chars().count() > 200 || !text_ok(note) {
return Err("a note is at most 200 characters");
}
self.withdrawals.push(Withdrawal { id: withdrawal.clone(), amount: *amount, on: *on, note: note.clone(), seq });
}
EventBody::CategoryPlanned { category, amount, from } => {
if !self.category_known(category) || categories::NOT_PLANNABLE.contains(&category.as_str()) {
return Err("not a category that can have a plan");
}
if amount.0 < 0 || *amount > categories::MAX_PLAN {
return Err("a plan is 0-100 000 000 CZK");
}
if from.ymd().2 != 1 {
return Err("a plan starts on the 1st of a month");
}
self.category_plans.entry(category.clone()).or_default().push(PlanRecord { from: *from, amount: *amount, seq });
}
EventBody::CategoryCreated { category, label } => {
if !categories::is_valid(category) {
return Err("not a category id");
}
if self.category_known(category) {
return Err("this category exists");
}
if !name_ok(label, MAX_PERSON) || label.trim() != label {
return Err("a category's name must be 1-40 characters");
}
self.custom_categories.insert(category.clone(), label.clone());
}
EventBody::SubscriptionsShared { budget, names } => {
if !self.budgets.contains_key(budget) {
return Err("no such budget");
}
if names.len() > MAX_SHARED_NAMES {
return Err("at most 100 subscription names");
}
if names.iter().any(|n| !name_ok(n, MAX_PERSON) || n.trim() != n) {
return Err("a subscription name must be 1-40 characters");
}
if names.iter().collect::<BTreeSet<_>>().len() != names.len() {
return Err("a subscription name appears twice");
}
}
}
Ok(())
}
/// A default category or one of your own.
pub fn category_known(&self, id: &str) -> bool {
categories::DEFAULT.iter().any(|(d, _)| *d == id) || self.custom_categories.contains_key(id)
}
/// The name the app shows for a category: yours, the default one, or the id itself.
pub fn category_label(&self, id: &str) -> String {
self.custom_categories.get(id).cloned().unwrap_or_else(|| categories::label(id).to_string())
}
/// Every category the app offers: the default ones in their order, then yours by id.
pub fn categories(&self) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = categories::DEFAULT.iter().map(|(id, l)| (id.to_string(), l.to_string())).collect();
out.extend(self.custom_categories.iter().map(|(id, l)| (id.clone(), l.clone())));
out
}
/// The plan for `category` in the month of `month`: the latest plan from that month or before (by month,
/// then log order); `None` without one, or when it was set to zero.
pub fn plan_for(&self, category: &str, month: Date) -> Option<Haler> {
let start = month.month_start();
self.category_plans
.get(category)?
.iter()
.filter(|p| p.from <= start)
.max_by_key(|p| (p.from, p.seq))
.map(|p| p.amount)
.filter(|a| a.0 > 0)
}
/// What the tax reserve holds: everything set aside for paid invoices, less what was taken out.
pub fn reserve_balance(&self) -> Haler {
let set: i64 = self.invoices.values().filter_map(|r| r.paid.as_ref()).map(|p| p.reserve.0).fold(0, i64::saturating_add);
let out: i64 = self.withdrawals.iter().map(|w| w.amount.0).fold(0, i64::saturating_add);
Haler(set.saturating_sub(out))
}
/// The number the next invoice issued in `year` gets.
pub fn next_invoice_number(&self, year: i32) -> Option<String> {
let prefix = year.to_string();
let last = self.invoice_numbers.keys().filter(|n| n.starts_with(&prefix)).filter_map(|n| n[4..].parse::<u32>().ok()).max().unwrap_or(0);
crate::invoice::invoice_number(year, last + 1).ok()
}
/// QR Platba for an unpaid invoice: its total, its number as the variable symbol, to the account set.
pub fn invoice_spayd(&self, invoice: &str) -> Option<String> {
let r = self.invoices.get(invoice)?;
if r.paid.is_some() || r.cancelled {
return None;
}
let a = self.account.as_ref()?;
let iban = Iban::parse(&a.iban).ok()?;
spayd(&iban, r.totals.total, Some(&a.name), &format!("Faktura {}", r.invoice.number), Some(&r.invoice.number)).ok()
}
/// Whether a phone's capture token (its SHA-256 in hex) may post captures.
pub fn capture_token_active(&self, token: &str) -> bool {
self.capture_tokens.get(token).is_some_and(|t| !t.revoked)
}
/// The page behind a share link (its token's SHA-256 in hex): one person's open share, or `None` for an
/// unknown, expired (after `expires`) or settled link.
pub fn share_view(&self, link: &str, today: Date) -> Option<ShareView> {
let l = self.share_links.get(link)?;
if today > l.expires {
return None;
}
let sp = self.splits.get(&l.split)?;
if sp.settled.contains_key(&l.person) {
return None;
}
let share = sp.shares.iter().find(|s| s.person == l.person)?;
let p = self.effective_payment(&sp.payment)?;
let amount = share.amount.checked_neg().ok()?;
let (y, m, d) = p.date.ymd();
let message = format!("{} {d}.{m}.{y}", p.merchant.trim());
let spayd = self.account.as_ref().and_then(|a| {
let iban = Iban::parse(&a.iban).ok()?;
spayd(&iban, amount, Some(&a.name), &message, None).ok()
});
Some(ShareView { name: share.name.clone(), amount, merchant: p.merchant, date: p.date, spayd })
}
/// Every payment as the user sees it, a confirmed pair as one, in date order (then log order).
pub fn effective_payments(&self) -> Vec<EffectivePayment> {
let mut out: Vec<EffectivePayment> = self
.payments
.values()
.filter(|p| !(p.origin == Origin::Imported && p.partner.is_some()))
.map(|p| self.effective(p))
.collect();
out.sort_by(|a, b| a.date.cmp(&b.date).then(a.seq.cmp(&b.seq)));
out
}
/// The effective payment that contains `id` (either half of a pair).
pub fn effective_payment(&self, id: &str) -> Option<EffectivePayment> {
let p = self.payments.get(id)?;
let primary = match (&p.origin, &p.partner) {
(Origin::Imported, Some(partner)) => self.payments.get(partner)?,
_ => p,
};
Some(self.effective(primary))
}
fn effective(&self, p: &PaymentRecord) -> EffectivePayment {
let partner = p.partner.as_ref().and_then(|id| self.payments.get(id));
let line_rec = if p.origin == Origin::Imported { Some(p) } else { partner };
let line = line_rec.and_then(|r| r.line.as_ref());
let merchant = match line {
Some(l) if !l.merchant.trim().is_empty() => l.merchant.clone(),
_ => p.merchant.clone(),
};
let key = merchant_key(&merchant);
let explicit = latest(&p.category, partner.map(|q| &q.category));
let (category, category_source) = match explicit {
Some(c) => (Some(c), CategorySource::Explicit),
None => match self.rules.get(&key) {
Some(r) => (Some(r.category.clone()), CategorySource::Rule),
None => (None, CategorySource::None),
},
};
let budget = latest(&p.budget, partner.map(|q| &q.budget)).or_else(|| self.default_budget.clone());
EffectivePayment {
id: p.id.clone(),
captured: if p.origin == Origin::Imported { None } else { Some(p.id.clone()) },
line: line_rec.map(|r| r.id.clone()),
glyph: match (line_rec.is_some(), p.origin) {
(true, _) => Glyph::Confirmed,
(false, Origin::Added) => Glyph::Hand,
(false, _) => Glyph::Captured,
},
origin: p.origin,
seq: p.seq,
amount: line_rec.map(|r| r.amount).unwrap_or(p.amount),
date: line_rec.map(|r| r.date).unwrap_or(p.date),
merchant,
merchant_key: key,
card: p.card.clone(),
note: p.note.clone(),
counterparty: line.and_then(|l| l.counterparty.clone()),
variable_symbol: line.and_then(|l| l.variable_symbol.clone()),
message: line.and_then(|l| l.message.clone()),
category,
category_source,
budget,
trial_ends: latest(&p.trial_ends, partner.map(|q| &q.trial_ends)),
}
}
}
+86
View File
@@ -0,0 +1,86 @@
//! v1 close: the name a person shows to the members of their shared budgets, the opt-in to share
//! subscription names with a shared budget, and what a shared budget's log may hold of either.
use fiscus_ledger::{Event, EventBody, Haler, State, Timestamp};
fn ev(id: &str, body: EventBody) -> Event {
Event::new(id, Timestamp(0), body)
}
fn budgets() -> Vec<Event> {
vec![
ev("e1", EventBody::BudgetCreated { budget: "b-mine".into(), name: "Mine".into(), limit: Haler(1_000_000) }),
ev("e2", EventBody::BudgetShared { budget: "b-home".into(), name: "Home".into(), limit: Haler(2_000_000) }),
]
}
fn rejected(log: &[Event]) -> Vec<String> {
State::replay(log).rejected.iter().map(|r| r.reason.clone()).collect()
}
#[test]
fn the_profile_name_is_the_latest_trimmed_and_bounded() {
let mut log = budgets();
log.push(ev("n1", EventBody::ProfileNamed { name: " Mark ".into() }));
log.push(ev("n2", EventBody::ProfileNamed { name: "Marek".into() }));
assert_eq!(State::replay(&log).profile_name.as_deref(), Some("Marek"));
for bad in ["", " ", "a\u{7}b", &"x".repeat(41)] {
let mut log = budgets();
log.push(ev("n", EventBody::ProfileNamed { name: bad.into() }));
assert_eq!(rejected(&log).len(), 1, "{bad:?} is not a name");
assert_eq!(State::replay(&log).profile_name, None);
}
}
#[test]
fn subscription_sharing_is_an_opt_in_per_shared_budget() {
let mut log = budgets();
log.push(ev("h1", EventBody::HouseholdSharingSet { budget: "b-home".into(), on: true }));
assert!(State::replay(&log).household_sharing.contains("b-home"));
log.push(ev("h2", EventBody::HouseholdSharingSet { budget: "b-home".into(), on: false }));
assert!(State::replay(&log).household_sharing.is_empty(), "opting out takes it back");
let mut log = budgets();
log.push(ev("h1", EventBody::HouseholdSharingSet { budget: "b-mine".into(), on: true }));
log.push(ev("h2", EventBody::HouseholdSharingSet { budget: "b-none".into(), on: true }));
assert_eq!(rejected(&log).len(), 2, "never the default budget, never an unknown one");
assert!(State::replay(&log).household_sharing.is_empty());
}
#[test]
fn a_member_name_and_shared_subscription_names_need_the_budget_and_are_bounded() {
let group = vec![ev("g1", EventBody::BudgetCreated { budget: "b-home".into(), name: "Home".into(), limit: Haler(0) })];
let ok = |body: EventBody| {
let mut log = group.clone();
log.push(ev("x", body));
rejected(&log).is_empty()
};
let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert!(ok(EventBody::MemberNamed { budget: "b-home".into(), name: "Jana".into() }));
assert!(!ok(EventBody::MemberNamed { budget: "b-other".into(), name: "Jana".into() }));
assert!(!ok(EventBody::MemberNamed { budget: "b-home".into(), name: " ".into() }));
assert!(ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: names(&["spotify", "netflix"]) }));
assert!(ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: vec![] }), "an empty list withdraws them");
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-other".into(), names: names(&["spotify"]) }));
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: names(&["spotify", "spotify"]) }));
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: names(&[""]) }));
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: vec!["x".repeat(41)] }));
assert!(!ok(EventBody::SubscriptionsShared { budget: "b-home".into(), names: (0..101).map(|i| format!("s{i}")).collect() }));
}
#[test]
fn the_new_events_round_trip_as_json_with_their_type_tags() {
for (body, tag) in [
(EventBody::ProfileNamed { name: "Mark".into() }, "profile.named"),
(EventBody::HouseholdSharingSet { budget: "b".into(), on: true }, "household.sharing_set"),
(EventBody::MemberNamed { budget: "b".into(), name: "Mark".into() }, "member.named"),
(EventBody::SubscriptionsShared { budget: "b".into(), names: vec!["spotify".into()] }, "subscriptions.shared"),
] {
let json = serde_json::to_value(&body).unwrap();
assert_eq!(json["type"], tag);
assert_eq!(serde_json::from_value::<EventBody>(json).unwrap(), body);
}
}
+365
View File
@@ -0,0 +1,365 @@
//! Invoices (v1.1): the totals to the haléř with and without VAT, the number that is the variable symbol, a paid
//! invoice found on a statement and landing in its budget with the reserve set aside, and everything hostile or
//! inconsistent refused.
use fiscus_ledger::import::StatementLine;
use fiscus_ledger::invoice::{dic_ok, ico_ok, invoice_number, line_amount, plan_invoice_payments, same_vs, totals, Invoice, InvoiceError, InvoiceLine, Language, Party, Supplier};
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
struct Ids(u64);
impl Ids {
fn next(&mut self) -> String {
self.0 += 1;
format!("id{:04}", self.0)
}
}
fn ev(ids: &mut Ids, body: EventBody) -> Event {
Event::new(ids.next(), Timestamp(0), body)
}
fn party(name: &str) -> Party {
Party { name: name.into(), address: vec!["Dlouhá 1".into(), "110 00 Praha 1".into()], ico: Some("45244782".into()), dic: None }
}
fn supplier(vat_payer: bool, reserve_permille: u16) -> Supplier {
let mut p = party("Marek Novák");
p.ico = Some("27074358".into());
p.dic = vat_payer.then(|| "CZ8001011234".into());
Supplier { party: p, vat_payer, reserve_permille, registration: Some("Fyzická osoba zapsaná v živnostenském rejstříku.".into()) }
}
fn line(text: &str, quantity: i64, price: i64, vat: Option<u8>) -> InvoiceLine {
InvoiceLine { text: text.into(), quantity, unit: "h".into(), unit_price: Haler(price), vat }
}
fn invoice(id: &str, number: &str, issued: &str, lines: Vec<InvoiceLine>, vat: bool) -> Invoice {
Invoice {
id: id.into(),
number: number.into(),
issued: d(issued),
due: d(issued).add_days(14),
taxable: vat.then(|| d(issued)),
customer: party("Odběratel s.r.o."),
lines,
budget: None,
language: Language::Cs,
}
}
fn imported(ids: &mut Ids, amount: i64, booked: &str, vs: Option<&str>) -> (Event, String) {
let payment = ids.next();
let line = StatementLine {
bank: "test".into(),
account: "1".into(),
booked: d(booked),
amount: Haler(amount),
merchant: "Odběratel s.r.o.".into(),
counterparty: Some("123/0100".into()),
variable_symbol: vs.map(Into::into),
message: None,
bank_ref: Some(payment.clone()),
};
(ev(ids, EventBody::PaymentImported { payment: payment.clone(), line, line_key: format!("test|1|{payment}") }), payment)
}
fn apply(state: &mut State, events: &[Event]) {
for e in events {
state.apply(e);
}
}
#[test]
fn ico_and_dic_are_checked() {
assert!(ico_ok("45244782")); // Česká spořitelna
assert!(ico_ok("27074358"));
assert!(!ico_ok("45244783"));
assert!(!ico_ok("4524478"));
assert!(!ico_ok("4524478a"));
assert!(dic_ok("CZ45244782") && dic_ok("CZ8001011234"));
assert!(!dic_ok("SK45244782") && !dic_ok("CZ1234567") && !dic_ok("CZ1234567890123"));
}
#[test]
fn an_invoice_without_vat_adds_up_to_the_haler() {
let t = totals(&[line("Konzultace", 1_500, 120_000, None), line("Licence", 3_000, 33_333, None)], false).unwrap();
assert_eq!(t.lines, vec![Haler(180_000), Haler(99_999)]);
assert_eq!((t.net, t.vat, t.total), (Haler(279_999), Haler(0), Haler(279_999)));
assert!(t.rates.is_empty());
// 0,333 h at 1 000 Kč is 333,00; at 1 000,05 Kč 333,016… → 333,02. Rounded half away from zero.
assert_eq!(line_amount(333, Haler(100_000)).unwrap(), Haler(33_300));
assert_eq!(line_amount(333, Haler(100_005)).unwrap(), Haler(33_302));
assert_eq!(line_amount(1, Haler(50)).unwrap(), Haler(0), "0,0005 Kč is nothing");
assert_eq!(line_amount(500, Haler(1)).unwrap(), Haler(1), "0,005 Kč rounds up to 0,01");
}
#[test]
fn a_vat_invoice_computes_vat_once_per_rate_from_its_base() {
let t = totals(&[line("Vývoj", 10_000, 100_000, Some(21)), line("Kniha", 1_000, 100_000, Some(12)), line("Vývoj", 1_000, 3, Some(21)), line("Pojištění", 1_000, 5_000, Some(0))], true).unwrap();
// 21 %: base 10 000,03 → VAT 2 100,0063 → 2 100,01; 12 %: 1 000 → 120; 0 %: 50 → 0.
assert_eq!(t.rates, vec![(21, Haler(1_000_003), Haler(210_001)), (12, Haler(100_000), Haler(12_000)), (0, Haler(5_000), Haler(0))]);
assert_eq!((t.net, t.vat, t.total), (Haler(1_105_003), Haler(222_001), Haler(1_327_004)));
// Per rate, not per line: three lines of 0,05 at 21 % are 0,15 → 0,03 VAT (per line it would be 3 × 0,01).
let t = totals(&[line("a", 1_000, 5, Some(21)), line("b", 1_000, 5, Some(21)), line("c", 1_000, 5, Some(21))], true).unwrap();
assert_eq!(t.vat, Haler(3));
}
#[test]
fn bad_lines_are_refused() {
let ok = line("Práce", 1_000, 100_000, None);
assert_eq!(totals(&[], false), Err(InvoiceError::Lines));
assert_eq!(totals(&vec![ok.clone(); 51], false), Err(InvoiceError::Lines));
assert_eq!(totals(&[line("Práce", 0, 100, None)], false), Err(InvoiceError::Quantity));
assert_eq!(totals(&[line("Práce", 1_000, 0, None)], false), Err(InvoiceError::Price));
assert_eq!(totals(&[line("Práce", 1_000, -100, None)], false), Err(InvoiceError::Price));
assert_eq!(totals(&[line("", 1_000, 100, None)], false), Err(InvoiceError::LineText));
assert_eq!(totals(&[line("A\u{0}B", 1_000, 100, None)], false), Err(InvoiceError::LineText));
assert_eq!(totals(&[line("Práce", 1_000, 100, Some(21))], false), Err(InvoiceError::RateUse), "a rate without being a VAT payer");
assert_eq!(totals(&[line("Práce", 1_000, 100, None)], true), Err(InvoiceError::RateUse), "a VAT invoice line without a rate");
assert_eq!(totals(&[line("Práce", 1_000, 100, Some(15))], true), Err(InvoiceError::Rate));
// Over what QR Platba and a statement can carry.
assert_eq!(totals(&[line("Práce", 1_000_000_000, 999_999_999, None)], false), Err(InvoiceError::Total));
assert_eq!(totals(&[line("Práce", 2_000, 999_999_999, None)], false), Err(InvoiceError::Total));
}
#[test]
fn numbers_are_the_year_and_a_sequence_and_the_variable_symbol() {
assert_eq!(invoice_number(2026, 1).unwrap(), "20260001");
assert_eq!(invoice_number(2026, 0), Err(InvoiceError::Number));
assert_eq!(invoice_number(2026, 10_000), Err(InvoiceError::Number));
assert!(same_vs("0020260001", "20260001") && same_vs(" 20260001 ", "20260001"));
assert!(!same_vs("20260002", "20260001") && !same_vs("", "") && !same_vs("000", "0"));
let mut ids = Ids(0);
let mut s = State::default();
assert_eq!(s.next_invoice_number(2026).as_deref(), Some("20260001"));
let events = [
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i2", "20260002", "2026-04-01", vec![line("Práce", 1_000, 100_000, None)], false) }),
];
apply(&mut s, &events);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
assert_eq!(s.next_invoice_number(2026).as_deref(), Some("20260003"));
assert_eq!(s.next_invoice_number(2027).as_deref(), Some("20270001"), "each year starts again");
}
#[test]
fn an_invoice_that_does_not_fit_is_rejected_and_changes_nothing() {
let mut ids = Ids(0);
let mut s = State::default();
let good = || invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false);
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: good() })]);
assert_eq!(s.rejected.len(), 1, "no supplier yet");
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) })]);
let mut cases: Vec<Invoice> = Vec::new();
let mut i = good();
i.number = "20250001".into(); // not this year's
cases.push(i);
let mut i = good();
i.number = "20260000".into();
cases.push(i);
let mut i = good();
i.number = "2026001".into();
cases.push(i);
let mut i = good();
i.due = d("2026-02-28");
cases.push(i);
let mut i = good();
i.taxable = Some(d("2026-03-01")); // a DUZP without being a VAT payer
cases.push(i);
let mut i = good();
i.customer.ico = Some("12345678".into());
cases.push(i);
let mut i = good();
i.customer.name = "X\u{7}".into();
cases.push(i);
let mut i = good();
i.customer.address = vec![];
cases.push(i);
let mut i = good();
i.budget = Some("no-such".into());
cases.push(i);
let before = s.rejected.len();
for c in cases.iter().cloned() {
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: c })]);
}
assert_eq!(s.rejected.len() - before, cases.len());
assert!(s.invoices.is_empty() && s.invoice_numbers.is_empty());
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: good() })]);
let mut again = good();
again.id = "i2".into();
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceIssued { invoice: again })]);
assert_eq!(s.invoices.len(), 1, "a number is used once");
// A VAT payer without a DIČ, a reserve over 60 %.
let mut no_dic = supplier(true, 150);
no_dic.party.dic = None;
let before = s.rejected.len();
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: no_dic }), ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 601) })]);
assert_eq!(s.rejected.len() - before, 2);
assert_eq!(s.supplier, Some(supplier(false, 150)));
}
#[test]
fn a_paid_invoice_lands_in_its_budget_with_the_reserve_set_aside_untouched() {
let mut ids = Ids(0);
let mut s = State::default();
let mut inv = invoice("i1", "20260001", "2026-03-01", vec![line("Konzultace", 10_000, 150_000, None)], false);
inv.budget = Some("home".into());
apply(
&mut s,
&[
ev(&mut ids, EventBody::BudgetCreated { budget: "home".into(), name: "Home".into(), limit: Haler(3_000_000) }),
ev(&mut ids, EventBody::AccountSet { iban: "CZ6508000000192000145399".into(), name: "Marek Novak".into() }),
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: inv }),
],
);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
assert_eq!(s.invoices["i1"].totals.total, Haler(1_500_000));
let qr = s.invoice_spayd("i1").unwrap();
assert!(qr.contains("*AM:15000.00*") && qr.contains("*X-VS:20260001") && qr.contains("*MSG:Faktura 20260001"), "{qr}");
// The statement brings three lines: the wrong amount, no symbol, and the payment (the bank pads the symbol).
let (wrong, _) = imported(&mut ids, 1_400_000, "2026-03-10", Some("20260001"));
let (nosym, _) = imported(&mut ids, 1_500_000, "2026-03-11", None);
let (right, paid_by) = imported(&mut ids, 1_500_000, "2026-03-12", Some("0020260001"));
apply(&mut s, &[wrong, nosym, right]);
let plan = plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0));
let kinds: Vec<String> = plan.iter().map(|e| format!("{:?}", e.body).split_whitespace().next().unwrap().to_string()).collect();
assert_eq!(kinds, vec!["InvoicePaid", "PaymentCategorised", "PaymentAssigned"]);
apply(&mut s, &plan);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
let paid = s.invoices["i1"].paid.clone().unwrap();
assert_eq!((paid.payment.as_deref(), paid.on), (Some(paid_by.as_str()), d("2026-03-12")));
assert_eq!(paid.reserve, Haler(225_000), "15 % of 15 000 Kč");
assert_eq!(s.reserve_balance(), Haler(225_000));
let p = s.effective_payment(&paid_by).unwrap();
assert_eq!((p.category.as_deref(), p.budget.as_deref()), (Some("income"), Some("home")));
assert_eq!(s.invoice_spayd("i1"), None, "no QR for a paid invoice");
// Planning again finds nothing: paid once.
assert!(plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0)).is_empty());
// The reserve pays the tax: no more than it holds.
let before = s.rejected.len();
apply(&mut s, &[ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w1".into(), amount: Haler(225_001), on: d("2027-03-31"), note: "Daň z příjmů".into() })]);
assert_eq!(s.rejected.len() - before, 1);
apply(&mut s, &[ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w1".into(), amount: Haler(200_000), on: d("2027-03-31"), note: "Daň z příjmů".into() })]);
assert_eq!(s.reserve_balance(), Haler(25_000), "{:?}", s.rejected);
}
#[test]
fn a_vat_payer_sets_aside_all_the_vat_and_the_share_of_the_rest() {
let mut ids = Ids(0);
let mut s = State::default();
apply(
&mut s,
&[
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 100) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Vývoj", 10_000, 100_000, Some(21))], true) }),
],
);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
assert_eq!(s.invoices["i1"].totals.total, Haler(1_210_000));
apply(&mut s, &[ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-05") })]);
// VAT 2 100 Kč, and 10 % of 10 000 Kč.
assert_eq!(s.reserve_balance(), Haler(310_000));
// A later change of the supplier does not change an invoice issued before it.
apply(&mut s, &[ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 300) })]);
assert_eq!(s.invoices["i1"].supplier.reserve_permille, 100);
}
#[test]
fn a_payment_pays_one_invoice_once_and_only_its_own_amount() {
let mut ids = Ids(0);
let mut s = State::default();
let one = |id: &str, n: &str| invoice(id, n, "2026-03-01", vec![line("Práce", 1_000, 100_000, None)], false);
apply(
&mut s,
&[
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(false, 150) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i1", "20260001") }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i2", "20260002") }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: one("i3", "20260003") }),
],
);
let (line_event, line) = imported(&mut ids, 100_000, "2026-03-02", Some("20260001"));
let (small, small_id) = imported(&mut ids, 99_999, "2026-03-02", Some("20260002"));
let (early, _) = imported(&mut ids, 100_000, "2026-02-27", Some("20260003"));
apply(&mut s, &[line_event, small, early]);
let before = s.rejected.len();
apply(
&mut s,
&[
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: Some(small_id), on: d("2026-03-02") }), // wrong amount
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: Some("no-such".into()), on: d("2026-03-02") }),
ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: None, on: d("2026-02-01") }), // before it was issued
ev(&mut ids, EventBody::InvoicePaid { invoice: "nope".into(), payment: None, on: d("2026-03-02") }),
],
);
assert_eq!(s.rejected.len() - before, 4);
// The early line (before the invoice was issued) pays nothing; the right one pays i1 only.
let plan = plan_invoice_payments(&s, &mut || ids.next(), Timestamp(0));
let paid: Vec<String> = plan.iter().filter_map(|e| match &e.body { EventBody::InvoicePaid { invoice, .. } => Some(invoice.clone()), _ => None }).collect();
assert_eq!(paid, vec!["i1"]);
apply(&mut s, &plan);
let before = s.rejected.len();
apply(
&mut s,
&[
ev(&mut ids, EventBody::InvoicePaid { invoice: "i3".into(), payment: Some(line.clone()), on: d("2026-03-02") }), // used by i1
ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-02") }), // paid already
ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i1".into() }), // paid: cannot be cancelled
],
);
assert_eq!(s.rejected.len() - before, 3);
apply(&mut s, &[ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i2".into() })]);
assert!(s.invoices["i2"].cancelled);
let before = s.rejected.len();
apply(&mut s, &[ev(&mut ids, EventBody::InvoicePaid { invoice: "i2".into(), payment: None, on: d("2026-03-03") })]);
assert_eq!(s.rejected.len() - before, 1, "a cancelled invoice is not paid");
}
#[test]
fn the_events_round_trip_and_keep_their_names() {
let mut ids = Ids(0);
let events = vec![
ev(&mut ids, EventBody::SupplierSet { supplier: supplier(true, 150) }),
ev(&mut ids, EventBody::InvoiceIssued { invoice: invoice("i1", "20260001", "2026-03-01", vec![line("Práce", 1_000, 100_000, Some(21))], true) }),
ev(&mut ids, EventBody::InvoicePaid { invoice: "i1".into(), payment: None, on: d("2026-03-05") }),
ev(&mut ids, EventBody::InvoiceCancelled { invoice: "i1".into() }),
ev(&mut ids, EventBody::ReserveWithdrawn { withdrawal: "w".into(), amount: Haler(1), on: d("2026-03-05"), note: String::new() }),
];
let json = serde_json::to_string(&events).unwrap();
for name in ["supplier.set", "invoice.issued", "invoice.paid", "invoice.cancelled", "reserve.withdrawn"] {
assert!(json.contains(&format!("\"type\":\"{name}\"")), "{name}");
}
let back: Vec<Event> = serde_json::from_str(&json).unwrap();
assert_eq!(back, events);
// Replaying the log twice gives the same state.
assert_eq!(State::replay(&events), State::replay(&back));
}
#[test]
fn an_invoice_is_printed_in_czech_or_english_and_czech_when_unsaid() {
let mut i = invoice("i1", "20260001", "2026-03-01", vec![line("Work", 1_000, 100_000, None)], false);
i.language = Language::En;
let json = serde_json::to_string(&i).unwrap();
assert!(json.contains("\"language\":\"en\""), "{json}");
assert_eq!(serde_json::from_str::<Invoice>(&json).unwrap(), i);
// An event written without the field reads as Czech.
let older = json.replace(",\"language\":\"en\"", "");
assert!(!older.contains("language"));
assert_eq!(serde_json::from_str::<Invoice>(&older).unwrap().language, Language::Cs);
// Anything else is refused.
assert!(serde_json::from_str::<Invoice>(&json.replace("\"en\"", "\"de\"")).is_err());
}
+222
View File
@@ -0,0 +1,222 @@
//! Mandatory test 3: matching captures to statement lines is one to one, a statement imported twice adds
//! nothing, and everything left over is reported on both sides.
use fiscus_ledger::import::{plan_import, StatementLine};
use fiscus_ledger::matching::find_matches;
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
use proptest::prelude::*;
fn d(s: &str) -> Date {
s.parse().unwrap()
}
struct Ids(u64);
impl Ids {
fn next(&mut self) -> String {
self.0 += 1;
format!("id{:04}", self.0)
}
}
fn captured(ids: &mut Ids, amount: i64, date: &str, merchant: &str) -> Event {
Event::new(
ids.next(),
Timestamp(0),
EventBody::PaymentCaptured {
payment: ids.next(),
amount: Haler(amount),
date: d(date),
merchant: merchant.into(),
card: None,
},
)
}
fn line(amount: i64, date: &str, merchant: &str) -> StatementLine {
StatementLine {
bank: "test".into(),
account: "123/0000".into(),
booked: d(date),
amount: Haler(amount),
merchant: merchant.into(),
counterparty: None,
variable_symbol: None,
message: None,
bank_ref: None,
}
}
fn payment_of(e: &Event) -> String {
match &e.body {
EventBody::PaymentCaptured { payment, .. } | EventBody::PaymentImported { payment, .. } => payment.clone(),
_ => unreachable!(),
}
}
fn import(state: &mut State, ids: &mut Ids, lines: &[StatementLine]) -> fiscus_ledger::import::ImportPlan {
let plan = plan_import(state, lines, &mut || ids.next(), Timestamp(1));
for e in plan.events.iter().chain(&plan.confirmations) {
state.apply(e);
}
plan
}
#[test]
fn a_capture_and_its_line_match() {
let mut ids = Ids(0);
let mut state = State::default();
let c = captured(&mut ids, -12_900, "2026-10-02", "ALBERT 1234 PRAHA");
state.apply(&c);
let plan = import(&mut state, &mut ids, &[line(-12_900, "2026-10-03", "Albert Praha")]);
assert_eq!(plan.events.len(), 1);
assert_eq!(plan.report.pairs.len(), 1);
assert_eq!(plan.report.pairs[0].0, payment_of(&c));
assert!(plan.report.unmatched_captured.is_empty() && plan.report.unmatched_lines.is_empty());
// Once confirmed, they are one payment and nothing is left to match.
assert_eq!(state.effective_payments().len(), 1);
let after = find_matches(&state);
assert!(after.pairs.is_empty() && after.unmatched_captured.is_empty() && after.unmatched_lines.is_empty());
}
#[test]
fn one_capture_never_matches_two_lines() {
let mut ids = Ids(0);
let mut state = State::default();
let c = captured(&mut ids, -5_000, "2026-10-02", "Kavarna Dobra");
state.apply(&c);
let twins = [line(-5_000, "2026-10-03", "KAVARNA DOBRA"), line(-5_000, "2026-10-03", "KAVARNA DOBRA")];
let plan = import(&mut state, &mut ids, &twins);
// Two identical lines are two lines (two coffees), and the capture cannot pick one by itself.
assert_eq!(plan.events.len(), 2);
assert!(plan.report.pairs.is_empty());
assert_eq!(plan.report.ambiguous.len(), 1);
assert_eq!(plan.report.ambiguous[0].candidates.len(), 2);
assert_eq!(plan.report.unmatched_captured, vec![payment_of(&c)]);
assert_eq!(plan.report.unmatched_lines.len(), 2);
}
#[test]
fn a_second_confirmation_of_the_same_capture_is_rejected() {
let mut ids = Ids(0);
let mut state = State::default();
let c = captured(&mut ids, -5_000, "2026-10-02", "Kavarna");
state.apply(&c);
let plan = import(&mut state, &mut ids, &[line(-5_000, "2026-10-02", "Kavarna"), line(-5_000, "2026-10-04", "Kavarna")]);
assert_eq!(plan.report.pairs.len(), 1, "the line on the same day wins over the one two days later");
let second_line = payment_of(&plan.events[1]);
let again = Event::new(ids.next(), Timestamp(2), EventBody::PaymentConfirmed { payment: payment_of(&c), line: second_line });
let before = serde_json::to_string(&state.effective_payments()).unwrap();
state.apply(&again);
assert_eq!(serde_json::to_string(&state.effective_payments()).unwrap(), before);
assert_eq!(state.rejected.len(), 1);
}
#[test]
fn the_same_statement_imported_twice_adds_nothing() {
let mut ids = Ids(0);
let mut state = State::default();
let lines = [
line(-12_900, "2026-10-03", "Albert"),
line(-12_900, "2026-10-03", "Albert"),
line(-49_900, "2026-10-05", "Spotify"),
line(3_500_000, "2026-10-10", "Salary"),
];
let first = import(&mut state, &mut ids, &lines);
assert_eq!(first.events.len(), 4);
let snapshot = serde_json::to_vec(&state).unwrap();
let second = import(&mut state, &mut ids, &lines);
assert!(second.events.is_empty() && second.confirmations.is_empty());
assert_eq!(second.duplicates, 4);
assert_eq!(serde_json::to_vec(&state).unwrap(), snapshot);
// An overlapping statement adds only its new lines.
let mut overlap = lines.to_vec();
overlap.push(line(-9_900, "2026-10-12", "Netflix"));
let third = import(&mut state, &mut ids, &overlap);
assert_eq!((third.events.len(), third.duplicates), (1, 4));
}
#[test]
fn unmatched_items_are_reported_on_both_sides() {
let mut ids = Ids(0);
let mut state = State::default();
let c1 = captured(&mut ids, -12_900, "2026-10-02", "Albert");
let c2 = captured(&mut ids, -7_000, "2026-10-02", "Rohlik"); // never on the statement
state.apply(&c1);
state.apply(&c2);
let plan = import(
&mut state,
&mut ids,
&[
line(-12_900, "2026-10-03", "Albert"),
line(-7_001, "2026-10-03", "Rohlik"), // one haléř off: not the same payment
line(-7_000, "2026-10-20", "Rohlik"), // too late
line(-3_000, "2026-10-03", "Benzina"), // nothing captured
],
);
assert_eq!(plan.report.pairs, vec![(payment_of(&c1), payment_of(&plan.events[0]))]);
assert_eq!(plan.report.unmatched_captured, vec![payment_of(&c2)]);
assert_eq!(plan.report.unmatched_lines.len(), 3);
}
#[test]
fn a_hand_added_payment_without_merchant_is_only_proposed() {
let mut ids = Ids(0);
let mut state = State::default();
let added = Event::new(
ids.next(),
Timestamp(0),
EventBody::PaymentAdded {
payment: ids.next(),
amount: Haler(-25_000),
date: d("2026-10-02"),
merchant: String::new(),
category: Some("groceries".into()),
note: None,
},
);
state.apply(&added);
let plan = import(&mut state, &mut ids, &[line(-25_000, "2026-10-02", "Lidl")]);
assert!(plan.report.pairs.is_empty());
assert_eq!(plan.report.ambiguous.len(), 1);
}
proptest! {
#[test]
fn matching_is_always_one_to_one_and_complete(
caps in prop::collection::vec((0i64..4, 0i32..10, 0usize..3), 0..12),
lines in prop::collection::vec((0i64..4, 0i32..10, 0usize..3), 0..12),
) {
let merchants = ["Albert", "Lidl", "Spotify"];
let base = d("2026-10-01");
let mut ids = Ids(0);
let mut state = State::default();
for (a, day, m) in &caps {
let e = Event::new(ids.next(), Timestamp(0), EventBody::PaymentCaptured {
payment: ids.next(), amount: Haler(-(a + 1) * 1000), date: base.add_days(*day),
merchant: merchants[*m].into(), card: None,
});
state.apply(&e);
}
let lines: Vec<_> = lines.iter().map(|(a, day, m)| StatementLine {
booked: base.add_days(*day), amount: Haler(-(a + 1) * 1000), merchant: merchants[*m].into(),
..line(0, "2026-10-01", "")
}).collect();
let plan = import(&mut state, &mut ids, &lines);
let r = &plan.report;
let mut seen_c = std::collections::BTreeSet::new();
let mut seen_l = std::collections::BTreeSet::new();
for (c, l) in &r.pairs {
prop_assert!(seen_c.insert(c.clone()), "capture matched twice");
prop_assert!(seen_l.insert(l.clone()), "line matched twice");
}
prop_assert_eq!(seen_c.len() + r.unmatched_captured.len(), caps.len());
prop_assert_eq!(seen_l.len() + r.unmatched_lines.len(), lines.len());
prop_assert!(state.rejected.is_empty());
// Applying the plan leaves every capture in at most one pair and the totals unchanged.
let total_lines: i64 = lines.iter().map(|l| l.amount.0).sum();
let total_unmatched_caps: i64 = state.effective_payments().iter()
.filter(|p| p.line.is_none()).map(|p| p.amount.0).sum();
let total: i64 = state.effective_payments().iter().map(|p| p.amount.0).sum();
prop_assert_eq!(total, total_lines + total_unmatched_caps);
}
}
+97
View File
@@ -0,0 +1,97 @@
//! Mandatory test 1: money never loses or creates a haléř.
use fiscus_ledger::money::{split, Haler, MoneyError};
use proptest::prelude::*;
const BIG: i64 = 1_000_000_000_000; // ten billion CZK in haléře: far beyond any household
proptest! {
#[test]
fn split_shares_sum_to_the_total(total in -BIG..BIG, weights in prop::collection::vec(0u64..10_000, 1..12)) {
prop_assume!(weights.iter().any(|w| *w > 0));
let shares = split(Haler(total), &weights).unwrap();
prop_assert_eq!(shares.len(), weights.len());
prop_assert_eq!(Haler::sum(shares.iter().copied()).unwrap(), Haler(total));
}
#[test]
fn a_zero_weight_gets_nothing(total in -BIG..BIG, n in 1usize..8) {
let mut weights = vec![1u64; n];
weights.push(0);
let shares = split(Haler(total), &weights).unwrap();
prop_assert_eq!(*shares.last().unwrap(), Haler(0));
}
#[test]
fn shares_differ_by_at_most_one_haler_for_equal_weights(total in -BIG..BIG, n in 1usize..12) {
let shares = split(Haler(total), &vec![1u64; n]).unwrap();
let min = shares.iter().map(|h| h.0).min().unwrap();
let max = shares.iter().map(|h| h.0).max().unwrap();
prop_assert!(max - min <= 1);
}
#[test]
fn the_remainder_rule_is_deterministic(total in -BIG..BIG, weights in prop::collection::vec(1u64..100, 1..8)) {
prop_assert_eq!(split(Haler(total), &weights).unwrap(), split(Haler(total), &weights).unwrap());
}
#[test]
fn a_payment_and_its_refund_cancel_out(amount in 1i64..BIG, refunds in prop::collection::vec(1u64..100, 1..5)) {
// A refund split into parts: the parts plus the payment come back to zero exactly.
let parts = split(Haler(amount), &refunds).unwrap();
let mut all = vec![Haler(-amount)];
all.extend(parts);
prop_assert_eq!(Haler::sum(all).unwrap(), Haler(0));
}
#[test]
fn sums_are_order_independent(mut xs in prop::collection::vec(-BIG..BIG, 0..50)) {
let a = Haler::sum(xs.iter().copied().map(Haler)).unwrap();
xs.reverse();
let b = Haler::sum(xs.iter().copied().map(Haler)).unwrap();
prop_assert_eq!(a, b);
}
#[test]
fn czk_text_round_trips(h in -BIG..BIG) {
let text = Haler(h).to_czk();
prop_assert_eq!(Haler::parse_czk(&text).unwrap(), Haler(h));
}
}
#[test]
fn overflow_is_an_error_never_a_wrap() {
assert_eq!(Haler(i64::MAX).checked_add(Haler(1)), Err(MoneyError::Overflow));
assert_eq!(Haler(i64::MIN).checked_sub(Haler(1)), Err(MoneyError::Overflow));
assert_eq!(Haler(i64::MIN).checked_neg(), Err(MoneyError::Overflow));
assert_eq!(Haler::sum([Haler(i64::MAX), Haler(1)]), Err(MoneyError::Overflow));
}
#[test]
fn split_rejects_no_weight() {
assert_eq!(split(Haler(100), &[]), Err(MoneyError::NoWeight));
assert_eq!(split(Haler(100), &[0, 0]), Err(MoneyError::NoWeight));
}
#[test]
fn split_known_cases() {
// 100,00 Kč in three: the first share takes the leftover haléř.
assert_eq!(split(Haler(10_000), &[1, 1, 1]).unwrap(), vec![Haler(3_334), Haler(3_333), Haler(3_333)]);
// A refund (negative) splits the same way, mirrored.
assert_eq!(split(Haler(-10_000), &[1, 1, 1]).unwrap(), vec![Haler(-3_334), Haler(-3_333), Haler(-3_333)]);
// Weighted 2:1.
assert_eq!(split(Haler(1_000), &[2, 1]).unwrap(), vec![Haler(667), Haler(333)]);
}
#[test]
fn czk_text() {
assert_eq!(Haler(-123_450).to_czk(), "-1 234,50");
assert_eq!(Haler(5).to_czk(), "0,05");
assert_eq!(Haler(100_000_000).to_czk(), "1 000 000,00");
assert_eq!(Haler::parse_czk("1234,5").unwrap(), Haler(123_450));
assert_eq!(Haler::parse_czk("12").unwrap(), Haler(1_200));
assert_eq!(Haler::parse_czk("-0,01").unwrap(), Haler(-1));
for bad in ["", "-", "1,234", "1.5.2", "abc", "1,", ",5", "1e3", "١٢", "99999999999999999999"] {
assert!(Haler::parse_czk(bad).is_err(), "{bad:?} must be refused");
}
}
+40
View File
@@ -0,0 +1,40 @@
//! Mandatory test 1 (b): no floating-point type appears anywhere in the core. Money, dates, matching,
//! subscriptions and the forecast are all integers, so the whole workspace is scanned.
use std::path::{Path, PathBuf};
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
if path.file_name().is_some_and(|n| n == "target") {
continue;
}
rust_files(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
#[test]
fn no_float_type_in_any_source_file() {
let crates = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap();
let mut files = Vec::new();
rust_files(crates, &mut files);
assert!(files.len() > 10, "the scan found too few files: {}", files.len());
// Spelled apart so this file does not match itself.
let banned = [concat!("f", "32"), concat!("f", "64")];
let mut hits = Vec::new();
for file in &files {
let text = std::fs::read_to_string(file).unwrap();
for (n, line) in text.lines().enumerate() {
let words = line.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
if words.into_iter().any(|w| banned.contains(&w)) {
hits.push(format!("{}:{}: {}", file.display(), n + 1, line.trim()));
}
}
}
assert!(hits.is_empty(), "floating point in the core:\n{}", hits.join("\n"));
}
+99
View File
@@ -0,0 +1,99 @@
//! Day-2 mandatory test: QR Platba. Generated SPAYD strings match the format, and only valid Czech accounts
//! get one.
use fiscus_ledger::pay::{spayd, Iban, PayError};
use fiscus_ledger::Haler;
const IBAN: &str = "CZ6508000000192000145399";
#[test]
fn an_iban_is_checked_by_mod_97() {
assert_eq!(Iban::parse(IBAN).unwrap().as_str(), IBAN);
assert_eq!(Iban::parse("cz65 0800 0000 1920 0014 5399").unwrap().as_str(), IBAN);
for bad in [
"CZ6608000000192000145399", // check digits
"CZ650800000019200014539", // too short
"CZ65080000001920001453991", // too long
"SK3112000000198742637541", // valid, but not Czech
"CZ65 0800 0000 1920 0014 539X",
"",
] {
assert!(Iban::parse(bad).is_err(), "{bad}");
}
}
#[test]
fn a_czech_account_number_becomes_its_iban() {
assert_eq!(Iban::parse("19-2000145399/0800").unwrap().as_str(), IBAN);
assert_eq!(Iban::parse("2000145399/0800").unwrap().as_str(), "CZ7908000000002000145399");
for bad in [
"19-2000145398/0800", // the number's mod 11
"18-2000145399/0800", // the prefix's mod 11
"2000145399/080",
"2000145399",
"1234567-2000145399/0800",
] {
assert!(Iban::parse(bad).is_err(), "{bad}");
}
}
/// The SPAYD 1.0 grammar for what Fiscus writes: `SPD*1.0` then `KEY:value` pairs separated by `*`, values
/// without a raw `*`.
fn well_formed(s: &str) -> bool {
let mut parts = s.split('*');
if parts.next() != Some("SPD") || parts.next() != Some("1.0") {
return false;
}
let mut keys = Vec::new();
for p in parts {
let Some((k, v)) = p.split_once(':') else { return false };
if v.is_empty() || !k.bytes().all(|b| b.is_ascii_uppercase() || b == b'-') {
return false;
}
keys.push(k);
}
keys.first() == Some(&"ACC") && keys.contains(&"AM") && keys.contains(&"CC")
}
#[test]
fn spayd_strings_match_the_format() {
let iban = Iban::parse(IBAN).unwrap();
let s = spayd(&iban, Haler(45_000), Some("Marek"), "Pizza, 2.11.", Some("123")).unwrap();
assert_eq!(s, "SPD*1.0*ACC:CZ6508000000192000145399*AM:450.00*CC:CZK*RN:Marek*MSG:Pizza, 2.11.*X-VS:123");
assert!(well_formed(&s));
for amount in [1, 99, 100, 123_456, 999_999_999] {
let s = spayd(&iban, Haler(amount), None, "x", None).unwrap();
assert!(well_formed(&s), "{s}");
let am = s.split('*').find_map(|p| p.strip_prefix("AM:")).unwrap();
assert_eq!(am, format!("{}.{:02}", amount / 100, amount % 100));
}
}
#[test]
fn a_star_in_a_text_never_breaks_the_string_and_texts_are_cut_to_size() {
let iban = Iban::parse(IBAN).unwrap();
let s = spayd(&iban, Haler(100), Some("A*B"), "1*2", None).unwrap();
assert!(s.contains("RN:A%2AB") && s.contains("MSG:1%2A2"), "{s}");
assert!(well_formed(&s));
let long = "ž".repeat(100);
let s = spayd(&iban, Haler(100), Some(&long), &long, None).unwrap();
let msg = s.split('*').find_map(|p| p.strip_prefix("MSG:")).unwrap();
let rn = s.split('*').find_map(|p| p.strip_prefix("RN:")).unwrap();
assert_eq!((msg.chars().count(), rn.chars().count()), (60, 35));
// `%2A` is never cut in half.
let s = spayd(&iban, Haler(100), None, &"*".repeat(30), None).unwrap();
let msg = s.split('*').find_map(|p| p.strip_prefix("MSG:")).unwrap();
assert!(msg.len() <= 60 && msg.len() % 3 == 0, "{msg}");
}
#[test]
fn what_cannot_be_paid_is_an_error() {
let iban = Iban::parse(IBAN).unwrap();
assert_eq!(spayd(&iban, Haler(0), None, "x", None), Err(PayError::Amount));
assert_eq!(spayd(&iban, Haler(-100), None, "x", None), Err(PayError::Amount));
assert_eq!(spayd(&iban, Haler(1_000_000_000), None, "x", None), Err(PayError::Amount));
for vs in ["", "12345678901", "12a"] {
assert_eq!(spayd(&iban, Haler(100), None, "x", Some(vs)), Err(PayError::VariableSymbol), "{vs}");
}
assert_eq!(spayd(&iban, Haler(100), None, "a\nb", None), Err(PayError::Text));
}
+104
View File
@@ -0,0 +1,104 @@
//! Category plans and categories of your own: a plan carries forward until a later one replaces it, zero
//! removes it, and only a real spending category can have one. Every refusal changes nothing.
use fiscus_ledger::categories::MAX_PLAN;
use fiscus_ledger::{Date, Event, EventBody, Haler, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
fn plan(id: &str, category: &str, amount: i64, from: &str) -> Event {
Event::new(id, Timestamp(0), EventBody::CategoryPlanned { category: category.into(), amount: Haler(amount), from: d(from) })
}
fn created(id: &str, category: &str, label: &str) -> Event {
Event::new(id, Timestamp(0), EventBody::CategoryCreated { category: category.into(), label: label.into() })
}
#[test]
fn a_plan_carries_forward_until_a_later_one_replaces_it() {
let s = State::replay(&[plan("p1", "groceries", 800_000, "2026-09-01"), plan("p2", "groceries", 900_000, "2026-11-01"), plan("p3", "eating-out", 200_000, "2026-10-01")]);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
assert_eq!(s.plan_for("groceries", d("2026-08-31")), None, "not before its month");
assert_eq!(s.plan_for("groceries", d("2026-09-15")), Some(Haler(800_000)));
assert_eq!(s.plan_for("groceries", d("2026-10-31")), Some(Haler(800_000)), "carried forward");
assert_eq!(s.plan_for("groceries", d("2026-11-01")), Some(Haler(900_000)));
assert_eq!(s.plan_for("groceries", d("2027-06-10")), Some(Haler(900_000)));
assert_eq!(s.plan_for("eating-out", d("2026-09-30")), None);
assert_eq!(s.plan_for("transport", d("2026-11-01")), None);
}
#[test]
fn the_latest_plan_for_a_month_wins_and_zero_removes_it() {
// Written later for an earlier month: the plan from November still counts in November.
let s = State::replay(&[plan("p1", "groceries", 900_000, "2026-11-01"), plan("p2", "groceries", 700_000, "2026-10-01")]);
assert_eq!(s.plan_for("groceries", d("2026-11-20")), Some(Haler(900_000)));
assert_eq!(s.plan_for("groceries", d("2026-10-20")), Some(Haler(700_000)));
// Two for the same month: the later in the log.
let s = State::replay(&[plan("p1", "groceries", 900_000, "2026-11-01"), plan("p2", "groceries", 500_000, "2026-11-01")]);
assert_eq!(s.plan_for("groceries", d("2026-11-20")), Some(Haler(500_000)));
// Zero from December: no plan from then on.
let s = State::replay(&[plan("p1", "groceries", 900_000, "2026-11-01"), plan("p2", "groceries", 0, "2026-12-01")]);
assert_eq!(s.plan_for("groceries", d("2026-11-30")), Some(Haler(900_000)));
assert_eq!(s.plan_for("groceries", d("2026-12-01")), None);
}
#[test]
fn only_a_spending_category_can_have_a_plan() {
for (category, amount, from, why) in [
("income", 100, "2026-11-01", "money in"),
("transfers", 100, "2026-11-01", "money moved"),
("uncategorised", 100, "2026-11-01", "not sorted"),
("fuel", 100, "2026-11-01", "an unknown category"),
("Groceries", 100, "2026-11-01", "not an id"),
("groceries", -1, "2026-11-01", "negative"),
("groceries", MAX_PLAN.0 + 1, "2026-11-01", "over 100 million"),
("groceries", 100, "2026-11-02", "not the 1st"),
] {
let s = State::replay(&[plan("p", category, amount, from)]);
assert_eq!(s.rejected.len(), 1, "{why}");
assert!(s.category_plans.is_empty(), "{why}: nothing kept");
}
let s = State::replay(&[plan("p", "groceries", MAX_PLAN.0, "2026-11-01")]);
assert!(s.rejected.is_empty(), "exactly 100 million is a plan");
}
#[test]
fn categories_of_your_own() {
let s = State::replay(&[created("c1", "fuel", "Fuel"), plan("p1", "fuel", 300_000, "2026-11-01")]);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
assert_eq!(s.category_label("fuel"), "Fuel");
assert_eq!(s.category_label("groceries"), "Groceries");
assert_eq!(s.plan_for("fuel", d("2026-11-03")), Some(Haler(300_000)));
let all = s.categories();
assert_eq!(all.last().unwrap(), &("fuel".to_string(), "Fuel".to_string()), "yours after the default ones");
assert_eq!(all[0].0, "groceries");
for (event, why) in [
(created("c2", "fuel", "Petrol"), "the same id twice"),
(created("c2", "groceries", "Food"), "a default category"),
(created("c2", "Fuel-2", "Fuel"), "not an id"),
(created("c2", "parking", ""), "an empty name"),
(created("c2", "parking", " Parking"), "a name with spaces around"),
(created("c2", "parking", &"x".repeat(41)), "a long name"),
(created("c2", "parking", "Park\ning"), "a control character"),
] {
let mut t = s.clone();
t.apply(&event);
assert_eq!(t.rejected.len(), 1, "{why}");
assert_eq!(t.custom_categories.len(), 1, "{why}: nothing kept");
}
}
#[test]
fn the_events_round_trip_and_replay_the_same() {
let log = vec![created("c1", "fuel", "Fuel"), plan("p1", "fuel", 300_000, "2026-11-01"), plan("p2", "groceries", 900_000, "2026-10-01")];
let json = serde_json::to_string(&log).unwrap();
for name in ["category.planned", "category.created"] {
assert!(json.contains(name), "{name}");
}
let back: Vec<Event> = serde_json::from_str(&json).unwrap();
assert_eq!(back, log);
assert_eq!(State::replay(&back), State::replay(&log));
}
+129
View File
@@ -0,0 +1,129 @@
//! Mandatory test 4: derived state is a pure function of the log. Delete it, rebuild it from the log, and
//! the bytes are identical, however it was built.
use fiscus_ledger::import::{plan_import, StatementLine};
use fiscus_ledger::{Date, Decision, Event, EventBody, Haler, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
/// A month of everything: captures, a statement, hand-added cash, fixes, rules, budgets, a trial, decisions,
/// and a few events that must be rejected.
fn sample_log() -> Vec<Event> {
let mut n = 0u64;
let mut id = || {
n += 1;
format!("e{n:04}")
};
let mut log = Vec::new();
let push = |log: &mut Vec<Event>, id: String, body: EventBody| {
let at = Timestamp(1_790_000_000_000 + log.len() as i64 * 1000);
log.push(Event::new(id, at, body));
};
push(&mut log, id(), EventBody::BudgetCreated { budget: "b-home".into(), name: "Home".into(), limit: Haler(2_000_000) });
push(&mut log, id(), EventBody::BudgetCreated { budget: "b-fun".into(), name: "Fun".into(), limit: Haler(300_000) });
push(&mut log, id(), EventBody::BudgetLimitSet { budget: "b-fun".into(), limit: Haler(350_000) });
push(
&mut log,
id(),
EventBody::PaymentCaptured { payment: "p-cap1".into(), amount: Haler(-12_900), date: d("2026-10-02"), merchant: "ALBERT 1234".into(), card: Some("Visa".into()) },
);
push(
&mut log,
id(),
EventBody::PaymentAdded { payment: "p-cash".into(), amount: Haler(-8_000), date: d("2026-10-04"), merchant: "Trh".into(), category: Some("groceries".into()), note: Some("market".into()) },
);
let lines: Vec<StatementLine> = [
(-12_900, "2026-10-03", "Albert"),
(-49_900, "2026-10-05", "PAYPAL *SPOTIFY"),
(-100, "2026-10-06", "NETFLIX.COM"),
(3_500_000, "2026-10-10", "Mzda"),
]
.iter()
.map(|(a, date, m)| StatementLine {
bank: "test".into(),
account: "1/0000".into(),
booked: d(date),
amount: Haler(*a),
merchant: (*m).into(),
counterparty: None,
variable_symbol: None,
message: None,
bank_ref: None,
})
.collect();
let mut state = State::replay(&log);
let mut k = 0u64;
let plan = plan_import(&state, &lines, &mut || {
k += 1;
format!("imp{k:03}")
}, Timestamp(1_790_000_100_000));
for e in plan.events.iter().chain(&plan.confirmations) {
state.apply(e);
log.push(e.clone());
}
push(&mut log, id(), EventBody::RuleCreated { rule: "r1".into(), merchant_key: "spotify".into(), category: "subscriptions".into() });
push(&mut log, id(), EventBody::PaymentCategorised { payment: "p-cap1".into(), category: "groceries".into() });
push(&mut log, id(), EventBody::PaymentAssigned { payment: "p-cash".into(), budget: "b-fun".into() });
push(&mut log, id(), EventBody::PaymentTrialMarked { payment: "imp003".into(), ends: d("2026-11-06") });
push(&mut log, id(), EventBody::SubscriptionDecided { subscription: "spotify".into(), decision: Decision::Keep, amount: Haler(49_900), on: d("2026-10-20") });
// To be rejected, deterministically.
push(&mut log, id(), EventBody::PaymentAssigned { payment: "p-nope".into(), budget: "b-fun".into() });
push(&mut log, id(), EventBody::BudgetCreated { budget: "b-fun".into(), name: "Again".into(), limit: Haler(1) });
push(&mut log, id(), EventBody::PaymentAdded { payment: "p-zero".into(), amount: Haler(0), date: d("2026-10-04"), merchant: "x".into(), category: None, note: None });
let dup = log[3].clone();
log.push(dup); // the same event twice (a sync replay)
log
}
#[test]
fn rebuild_from_the_log_is_byte_identical() {
let log = sample_log();
// 1. Built incrementally, saved, "deleted".
let mut live = State::default();
for e in &log {
live.apply(e);
}
let saved = serde_json::to_vec(&live).unwrap();
drop(live);
// 2. Rebuilt in one go from the log.
let rebuilt = State::replay(&log);
assert_eq!(serde_json::to_vec(&rebuilt).unwrap(), saved);
// 3. Rebuilt from the log after it went through its serialised form (what the app stores).
let stored = serde_json::to_vec(&log).unwrap();
let reloaded: Vec<Event> = serde_json::from_slice(&stored).unwrap();
assert_eq!(serde_json::to_vec(&State::replay(&reloaded)).unwrap(), saved);
// 4. The derived views are byte-identical too.
assert_eq!(
serde_json::to_vec(&State::replay(&log).effective_payments()).unwrap(),
serde_json::to_vec(&rebuilt.effective_payments()).unwrap()
);
// The bad events were rejected, and the right ones.
assert_eq!(rebuilt.rejected.len(), 4, "{:#?}", rebuilt.rejected);
}
#[test]
fn the_state_says_what_the_log_says() {
let s = State::replay(&sample_log());
let pays = s.effective_payments();
// cap1 + its line are one; cash; spotify; netflix check; salary.
assert_eq!(pays.len(), 5);
let albert = pays.iter().find(|p| p.merchant_key == "albert").unwrap();
assert_eq!(albert.category.as_deref(), Some("groceries"));
assert!(albert.line.is_some() && albert.captured.is_some());
let spotify = pays.iter().find(|p| p.merchant_key == "spotify").unwrap();
assert_eq!(spotify.category.as_deref(), Some("subscriptions"), "the rule applies to earlier payments");
let cash = pays.iter().find(|p| p.id == "p-cash").unwrap();
assert_eq!(cash.budget.as_deref(), Some("b-fun"));
assert_eq!(spotify.budget.as_deref(), Some("b-home"), "the first budget is the default");
assert_eq!(s.budgets["b-fun"].limit, Haler(350_000));
// Money in = money on the statement + hand-added cash.
let total = Haler::sum(pays.iter().map(|p| p.amount)).unwrap();
assert_eq!(total, Haler(-12_900 - 49_900 - 100 + 3_500_000 - 8_000));
}
+142
View File
@@ -0,0 +1,142 @@
//! Day 2: what a shared budget's log holds. `payment.shared` carries the effective payment and nothing of
//! its origin's details; the budget's members see it and can split it; unsharing takes it out again.
use fiscus_ledger::share::shared_payment;
use fiscus_ledger::split::Share;
use fiscus_ledger::{Date, Event, EventBody, Glyph, Haler, State, Timestamp};
fn d(s: &str) -> Date {
s.parse().unwrap()
}
fn ev(id: &str, body: EventBody) -> Event {
Event::new(id, Timestamp(0), body)
}
fn personal() -> Vec<Event> {
vec![
ev("e1", EventBody::BudgetCreated { budget: "b-home".into(), name: "Home".into(), limit: Haler(1_000_000) }),
ev("e2", EventBody::BudgetCreated { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(500_000) }),
ev(
"e3",
EventBody::PaymentCaptured {
payment: "p1".into(),
amount: Haler(-45_000),
date: d("2026-11-02"),
merchant: "Pension Lipno".into(),
card: Some("Visa 1234".into()),
},
),
ev("e4", EventBody::PaymentCategorised { payment: "p1".into(), category: "travel".into() }),
ev("e5", EventBody::PaymentAssigned { payment: "p1".into(), budget: "b-trip".into() }),
ev(
"e6",
EventBody::PaymentAdded {
payment: "p2".into(),
amount: Haler(-12_000),
date: d("2026-11-02"),
merchant: "Lekarna".into(),
category: None,
note: Some("private".into()),
},
),
]
}
#[test]
fn shared_payment_is_made_only_for_a_payment_in_that_budget() {
let s = State::replay(&personal());
let body = shared_payment(&s, "p1", "b-trip").expect("p1 is in the trip budget");
assert_eq!(
body,
EventBody::PaymentShared {
payment: "p1".into(),
budget: "b-trip".into(),
amount: Haler(-45_000),
date: d("2026-11-02"),
merchant: "Pension Lipno".into(),
category: Some("travel".into()),
glyph: Glyph::Captured,
}
);
let json = serde_json::to_string(&body).unwrap();
assert!(!json.contains("Visa") && !json.contains("1234"), "the card stays home: {json}");
assert!(shared_payment(&s, "p2", "b-trip").is_none(), "p2 is in the default budget, not the trip");
assert!(shared_payment(&s, "p1", "b-home").is_none());
assert!(shared_payment(&s, "nope", "b-trip").is_none());
}
fn shared_log() -> Vec<Event> {
let s = State::replay(&personal());
vec![
ev("g1", EventBody::BudgetCreated { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(500_000) }),
ev("g2", shared_payment(&s, "p1", "b-trip").unwrap()),
]
}
#[test]
fn members_see_the_shared_payment_in_the_budget() {
let s = State::replay(&shared_log());
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
let p = s.effective_payment("p1").unwrap();
assert_eq!((p.amount, p.glyph, p.budget.as_deref(), p.category.as_deref()), (Haler(-45_000), Glyph::Captured, Some("b-trip"), Some("travel")));
assert_eq!(p.card, None);
}
#[test]
fn a_shared_payment_can_be_split_and_unshared_until_it_is() {
let mut log = shared_log();
log.push(ev("g3", EventBody::PaymentUnshared { payment: "p1".into(), budget: "b-trip".into() }));
let s = State::replay(&log);
assert!(s.rejected.is_empty() && s.effective_payment("p1").is_none(), "unshared: gone from the budget");
let mut log = shared_log();
let shares = vec![
Share { person: "me".into(), name: "Me".into(), amount: Haler(-22_500) },
Share { person: "anna".into(), name: "Anna".into(), amount: Haler(-22_500) },
];
log.push(ev("g3", EventBody::SplitCreated { split: "s1".into(), payment: "p1".into(), payer: "me".into(), shares }));
log.push(ev("g4", EventBody::PaymentUnshared { payment: "p1".into(), budget: "b-trip".into() }));
let s = State::replay(&log);
assert_eq!(s.rejected.len(), 1, "a split payment stays shared");
assert!(s.effective_payment("p1").is_some());
}
#[test]
fn sharing_into_a_budget_the_log_does_not_have_is_rejected() {
let s = State::replay(&personal());
let s2 = State::replay(&[ev("g2", shared_payment(&s, "p1", "b-trip").unwrap())]);
assert_eq!(s2.rejected.len(), 1);
}
#[test]
fn only_an_explicit_assignment_shares_a_payment_never_the_default_budget() {
// A person whose only budget is a shared one: their unassigned payments fall to it as the default, but
// that never makes them shared.
let log = vec![
ev("e1", EventBody::BudgetCreated { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(500_000) }),
ev("e2", EventBody::PaymentCaptured { payment: "p1".into(), amount: Haler(-5_000), date: d("2026-11-02"), merchant: "Kavarna".into(), card: None }),
];
let s = State::replay(&log);
assert_eq!(s.effective_payment("p1").unwrap().budget.as_deref(), Some("b-trip"), "the default budget");
assert!(shared_payment(&s, "p1", "b-trip").is_none(), "not assigned, so not shared");
}
#[test]
fn a_shared_budget_in_the_personal_log_is_never_the_default() {
let log = vec![
ev("e1", EventBody::BudgetShared { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(500_000) }),
ev("e2", EventBody::PaymentCaptured { payment: "p1".into(), amount: Haler(-5_000), date: d("2026-11-02"), merchant: "Kavarna".into(), card: None }),
ev("e3", EventBody::BudgetCreated { budget: "b-home".into(), name: "Home".into(), limit: Haler(1_000_000) }),
ev("e4", EventBody::PaymentAssigned { payment: "p1".into(), budget: "b-trip".into() }),
];
let s = State::replay(&log);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
assert_eq!(s.default_budget.as_deref(), Some("b-home"));
assert_eq!(s.budgets["b-trip"].name, "Trip");
assert!(shared_payment(&s, "p1", "b-trip").is_some(), "assigned explicitly");
let dup = ev("e5", EventBody::BudgetShared { budget: "b-trip".into(), name: "Trip".into(), limit: Haler(1) });
let mut log2 = log.clone();
log2.push(dup);
assert_eq!(State::replay(&log2).rejected.len(), 1);
}
+211
View File
@@ -0,0 +1,211 @@
//! Day-2 mandatory tests: splits always sum exactly to the total and the remainder rule is deterministic;
//! `split.created` / `split.settled` refuse anything that does not add up; a share link shows exactly one
//! person's share, and nothing once it is settled, expired or unknown.
use fiscus_ledger::pay::Iban;
use fiscus_ledger::split::{split_equal, Person, Share};
use fiscus_ledger::{Date, Event, EventBody, Haler, Settlement, State, Timestamp};
use proptest::prelude::*;
fn d(s: &str) -> Date {
s.parse().unwrap()
}
fn people(ids: &[&str]) -> Vec<Person> {
ids.iter().map(|i| Person { id: (*i).into(), name: format!("Name {i}") }).collect()
}
fn ev(id: &str, body: EventBody) -> Event {
Event::new(id, Timestamp(0), body)
}
fn paid(amount: i64) -> Vec<Event> {
vec![ev(
"e-pay",
EventBody::PaymentAdded {
payment: "p1".into(),
amount: Haler(amount),
date: d("2026-11-02"),
merchant: "Pizzeria Uno".into(),
category: None,
note: None,
},
)]
}
fn created(shares: Vec<Share>) -> Event {
ev("e-split", EventBody::SplitCreated { split: "s1".into(), payment: "p1".into(), payer: "me".into(), shares })
}
fn share(person: &str, amount: i64) -> Share {
Share { person: person.into(), name: format!("Name {person}"), amount: Haler(amount) }
}
fn rejected_reason(log: &[Event]) -> Option<String> {
State::replay(log).rejected.last().map(|r| r.reason.clone())
}
proptest! {
#[test]
fn shares_always_sum_exactly_to_the_total(total in -10_000_000_000i64..10_000_000_000, n in 1usize..12) {
let ids: Vec<String> = (0..n).map(|i| format!("p{i}")).collect();
let ps: Vec<Person> = ids.iter().map(|i| Person { id: i.clone(), name: i.clone() }).collect();
let shares = split_equal(Haler(total), &ps).unwrap();
prop_assert_eq!(shares.len(), n);
prop_assert_eq!(shares.iter().map(|s| s.amount.0).sum::<i64>(), total);
let max = shares.iter().map(|s| s.amount.0.abs()).max().unwrap();
let min = shares.iter().map(|s| s.amount.0.abs()).min().unwrap();
prop_assert!(max - min <= 1, "equal shares differ by at most one haléř");
}
#[test]
fn the_remainder_does_not_depend_on_the_order_people_were_picked(total in -1_000_000i64..1_000_000, seed in any::<u64>()) {
let ids = ["anna", "bara", "cyril", "dana", "eva"];
let mut shuffled = ids.to_vec();
// A deterministic shuffle from the seed.
let mut s = seed;
for i in (1..shuffled.len()).rev() {
s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
shuffled.swap(i, (s >> 33) as usize % (i + 1));
}
prop_assert_eq!(split_equal(Haler(total), &people(&ids)).unwrap(), split_equal(Haler(total), &people(&shuffled)).unwrap());
}
}
#[test]
fn the_leftover_hal_go_to_the_first_people_by_id() {
let shares = split_equal(Haler(-100), &people(&["cyril", "anna", "bara"])).unwrap();
let got: Vec<(&str, i64)> = shares.iter().map(|s| (s.person.as_str(), s.amount.0)).collect();
assert_eq!(got, vec![("anna", -34), ("bara", -33), ("cyril", -33)]);
}
#[test]
fn a_person_picked_twice_counts_once_and_nobody_is_an_error() {
let shares = split_equal(Haler(-90), &people(&["anna", "bara", "anna"])).unwrap();
assert_eq!(shares.len(), 2);
assert!(split_equal(Haler(-90), &[]).is_err());
}
#[test]
fn a_split_that_adds_up_is_accepted() {
let mut log = paid(-1000);
log.push(created(vec![share("me", -334), share("anna", -333), share("bara", -333)]));
let s = State::replay(&log);
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
assert_eq!(s.splits["s1"].shares.len(), 3);
}
#[test]
fn a_split_that_does_not_add_up_is_rejected() {
for (shares, why) in [
(vec![share("me", -500), share("anna", -499)], "sum"),
(vec![share("me", -1001), share("anna", 1)], "sign"),
(vec![share("me", -500), share("me", -500)], "twice"),
(vec![share("anna", -500), share("bara", -500)], "payer"),
(vec![], "nobody"),
] {
let mut log = paid(-1000);
log.push(created(shares));
let s = State::replay(&log);
assert_eq!(s.rejected.len(), 1, "{why}: {:?}", s.rejected);
assert!(s.splits.is_empty(), "{why}: half-applied");
}
// A payment in (money received) is not split, and a split needs its payment.
let mut log = paid(1000);
log.push(created(vec![share("me", 500), share("anna", 500)]));
assert!(rejected_reason(&log).is_some());
assert!(rejected_reason(&[created(vec![share("me", -1)])]).is_some());
}
#[test]
fn settling_is_once_per_person_and_never_the_payer() {
let mut log = paid(-1000);
log.push(created(vec![share("me", -500), share("anna", -500)]));
let settle = |id: &str, person: &str| ev(id, EventBody::SplitSettled { split: "s1".into(), person: person.into(), how: Settlement::Qr });
log.push(settle("e-s1", "anna"));
assert!(State::replay(&log).rejected.is_empty());
for (id, person) in [("e-s2", "anna"), ("e-s3", "me"), ("e-s4", "cyril")] {
let mut l = log.clone();
l.push(settle(id, person));
assert!(rejected_reason(&l).is_some(), "{person} settled");
}
assert!(State::replay(&log).splits["s1"].settled.contains_key("anna"));
}
const LINK: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90";
const OTHER: &str = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
fn with_link() -> Vec<Event> {
let mut log = paid(-1000);
log.push(created(vec![share("me", -334), share("anna", -333), share("bara", -333)]));
log.push(ev("e-acc", EventBody::AccountSet { iban: "CZ6508000000192000145399".into(), name: "Marek Novak".into() }));
log.push(ev(
"e-link",
EventBody::ShareLinkCreated { link: LINK.into(), split: "s1".into(), person: "anna".into(), expires: d("2026-12-02") },
));
log
}
#[test]
fn a_share_link_shows_exactly_one_persons_share() {
let s = State::replay(&with_link());
assert!(s.rejected.is_empty(), "{:?}", s.rejected);
let v = s.share_view(LINK, d("2026-11-03")).expect("open");
assert_eq!(v.name, "Name anna");
assert_eq!(v.amount, Haler(333));
assert_eq!(v.merchant, "Pizzeria Uno");
assert_eq!(v.date, d("2026-11-02"));
assert_eq!(v.spayd.as_deref(), Some("SPD*1.0*ACC:CZ6508000000192000145399*AM:3.33*CC:CZK*RN:Marek Novak*MSG:Pizzeria Uno 2.11.2026"));
// Everything the page can show is in this one struct; serialise it and look for the others.
let all = serde_json::to_string(&v).unwrap();
for leak in ["bara", "Name me", "334", "-1000", "10,00", "s1", "p1"] {
assert!(!all.contains(leak), "{leak} leaked into {all}");
}
}
#[test]
fn a_settled_expired_or_unknown_link_shows_nothing() {
let s = State::replay(&with_link());
assert!(s.share_view(OTHER, d("2026-11-03")).is_none(), "unknown");
assert!(s.share_view(LINK, d("2026-12-03")).is_none(), "expired");
assert!(s.share_view(LINK, d("2026-12-02")).is_some(), "the last day is still open");
let mut log = with_link();
log.push(ev("e-set", EventBody::SplitSettled { split: "s1".into(), person: "anna".into(), how: Settlement::Marked }));
assert!(State::replay(&log).share_view(LINK, d("2026-11-03")).is_none(), "settled");
}
#[test]
fn a_link_for_the_payer_or_a_stranger_is_rejected() {
for person in ["me", "cyril"] {
let mut log = with_link();
log.pop();
log.push(ev(
"e-link",
EventBody::ShareLinkCreated { link: LINK.into(), split: "s1".into(), person: person.into(), expires: d("2026-12-02") },
));
assert!(rejected_reason(&log).is_some(), "{person}");
}
let mut log = with_link();
log.push(ev("e-link2", EventBody::ShareLinkCreated { link: "short".into(), split: "s1".into(), person: "bara".into(), expires: d("2026-12-02") }));
assert!(rejected_reason(&log).is_some(), "a link is a SHA-256 in hex");
}
#[test]
fn the_account_must_be_a_valid_czech_iban() {
assert!(Iban::parse("CZ6508000000192000145399").is_ok());
let bad = ev("e-acc", EventBody::AccountSet { iban: "CZ6608000000192000145399".into(), name: "X".into() });
assert!(rejected_reason(&[bad]).is_some());
}
#[test]
fn capture_tokens_are_hashes_and_revoke_once() {
let add = ev("e-t1", EventBody::CaptureTokenAdded { token: OTHER.into(), name: "Mark's iPhone".into(), kind: fiscus_ledger::CaptureKind::Iphone });
let revoke = |id: &str| ev(id, EventBody::CaptureTokenRevoked { token: OTHER.into() });
let s = State::replay(std::slice::from_ref(&add));
assert!(s.capture_token_active(OTHER));
let s = State::replay(&[add.clone(), revoke("e-t2")]);
assert!(!s.capture_token_active(OTHER) && s.rejected.is_empty());
assert!(rejected_reason(&[add.clone(), revoke("e-t2"), revoke("e-t3")]).is_some());
let raw = ev("e-t1", EventBody::CaptureTokenAdded { token: "my-secret-token".into(), name: "x".into(), kind: fiscus_ledger::CaptureKind::Android });
assert!(rejected_reason(&[raw]).is_some(), "only a hash is ever stored");
}
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "fiscus-statement"
description = "Fiscus Domi: strict statement parsing (only banks with real samples)"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
fiscus-ledger = { path = "../fiscus-ledger" }
encoding_rs = "0.8"
serde.workspace = true
thiserror.workspace = true
[dev-dependencies]
proptest.workspace = true
serde_json.workspace = true
+155
View File
@@ -0,0 +1,155 @@
//! A strict CSV reader (RFC 4180 with a chosen delimiter). Every irregularity is an error with its line
//! number; a row is either returned whole or the file is refused.
use serde::Serialize;
/// Longest row accepted, in bytes.
pub const MAX_ROW: usize = 64 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Dialect {
pub delimiter: char,
/// The last row must end with a line break: a file cut mid-row is then always an error.
pub final_newline: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error, Serialize)]
pub enum CsvError {
#[error("a quote inside a field that is not quoted")]
BareQuote,
#[error("a quoted field is never closed")]
UnterminatedQuote,
#[error("text after a closing quote")]
TextAfterQuote,
#[error("{found} fields where the header has {expected}")]
Ragged { expected: usize, found: usize },
#[error("the row is longer than {MAX_ROW} bytes")]
RowTooLong,
#[error("the file does not end with a line break; it may be cut short")]
MissingFinalNewline,
#[error("a carriage return without a line feed")]
LoneCarriageReturn,
}
/// One row and the line it starts on (1-based).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Row {
pub line: usize,
pub fields: Vec<String>,
}
/// Reads every row. All rows must have as many fields as the first. Blank lines are refused too (a bank
/// parser that expects them, e.g. between a preamble and the table, splits the text first).
pub fn read(text: &str, dialect: Dialect) -> Result<Vec<Row>, (usize, CsvError)> {
let mut rows: Vec<Row> = Vec::new();
let mut chars = text.chars().peekable();
let mut line = 1usize;
let mut row_start_line = 1usize;
let mut row_bytes = 0usize;
let mut fields: Vec<String> = Vec::new();
let mut field = String::new();
let mut in_quotes = false;
let mut was_quoted = false; // the current field was quoted and has been closed
let mut field_started = false;
let mut ended_with_newline = false;
let finish_row = |rows: &mut Vec<Row>, fields: &mut Vec<String>, start: usize| -> Result<(), (usize, CsvError)> {
let row = std::mem::take(fields);
if let Some(first) = rows.first() {
if row.len() != first.fields.len() {
return Err((start, CsvError::Ragged { expected: first.fields.len(), found: row.len() }));
}
}
rows.push(Row { line: start, fields: row });
Ok(())
};
while let Some(c) = chars.next() {
row_bytes += c.len_utf8();
if row_bytes > MAX_ROW {
return Err((row_start_line, CsvError::RowTooLong));
}
ended_with_newline = false;
if in_quotes {
match c {
'"' if chars.peek() == Some(&'"') => {
chars.next();
field.push('"');
}
'"' => {
in_quotes = false;
was_quoted = true;
}
'\n' => {
line += 1;
field.push('\n');
}
'\r' => {
if chars.peek() == Some(&'\n') {
chars.next();
line += 1;
field.push('\n');
} else {
return Err((line, CsvError::LoneCarriageReturn));
}
}
other => field.push(other),
}
continue;
}
let newline = match c {
'\n' => true,
'\r' if chars.peek() == Some(&'\n') => {
chars.next();
true
}
'\r' => return Err((line, CsvError::LoneCarriageReturn)),
_ => false,
};
if newline {
fields.push(std::mem::take(&mut field));
finish_row(&mut rows, &mut fields, row_start_line)?;
line += 1;
row_start_line = line;
row_bytes = 0;
was_quoted = false;
field_started = false;
ended_with_newline = true;
continue;
}
if c == dialect.delimiter {
fields.push(std::mem::take(&mut field));
was_quoted = false;
field_started = false;
continue;
}
if was_quoted {
return Err((line, CsvError::TextAfterQuote));
}
if c == '"' {
if field_started {
return Err((line, CsvError::BareQuote));
}
in_quotes = true;
field_started = true;
continue;
}
field_started = true;
field.push(c);
}
if in_quotes {
return Err((row_start_line, CsvError::UnterminatedQuote));
}
let pending = field_started || was_quoted || !fields.is_empty();
if pending {
if dialect.final_newline {
return Err((row_start_line, CsvError::MissingFinalNewline));
}
fields.push(field);
finish_row(&mut rows, &mut fields, row_start_line)?;
} else if dialect.final_newline && !ended_with_newline && !text.is_empty() {
return Err((row_start_line, CsvError::MissingFinalNewline));
}
Ok(rows)
}
+83
View File
@@ -0,0 +1,83 @@
//! Field parsers for Czech statements: amounts to whole haléře, dates. Strict: anything unusual is an error.
use fiscus_ledger::{Date, Haler};
use serde::Serialize;
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error, Serialize)]
pub enum FieldError {
#[error("empty")]
Empty,
#[error("not an amount: {0:?}")]
Amount(String),
#[error("more than two decimals: {0:?}")]
TooPrecise(String),
#[error("the amount is too large")]
Overflow,
#[error("not a date: {0:?}")]
Date(String),
}
fn shown(s: &str) -> String {
s.chars().take(40).collect()
}
/// `-1 234,50` → `Haler(-123450)` with `decimal = ','`; `-1,234.50` with `decimal = '.'`.
///
/// One sign at the front (`-`, `+` or the Unicode minus `−`), ASCII digits, the decimal mark followed by one
/// or two digits. Thousands separators (space, no-break spaces, or the other of `,`/`.`) only between
/// groups of exactly three digits.
pub fn amount(text: &str, decimal: char) -> Result<Haler, FieldError> {
let t = text.trim_matches(|c: char| c == ' ' || c == '\u{a0}');
if t.is_empty() {
return Err(FieldError::Empty);
}
let bad = || FieldError::Amount(shown(text));
let (neg, rest) = if let Some(r) = t.strip_prefix('-').or_else(|| t.strip_prefix('\u{2212}')) {
(true, r)
} else if let Some(r) = t.strip_prefix('+') {
(false, r)
} else {
(false, t)
};
let (int, frac) = match rest.split_once(decimal) {
Some((i, f)) => (i, Some(f)),
None => (rest, None),
};
let other = if decimal == ',' { '.' } else { ',' };
let is_sep = |c: char| c == ' ' || c == '\u{a0}' || c == '\u{202f}' || c == other;
let groups: Vec<&str> = int.split(is_sep).collect();
if groups.iter().any(|g| g.is_empty() || !g.bytes().all(|b| b.is_ascii_digit())) {
return Err(bad());
}
if groups.len() > 1 && (groups[0].len() > 3 || groups[1..].iter().any(|g| g.len() != 3)) {
return Err(bad());
}
let cents = match frac {
None => 0,
Some(f) if f.is_empty() || !f.bytes().all(|b| b.is_ascii_digit()) => return Err(bad()),
Some(f) if f.len() > 2 => return Err(FieldError::TooPrecise(shown(text))),
Some(f) => f.parse::<i64>().map_err(|_| bad())? * if f.len() == 1 { 10 } else { 1 },
};
let digits: String = groups.concat();
let whole: i64 = digits.parse().map_err(|_| FieldError::Overflow)?;
let abs = whole.checked_mul(100).and_then(|w| w.checked_add(cents)).ok_or(FieldError::Overflow)?;
Ok(Haler(if neg { -abs } else { abs }))
}
/// `03.11.2026` or `3.11.2026` (a two-digit year is refused).
pub fn date_dmy(text: &str) -> Result<Date, FieldError> {
let t = text.trim();
let bad = || FieldError::Date(shown(text));
let parts: Vec<&str> = t.split('.').collect();
let [d, m, y] = parts.as_slice() else { return Err(bad()) };
let ok = |s: &str, lens: &[usize]| lens.contains(&s.len()) && s.bytes().all(|b| b.is_ascii_digit());
if !ok(d, &[1, 2]) || !ok(m, &[1, 2]) || !ok(y, &[4]) {
return Err(bad());
}
Date::from_ymd(y.parse().map_err(|_| bad())?, m.parse().map_err(|_| bad())?, d.parse().map_err(|_| bad())?).ok_or_else(bad)
}
/// `2026-11-03`.
pub fn date_iso(text: &str) -> Result<Date, FieldError> {
text.trim().parse().map_err(|_| FieldError::Date(shown(text)))
}
+112
View File
@@ -0,0 +1,112 @@
//! Statement parsing for Fiscus Domi. Hostile input: strict, typed errors, never a partial row.
//!
//! **Only banks with real samples in `fixtures/` are supported.** No bank format is ever written from memory
//! or documentation alone. Until a bank's redacted samples arrive, [`parse`] returns
//! [`ParseError::UnsupportedFormat`] for it, and the app says so. What this crate already holds is the
//! strict ground every bank parser stands on: [`csv`], [`field`] and [`decode`].
pub mod csv;
pub mod field;
use fiscus_ledger::import::StatementLine;
use serde::{Deserialize, Serialize};
/// A statement file larger than this is refused before it is read.
pub const MAX_FILE: usize = 16 * 1024 * 1024;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Statement {
pub bank: String,
pub account: String,
pub lines: Vec<StatementLine>,
}
/// A supported bank: which formats it parses, built from which samples.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct Bank {
pub id: &'static str,
pub name: &'static str,
pub formats: &'static [&'static str],
}
/// Every bank with a parser. Empty until real samples arrive (see the crate docs).
pub const BANKS: &[Bank] = &[];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Encoding {
/// Strict UTF-8; a leading BOM is dropped.
Utf8,
/// Windows-1250 (Central European), which many Czech banks still export.
Windows1250,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error, Serialize)]
pub enum ParseError {
#[error("the file is empty")]
Empty,
#[error("the file is {size} bytes; the limit is {MAX_FILE}")]
TooLarge { size: usize },
#[error("the file is not valid text in the expected encoding (byte {offset})")]
Encoding { offset: usize },
#[error("this is not a statement format Fiscus knows; no bank is supported until its real samples are added")]
UnsupportedFormat,
#[error("line {line}: {kind}")]
Csv { line: usize, kind: csv::CsvError },
#[error("line {line}, {column}: {error}")]
Field { line: usize, column: String, error: field::FieldError },
#[error("the header is not the one this bank writes")]
Header,
}
/// Decodes a whole file. Strict: invalid UTF-8 is an error, never replaced; NUL bytes are refused.
pub fn decode(bytes: &[u8], encoding: Encoding) -> Result<String, ParseError> {
if bytes.is_empty() {
return Err(ParseError::Empty);
}
if bytes.len() > MAX_FILE {
return Err(ParseError::TooLarge { size: bytes.len() });
}
if let Some(offset) = bytes.iter().position(|b| *b == 0) {
return Err(ParseError::Encoding { offset });
}
let (text, bom) = match encoding {
Encoding::Utf8 => {
let body = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
let bom = bytes.len() - body.len();
let text = std::str::from_utf8(body).map_err(|e| ParseError::Encoding { offset: e.valid_up_to() + bom })?;
(text.to_owned(), bom)
}
Encoding::Windows1250 => {
// The WHATWG table maps Windows-1250's five unassigned bytes to C1 controls, refused below.
let (text, _, had_errors) = encoding_rs::WINDOWS_1250.decode(bytes);
if had_errors {
return Err(ParseError::Encoding { offset: 0 });
}
(text.into_owned(), 0)
}
};
// A statement is text: no control characters but tab and line breaks. Report the byte where it starts.
if let Some((i, _)) = text.char_indices().find(|(_, c)| c.is_control() && !matches!(c, '\t' | '\r' | '\n')) {
let offset = match encoding {
Encoding::Utf8 => i + bom,
Encoding::Windows1250 => text[..i].chars().count(), // one byte per character
};
return Err(ParseError::Encoding { offset });
}
Ok(text)
}
/// Parses a statement file with the bank parser that recognises it.
///
/// No bank parser exists yet, so after the size checks every file is `UnsupportedFormat`.
pub fn parse(bytes: &[u8]) -> Result<Statement, ParseError> {
if bytes.is_empty() {
return Err(ParseError::Empty);
}
if bytes.len() > MAX_FILE {
return Err(ParseError::TooLarge { size: bytes.len() });
}
// Each bank in BANKS gets a `detect(bytes) -> bool` and a `parse(bytes)` here, in its own module,
// with its fixtures under fixtures/<bank>/.
Err(ParseError::UnsupportedFormat)
}
+62
View File
@@ -0,0 +1,62 @@
//! Mandatory test 2: every real sample in `fixtures/<bank>/` parses to exactly its `.expected.json`, and
//! every truncation of it is an error or a prefix of whole lines.
//!
//! A sample is any file in `fixtures/<bank>/` other than `*.expected.json` and `README*`. Day 1 has no
//! samples, so this test walks an empty tree; it starts to bite the moment a sample is added (and fails until
//! that bank has a parser and the expected rows).
use fiscus_statement::{parse, Statement};
use std::path::{Path, PathBuf};
fn samples() -> Vec<PathBuf> {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
let mut out = Vec::new();
let Ok(banks) = std::fs::read_dir(&root) else { return out };
for bank in banks.flatten().filter(|e| e.path().is_dir()) {
for f in std::fs::read_dir(bank.path()).unwrap().flatten() {
let name = f.file_name().to_string_lossy().to_string();
if f.path().is_file() && !name.ends_with(".expected.json") && !name.starts_with("README") {
out.push(f.path());
}
}
}
out.sort();
out
}
fn expected_for(sample: &Path) -> PathBuf {
let name = sample.file_name().unwrap().to_string_lossy();
sample.with_file_name(format!("{name}.expected.json"))
}
#[test]
fn every_fixture_parses_to_its_expected_rows() {
let all = samples();
eprintln!("statement fixtures: {}", all.len());
for sample in all {
let bytes = std::fs::read(&sample).unwrap();
let want: Statement = serde_json::from_slice(
&std::fs::read(expected_for(&sample)).unwrap_or_else(|_| panic!("{} has no .expected.json", sample.display())),
)
.unwrap();
let got = parse(&bytes).unwrap_or_else(|e| panic!("{}: {e}", sample.display()));
assert_eq!(got, want, "{}", sample.display());
}
}
#[test]
fn every_truncated_fixture_is_an_error_or_whole_lines() {
for sample in samples() {
let bytes = std::fs::read(&sample).unwrap();
let full = parse(&bytes).unwrap();
let step = (bytes.len() / 2000).max(1);
for cut in (0..bytes.len()).step_by(step) {
if let Ok(st) = parse(&bytes[..cut]) {
assert!(st.lines.len() <= full.lines.len(), "{} cut at {cut}", sample.display());
for (got, want) in st.lines.iter().zip(&full.lines) {
assert_eq!(got, want, "{} cut at {cut}: a partial line", sample.display());
}
}
}
}
}
+155
View File
@@ -0,0 +1,155 @@
//! Mandatory test 2: hostile statement input. Random bytes and every truncation give a typed error or only
//! whole rows, never a panic and never a partial row.
use fiscus_ledger::Haler;
use fiscus_statement::csv::{read, CsvError, Dialect};
use fiscus_statement::field::{amount, date_dmy, FieldError};
use fiscus_statement::{decode, parse, Encoding, ParseError, MAX_FILE};
use proptest::prelude::*;
const STRICT: Dialect = Dialect { delimiter: ';', final_newline: true };
/// A generic RFC 4180 file (not any bank's format): quotes, an escaped quote, a line break inside a field,
/// CRLF, diacritics.
const SAMPLE: &str = "date;amount;merchant;note\r\n\
03.10.2026;-129,00;Albert;\r\n\
04.10.2026;\"-1 234,50\";\"Kavárna \"\"U Nováků\"\"\";\"two\nlines\"\r\n\
05.10.2026;35 000,00;Mzda;říjen\r\n";
#[test]
fn reads_the_generic_sample() {
let rows = read(SAMPLE, STRICT).unwrap();
assert_eq!(rows.len(), 4);
assert_eq!(rows[2].fields, vec!["04.10.2026", "-1 234,50", "Kavárna \"U Nováků\"", "two\nlines"]);
assert_eq!(rows[3].line, 5, "the row after a two-line field starts on line 5");
assert_eq!(amount(&rows[2].fields[1], ','), Ok(Haler(-123_450)));
assert_eq!(amount(&rows[3].fields[1], ','), Ok(Haler(3_500_000)));
}
#[test]
fn every_truncation_is_an_error_or_whole_rows() {
let full = read(SAMPLE, STRICT).unwrap();
for cut in 0..SAMPLE.len() {
if !SAMPLE.is_char_boundary(cut) {
continue;
}
match read(&SAMPLE[..cut], STRICT) {
Err(_) => {}
Ok(rows) => {
assert!(rows.len() <= full.len());
for (got, want) in rows.iter().zip(&full) {
assert_eq!(got, want, "a partial row at cut {cut}");
}
}
}
}
}
#[test]
fn irregular_csv_is_refused_with_its_line() {
let cases: &[(&str, usize, CsvError)] = &[
("a;b\nc;d;e\n", 2, CsvError::Ragged { expected: 2, found: 3 }),
("a;b\nc\n", 2, CsvError::Ragged { expected: 2, found: 1 }),
("a;b\n\nc;d\n", 2, CsvError::Ragged { expected: 2, found: 1 }),
("a;b\nc\"x;d\n", 2, CsvError::BareQuote),
("a;b\n\"c;d\n", 2, CsvError::UnterminatedQuote),
("a;b\n\"c\"x;d\n", 2, CsvError::TextAfterQuote),
("a;b\nc;d", 2, CsvError::MissingFinalNewline),
("a;b\rc;d\n", 1, CsvError::LoneCarriageReturn),
];
for (text, line, kind) in cases {
assert_eq!(read(text, STRICT), Err((*line, kind.clone())), "{text:?}");
}
let long = format!("a\n{}\n", "x".repeat(70_000));
assert_eq!(read(&long, STRICT), Err((2, CsvError::RowTooLong)));
}
#[test]
fn amounts() {
let ok: &[(&str, char, i64)] = &[
("-1 234,50", ',', -123_450),
("1234,50", ',', 123_450),
("\u{2212}12,00", ',', -1_200),
("1.234,50", ',', 123_450),
("+5,5", ',', 550),
("1\u{a0}000\u{a0}000,00", ',', 100_000_000),
("-1,234.50", '.', -123_450),
("0,01", ',', 1),
("12", ',', 1_200),
];
for (text, dec, want) in ok {
assert_eq!(amount(text, *dec), Ok(Haler(*want)), "{text:?}");
}
let bad = ["", "-", "1,2,3", "12,345", "1 23,00", "12 3456,00", "--5", "5-", "1e3", "12,", ",50", "NaN", "0x10", "١٢٣", "12.50"];
for text in bad {
assert!(amount(text, ',').is_err(), "{text:?} must be refused");
}
assert!(matches!(amount("12,345", ','), Err(FieldError::TooPrecise(_))));
assert_eq!(amount("99999999999999999999,00", ','), Err(FieldError::Overflow));
}
#[test]
fn dates() {
assert_eq!(date_dmy("03.11.2026").unwrap().to_string(), "2026-11-03");
assert_eq!(date_dmy("3.1.2026").unwrap().to_string(), "2026-01-03");
for bad in ["31.02.2026", "03.11.26", "2026.11.03", "03/11/2026", "03.11.2026x", "", "0.0.0000"] {
assert!(date_dmy(bad).is_err(), "{bad:?}");
}
}
#[test]
fn decoding_is_strict() {
assert_eq!(decode(b"\xEF\xBB\xBFa;b\n", Encoding::Utf8).unwrap(), "a;b\n");
assert!(matches!(decode(b"a;\xC3\x28\n", Encoding::Utf8), Err(ParseError::Encoding { offset: 2 })));
assert!(matches!(decode(b"a\x00b", Encoding::Utf8), Err(ParseError::Encoding { offset: 1 })));
// "Příliš" in Windows-1250.
assert_eq!(decode(b"P\xF8\xEDli\x9A", Encoding::Windows1250).unwrap(), "Příliš");
assert!(matches!(decode(b"x\x81", Encoding::Windows1250), Err(ParseError::Encoding { .. })));
assert_eq!(decode(b"", Encoding::Utf8), Err(ParseError::Empty));
}
#[test]
fn no_bank_is_supported_without_samples() {
assert!(fiscus_statement::BANKS.is_empty());
assert_eq!(parse(SAMPLE.as_bytes()), Err(ParseError::UnsupportedFormat));
assert_eq!(parse(b""), Err(ParseError::Empty));
let huge = vec![b'a'; MAX_FILE + 1];
assert_eq!(parse(&huge), Err(ParseError::TooLarge { size: MAX_FILE + 1 }));
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2000))]
#[test]
fn random_bytes_never_panic(bytes in prop::collection::vec(any::<u8>(), 0..400)) {
let _ = parse(&bytes);
for enc in [Encoding::Utf8, Encoding::Windows1250] {
if let Ok(text) = decode(&bytes, enc) {
for dialect in [STRICT, Dialect { delimiter: ',', final_newline: false }] {
if let Ok(rows) = read(&text, dialect) {
if let Some(first) = rows.first() {
prop_assert!(rows.iter().all(|r| r.fields.len() == first.fields.len()));
}
for r in &rows {
for f in &r.fields {
let _ = amount(f, ',');
let _ = date_dmy(f);
}
}
}
}
}
}
}
#[test]
fn csv_like_noise_never_panics(text in "[a;\"\r\n,0-9 ]{0,200}") {
let _ = read(&text, STRICT);
let _ = read(&text, Dialect { delimiter: ',', final_newline: false });
}
#[test]
fn amounts_round_trip(h in -100_000_000_000i64..100_000_000_000) {
prop_assert_eq!(amount(&Haler(h).to_czk(), ','), Ok(Haler(h)));
}
}
+125
View File
@@ -0,0 +1,125 @@
# 01 — The core (day 1)
Three crates in one workspace, all pure: no I/O, no clock, no OS randomness. Dates, "today" and seeds are
parameters. There is no `f32`/`f64` anywhere in the workspace (a test scans the sources).
| Crate | What it holds |
|:--|:--|
| `fiscus-ledger` | `Haler`, `Date`, the event log and `apply()`, merchant keys, rules, matching |
| `fiscus-statement` | statement parsing: strict CSV reader, Czech amount/date fields, the bank registry |
| `fiscus-insight` | subscriptions (cadence, price creep, trials, next charge), cancel kits, the forecast |
## Money
`Haler(i64)`: one haléř. Outflows are negative, inflows positive, as on a statement. Arithmetic is checked;
an overflow is an error, never a wrap. `split(total, weights)` uses the largest-remainder rule: everyone gets
`floor(total·w/Σw)`, the leftover haléře go one each to the largest remainders, ties to the lower index.
The shares always sum to the total. CZK only.
## Dates
`Date` is a civil date stored as days since 1970-01-01 (proleptic Gregorian). `add_months` clamps to the
month's last day (31 Jan + 1 month = 28/29 Feb). `Timestamp` is milliseconds since the epoch, given by the app.
## The ledger
An append-only list of `Event { id, at, body }`. State is `apply()` folded over the log, in log order. Every
map in the state is a `BTreeMap`, so the serialised state is byte-identical however it was built.
`apply()` is total: an event that does not fit (unknown payment, a second confirmation, a zero amount) is
recorded in `state.rejected` and changes nothing else. Corrections are new events; nothing is ever removed.
| Event | Effect |
|:--|:--|
| `payment.captured` | a phone saw a card payment (○). Not used on day 1, but in the model and the tests |
| `payment.imported` | a statement line (●). Carries `line_key`: the same line imported twice is rejected |
| `payment.added` | added by hand (◆) |
| `payment.confirmed` | ties a captured or hand-added payment to a statement line, one to one; they show as one payment |
| `payment.categorised` | an explicit category for one payment |
| `payment.assigned` | puts a payment into a budget |
| `payment.trial_marked` | "this is a trial", with its end date |
| `budget.created` / `budget.limit_set` | a monthly budget and its limit |
| `rule.created` | "always <merchant> → <category>" |
| `subscription.decided` | keep or cancel, for a merchant, at the amount seen when deciding |
**Effective payment.** A confirmed pair is one payment: the statement line's amount and date, the earlier
payment's merchant text if the line has none, any explicit category or budget from either side (the later
event wins). Source glyph: ● if a statement line is involved, else ○ captured or ◆ by hand.
**Category.** Explicit `payment.categorised` (latest) → the latest rule for the payment's merchant key →
`uncategorised`. Fixing a category in the app writes both a `payment.categorised` and a `rule.created`, so
earlier and later payments from that merchant follow (unless they have their own explicit category).
**Budget.** Explicit `payment.assigned` (latest) → the default budget (the first one created). Budgets are
monthly; a budget's spending is minus the sum of its payments in that month.
## Merchant keys
`merchant_key(raw)`: fold Czech diacritics to ASCII, lowercase, cut a processor prefix before `*`
(`PAYPAL *SPOTIFY` → `spotify`), turn punctuation into spaces, drop tokens that contain a digit
(store numbers, card tails, dates) and a trailing country code (`cz`, `cze`), collapse spaces. Rules and
subscriptions key on this.
## Matching (capture ↔ statement)
Candidates: unconfirmed captured or hand-added payments, and unconfirmed statement lines. A pair is
compatible when the amounts are equal to the haléř, the line is booked 1 day before to 5 days after the
capture, and the merchant keys are compatible (equal, one contains the other, or the same first word of
≥ 3 letters). A capture with no merchant (hand-added cash) never auto-matches on merchant alone.
Rounds until nothing changes: a pair is matched when each side's best candidate is the other and the best is
strictly better than the second best on both sides (score: exact merchant key, then smaller day gap).
Everything else is reported: `unmatched_captured`, `unmatched_lines`, and `ambiguous` (with its candidates)
for the user to pick. One capture never matches two lines; a line never matches two captures.
## Import
`plan_import(state, lines)` → the lines whose `line_key` is new, the duplicates it skipped, and the match
proposals. Re-importing the same statement produces no events. `line_key` = bank + account + the bank's own
transaction id when the format has one, else date|amount|merchant|counterparty|message plus the occurrence
number of that exact tuple within the file (two identical coffees on one day stay two lines).
## Statement parsing
`fiscus-statement` registers one parser per bank, built only from that bank's real samples in
`fixtures/<bank>/` (each `x.csv` next to its `x.expected.json`). **Day 1 has no samples, so no bank is
supported** and `parse()` returns `UnsupportedFormat`. What exists is the shared ground every bank parser
will stand on, all strict:
- `csv::read(text, delimiter)` — RFC 4180 with a chosen delimiter; a bare quote, an unterminated quote, a
ragged row or a row over 64 KiB is an error with its line number, never a skipped or partial row;
- `field::amount("-1 234,50")` → `Haler(-123450)` (a space, NBSP or `.` as thousands separator only where it
is unambiguous, `,` as decimal comma, at most two decimals, the Unicode minus too); `field::date_dmy`;
- `decode(bytes, Encoding)` — strict UTF-8 (BOM dropped) or Windows-1250;
- size cap: a file over 16 MiB is refused before it is read.
A fixture test walks `fixtures/` and fails for any sample whose parse differs from its `.expected.json`;
the same files are then cut at every length and must give an error or only whole rows.
## Subscriptions (`fiscus-insight`)
Outflows grouped by merchant key, in date order, a confirmed pair counted once.
- **Cadence:** monthly when there are ≥ 2 charges and every gap is 26–35 days; yearly when every gap is
358–373 days. Charges are first grouped by amount (each within ±50 % of the group's last, so a price rise
stays in its group and one merchant can bill two subscriptions), and a group must be mostly one price: at
most one change in every two steps, none with only two charges. A supermarket's varying totals never pass.
Payments categorised housing, utilities, transfers or income are not subscriptions.
- **Price creep:** the last charge differs from the one before it. The alert stands until a
`subscription.decided` records that amount.
- **Trial:** a charge of at most 10 CZK (card check) at a merchant with no later full charge, or a payment
marked by hand. An automatic trial's end is estimated at 30 days after the check and shown as an estimate;
a hand-marked trial uses its end date. A trial followed by a full charge becomes a subscription.
- **Next charge:** last charge + 1 month (day clamped) or + 1 year; the "next 7 days" strip is everything
due in `[today, today + 7]`, trials by their end date.
- **Review:** each month every active subscription without a decision in that month is listed for keep/cancel.
A charge after a "cancel" decision is flagged.
- **Cancel kit:** a known provider's account page (a short built-in list) and a prefilled email.
## Forecast
Bootstrap Monte Carlo, integers only. Inputs: the last 90 days' daily spending, this month's spending so far,
the days left, the limit, known subscription charges still due this month, a seed and the number of runs.
Each run adds a randomly drawn past day for every day left (xoshiro256** seeded by SplitMix64, unbiased
index by rejection), plus the known charges. Output: chance to stay under the limit in basis points
(0–10 000) and the 10th/50th/90th percentile month ends in haléře. Same inputs and seed → identical output.
## Day 1 test list (written first)
1. Money: property tests — sums, splits and refunds never lose or create a haléř; overflow is an error;
no `f32`/`f64` in any source file of the workspace.
2. Statements: every fixture parses to its expected rows (none yet); random bytes and every truncation of a
valid CSV give a typed error or only whole rows, never a panic.
3. Matching: one capture never matches two lines; the same statement imported twice adds nothing;
unmatched items on both sides are reported.
4. Replay: state built incrementally, built in one go, and rebuilt from the serialised log serialise to the
same bytes.
5. Subscriptions: on fixture histories, detection finds the known subscriptions, flags the known price change
and the known trial, and does not call a monthly supermarket a subscription.
6. Forecast: same seed → identical output.
+84
View File
@@ -0,0 +1,84 @@
# 02 — Capture, splits, QR Platba, sharing (day 2)
Written before the code. Everything here is pure, like day 1: no I/O, no clock, no randomness. The app
(Fiscus `docs/02_phones_sharing.md`) moves these events through Fundamentum; the core only defines them,
applies them and checks them.
## New events (`fiscus-ledger`)
A **personal log** (your own devices, the Fundamentum *self group*) holds every event. A **shared budget**
is a log of its own (one MLS group): its members see exactly what was put into it, nothing else.
| Event | Where | Effect |
|:--|:--|:--|
| `payment.shared` | shared budget | a member put one payment into this budget: `payment, budget, amount, date, merchant, category, origin`. Creates the payment in this log, or reassigns it after an unshare |
| `payment.unshared` | shared budget | takes it out again (it stays in the log, unassigned) |
| `budget.shared` | personal | a shared budget (created here or joined): like `budget.created`, but **never the default budget** |
| `split.created` | either | `split, payment, payer, shares: [{person, name, amount}]`. Rejected unless the shares sum **exactly** to the payment's amount, every amount has the payment's sign, people are unique, and the payer is one of them |
| `split.settled` | either | `split, person, how` (`qr`, `marked`). Rejected for an unknown split or person, the payer, or a second settlement |
| `capture.token_added` / `capture.token_revoked` | personal | a phone's capture token: only its SHA-256 (`token`), a `name` and the `kind` (`iphone`, `android`). The token itself lives in Custos |
| `share.link_created` | personal | a share link for one person of one split: only the SHA-256 of the link token, `split`, `person`, `expires` |
| `account.set` | personal | the account for QR Platba (`iban`, `name`); the log is encrypted everywhere it is stored |
| `profile.named` | personal | the name you show to the members of your shared budgets (1–40 characters) *(v0.3.0)* |
| `household.sharing_set` | personal | `budget, on`: share your subscription names with this shared budget, or stop. Rejected for the default budget or an unknown one *(v0.3.0)* |
| `member.named` | shared budget | `budget, name`: what its author is called there. The latest per author counts *(v0.3.0)* |
| `subscriptions.shared` | shared budget | `budget, names`: the service keys of every subscription its author still pays (at most 100, each 1–40 characters, no repeats). The latest per author replaces the earlier; `[]` withdraws them *(v0.3.0)* |
`apply()` stays total: anything that does not fit is recorded in `state.rejected` with the reason.
**Only an explicit `payment.assigned` shares a payment** (`share::shared_payment`). A payment that falls into
a budget as the default is never sent anywhere.
### The split rule
`split_equal(total, people)`: the people are **sorted by id and deduplicated first**, then split with
equal weights by the day-1 largest-remainder `split()`. Every device computes the same shares in whatever
order the people were picked, and the shares always sum to the total. The leftover haléře go to the first
people in id order.
A **share link** is open while its split is not settled for that person and `today <= expires`
(`share_link_open`). The page shows exactly `ShareView { name, amount, merchant, date, spayd }` and nothing else.
## `fiscus-capture`: what the phones send
Both are **hostile input**. Each yields a `Capture { amount (an outflow, negative), date, merchant, card }`
or a typed error, never a partial payment.
**The iPhone Shortcut post.** We write the Shortcut, so this is our format, not a bank's. It is a JSON object
with exactly `amount`, `merchant`, `card`, `time`, plus an optional `currency`. Anything else is an error.
- `amount`: a positive number, or a string in the form Shortcuts writes in Czech or English (`129`,
`129,5`, `1 234,50`, `129.00`, optionally `Kč`/`CZK` before or after). It is parsed from its text, never
as a float. `currency`, if present, must be `CZK`.
- `merchant`: 1–200 characters, no control characters. `card`: 0–60 characters.
- `time`: ISO 8601 with an offset (`2026-11-03T14:05:00+01:00`); the payment's date is the local date in it.
- At most 4 KiB.
*(assumption)* Apple's exact `amount` text is checked against the first real post.
**Android bank notifications.** `recognise(app, title, text, selected)`:
1. If `app` is not one of the bank apps the person selected → `NotSelected`. The listener calls this only for
selected apps; the core checks again.
2. Otherwise each template **for that app** is tried in turn. A template is literal text with `{amount}`,
`{merchant}`, `{card}` and `{_}` holes, matched exactly (no regexes, no fuzziness).
3. No template matches → `Unknown`. The app counts it and shows the count in Settings; it is **never
guessed**.
**The template registry is empty**: no bank notification samples exist yet. Templates are written only from
real samples in `fixtures/notifications/<bank>/` (see `fixtures/README.md`). The engine is tested with
synthetic templates that live only in the tests.
## QR Platba (`fiscus_ledger::pay`)
- `Iban::parse` takes `CZ65 0800 0000 1920 0014 5399` or a Czech account `19-2000145399/0800`. Both checks
are strict: the IBAN's mod-97, and for a Czech account the weighted mod-11 of the prefix and the number.
Only CZ accounts (24 characters).
- `spayd(iban, amount, message, vs)` gives `SPD*1.0*ACC:<IBAN>*AM:<amount>*CC:CZK*MSG:<message>[*X-VS:<vs>]`.
- The amount must be positive. It is written from haléře with two decimals (`450.00`), never through a float.
- The message is at most 60 characters, and `*` is written as `%2A`.
- The variable symbol is 1–10 digits.
## Household duplicates (`fiscus-insight`)
`household_duplicates(&[(member, names)])`: the subscription merchant keys two or more members share, each
with its members. It runs only on names members chose to share into the household group (opt-in, asked once).
Nobody's names are read without that.
`shared_names(state, today)` *(v0.3.0)* is what a member who opted in sends: the **service key** (the first word
of the merchant key, at least three letters) of every subscription they still pay (active, or charged after a
cancel), sorted, at most 100. Only the key leaves: `PAYPAL *SPOTIFY 4029357733` is shared as `spotify`, never
with its merchant text, reference or amount.
+58
View File
@@ -0,0 +1,58 @@
# 03 — Invoices and the tax reserve (v1.1)
`fiscus-ledger::invoice`: issuing invoices (faktury) from the ledger, finding them paid on a statement, and
setting a share of each paid one aside for tax. Pure like the rest: no clock, no randomness; dates and ids are
parameters.
## The supplier
`supplier.set` names who issues invoices: name, address (1–4 lines), IČO, DIČ, whether they are a VAT payer, a
registration line for the invoice, and the reserve: the thousandths of each paid invoice's amount without VAT
set aside for income tax and insurance (0–600, so 0–60 %). A VAT payer must have a DIČ. The latest
`supplier.set` counts from then on; an invoice keeps the supplier it was issued under, so changing the reserve
never changes an invoice issued before.
IČO: 8 digits, the last the weighted mod-11 check of the first seven. DIČ: `CZ` and 8–10 digits.
## An invoice
`invoice.issued` carries the whole invoice: id, number, issue and due dates, the taxable-supply date (DUZP, on a
VAT invoice only), the customer, 1–50 lines, the budget its payment goes into (`None`: the default one), and
the language it is printed in: `cs` or `en`, chosen per invoice (absent: Czech).
- **Number = variable symbol.** `YYYYNNNN`: the year it was issued and its place in that year
(`State::next_invoice_number(year)`). A number is used once. The payment is matched by it.
- **A line:** text (1–200), quantity in thousandths (0,001–1 000 000), unit (≤ 10), unit price in haléře,
and on a VAT invoice a rate of 21, 12 or 0 %. Its amount is `quantity × price`, rounded half away from
zero to the haléř.
- **VAT:** per rate, from the base: the base of a rate is the sum of its lines, its VAT `base × rate / 100`
rounded once (§ 37 ZDPH). Not per line.
- **Total:** 0,01–9 999 999,99 CZK, what QR Platba carries. `State::invoice_spayd` gives the QR Platba of an
unpaid invoice: its total, `X-VS` its number, to the account set by `account.set`.
Every rule is checked when the event is applied; an invoice that breaks one is rejected and changes nothing.
## Paid
`invoice.paid { invoice, payment, on }`: `payment` is the statement line that paid it, or `None` for one marked
paid by hand. A line pays one invoice, only of the invoice's exact total, not before the invoice was issued.
`plan_invoice_payments(state, ids, at)` is what the app runs after an import. For each unpaid invoice, the
earliest statement line whose amount is its total and whose variable symbol is its number (leading zeros do
not count) pays it: `invoice.paid`, then `payment.categorised` → `income` (unless the person chose a category),
then `payment.assigned` → the invoice's budget. Nothing is guessed: a line of another amount, or without the
symbol, stays for the person to look at. Run twice, the second plan is empty.
## The reserve
When an invoice is paid, `reserve = VAT + round(net × reserve‰ / 1000)` is set aside: a VAT payer's VAT in full
(it is the state's), and the reserve share of the rest. `State::reserve_balance()` is everything set aside less
`reserve.withdrawn` (the tax or insurance paid from it), which can never take more than the reserve holds.
## Cancelling
`invoice.cancelled` cancels an unpaid invoice. A paid one stays; a credit note (opravný daňový doklad) is not
built yet.
| Event | Effect |
|:--|:--|
| `supplier.set` | the supplier from now on |
| `invoice.issued` | a new invoice, checked, with its totals |
| `invoice.paid` | paid by a statement line or by hand; the reserve set aside |
| `invoice.cancelled` | an unpaid invoice withdrawn |
| `reserve.withdrawn` | money out of the reserve, at most its balance |
+68
View File
@@ -0,0 +1,68 @@
# 04 — Spending, category plans and the month in numbers (v0.5.0)
Pure like the rest: `today` and the month are parameters. Money in haléře; every share is whole thousandths.
## One definition of spending (`fiscus-insight::spending`)
Spending is money out of your own payments (a confirmed pair once), as positive amounts, by category. Money
between your own accounts (`transfers`) is not spending; a payment nobody categorised counts as `uncategorised`.
Money in is positive payments that are not transfers. Every sum is checked: when one would not fit, the answer
is `None`, never a wrong number.
`permille(parts)` gives each part's share in thousandths by the largest remainder, so the shares add up to
exactly 1000 whenever there is anything to share (a pie never has a gap or an overlap). A tie goes to the
earlier part; callers order the parts first.
## Category plans (`category.planned`, `fiscus-insight::plan`)
`category.planned { category, amount, from }`: the most you mean to spend on a category in a month, from the
month of `from` (always the 1st) on, until a later plan for that category replaces it. You plan once; zero
removes the plan. `State::plan_for(category, month)` is the plan from that month or before, the latest month
first, then the latest in the log.
A plan is for a spending category only: not `income`, `transfers` or `uncategorised`, and a category the
ledger knows (a default one or one of your own). 0 to 100 000 000 CZK.
Plans are in your personal log and count **your own payments only**, like the forecast. They are never shared:
the sharing boundary (`share.rs`, the app's `outgoing`) builds only `payment.shared` and never copies other
events.
`month_plan(state, month, today)`: per planned category, what you spent this month up to today, what is left
(negative when over), the spent share of the plan (capped at 1000, for a bar), and the pace:
| Pace | When |
|:--|:--|
| Over | spent more than the whole month's plan |
| Ahead | more than 110 % of what the plan allows by today (`plan × day / days in month`) |
| On pace | 90–110 % |
| Under | below 90 %; for a past month, within the plan |
Then the categories spent on without a plan (largest first), and the month's totals: planned, spent, and the
part of it spent without a plan. A month that has not begun has nothing spent and no pace.
`suggest(state, today)`: a plan from your history. For each category you can plan, the average spent over the
last three complete months, rounded **up** to whole hundreds of crowns. Only months since your first payment
count, so a ledger one month old is not divided by three.
## Categories of your own (`category.created`)
`category.created { category, label }`: an id as `categories::is_valid` that is not a default category or one
you made before, and a name of 1–40 characters (no spaces around it, no control characters). It can be planned
and used like a default one. `State::category_label` and `State::categories()` (the default ones in their order,
then yours by id) are what the app lists.
## The month in numbers (`fiscus-insight::stats`)
`month_stats(state, insight, month, today)` for a month that has begun (`None` for one to come):
- **slices**: spending by category, the largest 7, then the rest as one slice; thousandths that add up to 1000;
- **out, in, net** (in less out);
- **months**: the last six, oldest first, ending with this one (up to today);
- **same day last month**: spent last month up to the same day (all of it for a past month);
- **top merchants**: the 5 you paid most, by merchant key (however the bank writes the name), with the latest
name and how many payments; a payment without a merchant is not a merchant;
- **subscriptions**: what the subscriptions `analyse` found charged this month, and their share of spending.
## Tests
`fiscus-ledger/tests/plans.rs` (5): a plan carries forward, the latest for a month wins, zero removes it,
every refusal (income, transfers, uncategorised, unknown, not an id, negative, over the limit, not the 1st)
changes nothing, categories of your own and their refusals, the events round-trip and replay the same.
`fiscus-insight/tests/stats.rs` (5) and `spending.rs` (1): the month against its plan with every pace, the
suggested plan, the month in numbers, shares that always add up to 1000, and no numbers when a sum would not
fit. Three deliberate mistakes (transfers as spending, a plan before its month, no largest remainder) each fail
them.
+13
View File
@@ -0,0 +1,13 @@
# Statement samples
Real, **redacted** samples only. One folder per bank (`fixtures/<bank>/`), each sample next to the rows it
must parse to:
```
fixtures/fio/2026-10.csv
fixtures/fio/2026-10.csv.expected.json # a fiscus_statement::Statement as JSON
```
Redact names, account numbers and messages, but keep the file byte-for-byte otherwise: the encoding, the
delimiter, the header, the line endings and the footer are exactly what the parser is built from. A bank
parser is written only from its samples here; a bank with no samples is unsupported.
+22
View File
@@ -0,0 +1,22 @@
# Bank notification samples (Android)
Real, **redacted** notifications only, one folder per bank (`fixtures/notifications/<bank>/`), one JSON file
per notification:
```json
{
"app": "cz.example.bank",
"title": "the notification's title, exactly",
"text": "the notification's text, exactly",
"expected": { "amount": -12950, "merchant": "ALBERT", "card": "*1234" }
}
```
`expected` is `null` for a notification from the bank app that is not a card payment (a balance, a login, an
incoming transfer); it must stay unknown. `amount` is in haléře, negative for a payment.
Redact names, card numbers and balances, but keep every other character: spaces, no-break spaces, the
currency sign and the punctuation are exactly what a template is written from. 3–5 payments per bank app,
plus one or two that are not payments. A template (`fiscus-capture/src/notification.rs`, `TEMPLATES`) is
written only from the samples here; a bank app with no samples is unsupported, and its notifications are
counted as unrecognised, never guessed.