507eb62216
fiscus_capture::receipt::read takes the OCR's lines (words with boxes and confidence in thousandths) and finds the total, date and time, IČO (check digit), DIČ and the shop's name by their labels, never a shop's layout; unsure words mark their field, the shop is always to check; bounded, control characters dropped, a proptest. The phone's post takes a receipt (source receipt, ico, dic). The ledger gains payment.receipt_attached (the payment keeps its merchant and key), known_shop and receipt_match (exactly one candidate or none). docs/07_receipts.md; fixtures/receipts/ waits for redacted samples. v0.9.0.
127 lines
8.9 KiB
Markdown
127 lines
8.9 KiB
Markdown
# 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 |
|
||
| `payment.receipt_attached` | a receipt for the payment: the shop's name, its IČO and DIČ (docs/07_receipts.md); the payment keeps its merchant |
|
||
| `budget.created` / `budget.limit_set` | a monthly budget and its limit |
|
||
| `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.
|