[repo] Merge: feature/core (day 1: ledger, statements, subscriptions, forecast, PR #1)
This commit was merged in pull request #1.
This commit is contained in:
@@ -0,0 +1 @@
|
|||||||
|
target/
|
||||||
Generated
+549
@@ -0,0 +1,549 @@
|
|||||||
|
# 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-insight"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"fiscus-ledger",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fiscus-ledger"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"proptest",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"thiserror",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fiscus-statement"
|
||||||
|
version = "0.1.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
@@ -0,0 +1,15 @@
|
|||||||
|
[workspace]
|
||||||
|
resolver = "2"
|
||||||
|
members = ["crates/fiscus-ledger", "crates/fiscus-statement", "crates/fiscus-insight"]
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
|
version = "0.1.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"
|
||||||
@@ -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.
|
||||||
@@ -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 |
|
||||||
|
| `fiscus-statement` | strict CSV, Czech amount and date fields, decoding; bank parsers only from real samples |
|
||||||
|
| `fiscus-insight` | subscriptions, cancel kits, the forecast |
|
||||||
|
|
||||||
|
Design: [docs/01_core.md](docs/01_core.md). Tests: `cargo test --workspace`.
|
||||||
|
|
||||||
|
Licence: MPL-2.0.
|
||||||
@@ -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
|
||||||
@@ -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()
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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))
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
//! Fiscus Domi's insight: which subscriptions you pay, what changed price, which trial is about to charge,
|
||||||
|
//! how to cancel, and whether the month will stay under its limit. Pure: "today" and seeds are parameters.
|
||||||
|
|
||||||
|
pub mod cancel;
|
||||||
|
pub mod forecast;
|
||||||
|
pub mod subscriptions;
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
//! The categories the app offers. A category is an id; the label is what the app shows.
|
||||||
|
|
||||||
|
pub const UNCATEGORISED: &str = "uncategorised";
|
||||||
|
|
||||||
|
/// `(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)
|
||||||
|
}
|
||||||
@@ -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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
//! 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::money::Haler;
|
||||||
|
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;
|
||||||
|
/// 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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 },
|
||||||
|
#[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 },
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
//! Fiscus Domi's ledger: money in haléře, civil dates, the append-only event log and the state derived from
|
||||||
|
//! it, merchant keys and rules, and capture ↔ statement matching. Pure: no I/O, no clock, no randomness.
|
||||||
|
|
||||||
|
pub mod categories;
|
||||||
|
pub mod date;
|
||||||
|
pub mod event;
|
||||||
|
pub mod import;
|
||||||
|
pub mod matching;
|
||||||
|
pub mod merchant;
|
||||||
|
pub mod money;
|
||||||
|
pub mod state;
|
||||||
|
|
||||||
|
pub use date::{Date, Timestamp};
|
||||||
|
pub use event::{BudgetId, Category, Decision, Event, EventBody, EventId, PaymentId};
|
||||||
|
pub use money::Haler;
|
||||||
|
pub use state::{EffectivePayment, Glyph, Origin, State};
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
@@ -0,0 +1,439 @@
|
|||||||
|
//! 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, Category, Decision, Event, EventBody, EventId, PaymentId, RuleId};
|
||||||
|
use crate::import::StatementLine;
|
||||||
|
use crate::merchant::merchant_key;
|
||||||
|
use crate::money::Haler;
|
||||||
|
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 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: 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>>,
|
||||||
|
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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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 } => {
|
||||||
|
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() {
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"));
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
@@ -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
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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)))
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
@@ -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.
|
||||||
@@ -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.
|
||||||
Reference in New Issue
Block a user