MCP: short connect text, a handbook, tool annotations, safe local imports
- The 13K-character instructions (clients cut them short) become a
connect text of at most 1,400 characters whose first 512 stand alone,
plus books.handbook and books://handbook/{section}: the old guidance by
section, with no helper commands, home paths, pull requests or
file-reading suggestions (tool_text_lint).
- Every tool has a title and read-only/destructive hints; no
requiresUserInteraction anywhere (owner decision 2026-10-16).
- books.import_local_file reads only regular files inside the import
roots (the downloads folder by default, or --import-root), never the
data dir, books dir, vault or the key's folder, no symlink escapes or
hard links, and the file opened must be the file checked.
- The store lock is a tokio mutex taken off the runtime threads.
- get_info refreshes settings first; a bare books://digest reads.
Review fixes (P0 review, 2026-10-16):
- Fail closed: a tokio mutex never poisons and spawn_blocking caught the
panic, so after a panic mid-mutation the server kept serving a Store
behind its journal. A panic (the task, or while holding the store)
now stops the shared store; every later request on every session is
refused with a plain message; a restart re-verifies the journal. The
join error goes through redact_refusal and never carries the panic's
text.
- books.set_w9 w9_file_path read any path (a link named w9.pdf to the
vault key was stored and get_w9 wrote it out): it now goes through the
import roots' lockdown, its type judged on the canonical path.
- Sealed even inside a root: the key file in force, where a linked one
leads, both folders, and the default key folder whatever the settings
say. Refusals check the roots first, so outside them every path gets
one message (no probing what exists); inside, other books-dir files say
to copy them out first.
- The open is O_NOFOLLOW | O_NONBLOCK (a pipe swapped in after the check
can't hang a thread) and must match the checked file's device and
inode. New dependency: libc (unix only), for those two open flags,
which std doesn't name.
- Default import roots are the downloads folder only (the plan); files
with full TINs (get_w9, vendor_1099 include_tins, the CPA package with
TINs) are never written into an import root, and the server refuses to
import any file it wrote with TINs (by SHA-256).
- set_tin and set_w9 overwrite vault records: destructive_hint = true;
annotations_complete pins the key tools' hints. The read-only hint is
checked in behaviour on every spec_mcp call (journal and data-dir files
unchanged).
- Text: the connect text names the settings file as the one local file
to edit, says every entry balances on real accounts and names its
party, says invoice/bill/payment/payroll tools post unchecked, rewords
the exemptions, and shows the company name as one plain line; the
handbook takes section "all", lists its ids in the schema and says to
read contract first; books.settings drops the config.json path and no
error names the data dir or the key file. tool_text_lint covers the
whole tool JSON and resources and bans git/commit/FL-0001; tool
descriptions over 700 characters are pinned to today's eight (P5).
- digest: an empty since= is bare; the default date is pinned on every
day of a month.
Round-2 review fixes (2026-10-16):
- TIN files (B-26): the in-memory, per-session set of TIN-file hashes
became one registry beside the vault (vault/tin-files.sha256, hashes
only), shared by every session and every later server. It holds the
W-9 set_w9 reads (recorded as read), get_w9 copies, 1099 worksheets
with TINs, CPA packages with TINs and each file in one that holds a
TIN; a file is recorded before it is written, and a failure refuses.
import_local_file, attach_receipt and file_document (base64 was never
checked) refuse a recorded file, and a text file (by type, name, or
UTF-8/UTF-16 decoding) holding a full TIN. Not caught: an altered
binary copy; the docs say so (P2/P7 remove the path tools).
- The text check is narrow (owner/engineer decision, 2026-10-16: bank
exports are filed for reconciliation, and has_full_tin's "nine digits
however separated" refused their routing numbers, long references and
dates run into amounts). Text is refused when it holds (a) a TIN the
vault holds for a party, anywhere, as nine digits, 3-2-4 joined by
hyphens, spaces or dots, or 2-7 joined by a hyphen or space, compared
on the server against the decrypted vault and never returned or
logged (a vault that can't be opened leaves (b)); or (b) a stand-alone
printed SSN (123-45-6789) or EIN (12-3456789) shape: no digit, and no
hyphen or dot followed by a digit, beside it. Full-width digits and
Unicode hyphens and spaces read as ASCII. has_full_tin still guards
refusals and results (redact_refusal). Known limit, for P7: a refusal
under (a) tells the agent a text it chose holds a vault TIN.
New dependency: zeroize in ledger-mcp (already in the workspace
through ledger-vault, same major version), so the vault's TINs decoded
for the scan are wiped from memory on drop as the vault's own are.
- Mutation testing of the final P0 diff (docs/testing.md): tests for
each law a survivor broke (handbook titles, a dropped default root, a
.jpg W-9, the waker, the walk's folder flags against a link and a
pipe, the 40-link limit, save paths refused as such, the package
marking only its TIN files, a registry that can't be read, text types,
the short receipt rule's counts and a 12-character code). Simpler
code where only a race could tell: inspect places an existing path by
canonicalize itself (no second comparison), read_checked's read limit
is its one size check, openat fails on -1 as specified. The 25 MiB
upload test removes its 50 MB of books however it ends.
- The GUI's stale-rule prompt no longer says to open a pull request: it
asks the agent to find the figure from the rule's official authority,
confirm it with the human, pass it explicitly, and tell the human so it
can be reported upstream (as the handbook says); a lib test pins it and
bans files, git, GitHub and pull requests from every attention prompt.
- Import roots (local_files.rs INVARIANT 0): XDG_DOWNLOAD_DIR="$HOME/"
made $HOME (or /) the root. No root may be /, the home folder or hold
it, or hold the books, data dir, vault or a key: a named one stops the
server at startup, a default one is dropped; the default falls back to
~/Downloads only if that is a real folder other than $HOME; with no
root, an import says so.
- The read is a component walk from / with openat(O_NOFOLLOW |
O_DIRECTORY) per folder and O_NOFOLLOW | O_NONBLOCK for the file, so a
folder swapped for a link after the check fails; no step may land on a
protected inode (one renamed into a root); dev/ino and nlink stay. No
/proc. Portable to macOS. (libc's openat, two small unsafe blocks.)
- One refusal for missing, dangling and outside paths: resolved()
follows every link, dangling ones too, so a link's target existing or
not no longer changes the answer.
- Sealing: the key files (in force, default) and their targets always;
their folders only when not $HOME, not a root, not holding a root; and
~/.config/wanderbooks whatever XDG_CONFIG_HOME says.
- Agent text (I-12): RuleNotKnown names the authority (IRS, with its
address) and says to tell the human, never a repo path, PR or GitHub;
the digest's stale_rules drop the repo catalog and path for it; vault,
outside-books, STOPPED and local-file refusals name no git, path or
flag. tool_text_lint bans docs/, .md, /home, data dir, --data-dir,
--import-root, vault.key, .jsonl, sqlite, .gitignore, github, pull
request, and also lints every error template (scanned from source),
built error texts, and the server's refusal constants.
- The receipt rule told (ReceiptPolicy::rule) is the one enforced: the
exact threshold in the base currency (no "$", no rounding), required
and exempt accounts, reversals exempt; the connect text fits 1,400
characters by dropping reasons, then codes, never the rule.
- The connect text follows the parties setting; "offer books.digest"
everywhere. shown_name drops Unicode format characters (bidi, zero
width).
- read_only_tools_change_nothing compares file contents, the database
by every row, the vault and the settings file (raw database bytes did
not change either; rows are the stable comparison).
- import_local_file takes the name and type from the canonical path;
the digest's journal repair says when the tail was set aside, not the
journal's file name; "version-history messages" back in the TIN rule;
openWorldHint false on every tool, pinned in annotations_complete.
- Outside the MCP crate, for the same texts: ledger-core's DatedRule
gains `authority` (the statute or publication with its address) and
RuleNotKnown carries it; ledger-store's "sqlite error" reads "database
error"; ledger-config's ReceiptPolicy::rule takes the base currency.
New dev-dependency: rusqlite in ledger-mcp (already in the workspace,
same version and features as ledger-store), to read the database's
rows in read_only_tools_change_nothing.
- The filing scan is no TIN oracle (tin_files.rs INVARIANT 4): text
holding more than two TIN-shaped numbers (any rendering rule (a)
reads) that end in a known TIN's last four (the books' TIN and W-9
facts, via known_tin_last4, before the vault is opened; then the
vault's own) is refused with TIN_PROBE, the same words whether or not
one is the vault's TIN; only one or two candidates are compared
against the vault. Tests: unit
text_probing_for_a_tin_is_refused_alike_whether_or_not_it_holds_it,
one_or_two_candidates_are_compared_against_the_vault; over HTTP
text_probing_for_a_tin_is_refused_alike_by_every_filing_tool.
Plan: plan/served.md P0, section 6 "Immediate hole (P0)", 4.1, 4.3, 4.9.
Review round 3. S1: a panic stops the server for every session, so no
input may reach one. Dates are four-digit years (new ledger_core::
calendar, 0001-01-01..9999-12-31): the MCP's parse_date is strict
YYYY-MM-DD, periods are bounded, last_day_of_month returns a refusal
(server and store); schedules, assets, recurring entries, periods,
documents, disposals and entries refuse dates outside the calendar, and
replay refuses such journal dates. Every amount a command takes is at
most a line's (draft lines by size, document lines, payouts, payroll,
statements, shares, tax basis, proceeds, recurring templates), on
replay too, so sums are exact; the 1099 vendor part and the K-1
property share use checked products (TooLargeToCompute); a recurring
run makes at most 1,000 drafts. tests/hostile_args.rs drives every tool
with schema-derived hostile arguments and every resource with generated
URIs, asserting the server never stops; the audit's panics are pinned.
S2: a `.` or `..` path name is refused as NO_SUCH_FILE up front. S3:
NUL-interleaved UTF-16 without a byte-order mark is scanned both ways.
S4: resource-read refusals are TIN-redacted. S5: set_w9 records its W-9
only once the call passes every check, just before the vault write.
S8: idempotentHint only on verify, run_depreciation, run_schedules,
run_recurring, set_party_roles (a repeat leaves journal and vault
alone; spec_vault checks every candidate twice); every tool's hints
pinned in one table. C1: books.settings lists receipt_required_accounts
and receipt_exempt_accounts uncut. C2: the default company name reads
"a new company". C3: the parties rule names no-party reasons. C4/C5:
the handbook names the settings file only as books.settings' books_toml,
and restores "check books.digest and offer it". C6: an import root
inside the books, data dir or vault is refused at startup. The lint
catches `just` however it ends and where the books are;
digest_resource_bare_reads reads the server's month.
Review round 4 (2026-10-17): round 3's bounds ran in replay too, so
journals main wrote and reopened (an entry dated 0000-06-01 or
+10000-01-01, a draft line of 2e15, an asset ending past 9999, a basis
or share past the line limit, sub-cent document and payroll lines) no
longer opened. Posted is forever: the bounds are the commands' only.
- Replay applies main's rule exactly: parse_date takes any date chrono
reads; replay_add_line(_fx) has no size bound (add_line/add_line_fx
do); replay_register_asset/correct_asset (chrono overflow only),
replay_set_asset_tax_basis (check_journaled), replay_set_entry_parties
(check_shares_journaled), replay_register_recurring
(validate_recurring_journaled), replay_register_schedule (months 1 to
600), replay_create_period (order only), replay_dispose_asset, and no
line, date, payment or payroll range checks in replay_invoice/bill,
their payments and replay_payroll_run.
- Derived figures over such books refuse (TooLargeToCompute,
DateOutOfRange), never panic: amortization plans, depreciation into
chrono's last month (and the true-up for lives past 9999), intervals,
document totals and aging, net pay and payroll plans, money flows and
share resolution, the asset register, receipt-policy debits; the MCP
tools and the viewer show what can't be computed.
- tests/fixtures/old-books: the review's 13 journals, its control and 15
more edges, written by main's Store API with main's figures
(expected.json); every one opens in the writer and the viewer to those
figures, every derived figure computes or refuses, every MCP tool and
GUI page answers; hostile_args restarts the server after each
property; each bound has a command/replay test pair.
Final review: a schedule's plan refuses a total of 10^26 or more
(TooLargeToCompute) instead of letting Decimal round its cents silently,
and a null `remaining` in the schedule output is always explained by
plan_error. Replay is unaffected: no journaled schedule month can belong
to a total that large (the line limit bounds every posted month).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T3gXMVt7XJPi6ens1or9Dj
This commit is contained in:
1 parent
9f9f00ed9a
commit
8693d5a3f5
161 files changed
+18938
-1110
No files matched your search
@@ -9,7 +9,7 @@ use crate::fmt;
|
||||
use crate::nav::Route;
|
||||
use crate::theme::{self, pal};
|
||||
use crate::widgets;
|
||||
use chrono::{Days, NaiveDate};
|
||||
use chrono::{Datelike, Days, NaiveDate};
|
||||
use egui::{CornerRadius, RichText, Sense, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
use ledger_core::analysis::{Interval, balance_history, flows_by_interval, interval_start};
|
||||
@@ -214,12 +214,27 @@ fn runway(ui: &mut Ui, b: &Books) {
|
||||
);
|
||||
ui.add_space(32.0);
|
||||
if net < Decimal::ZERO {
|
||||
let months_left = (b.kpis.cash / -net).round_dp(1);
|
||||
let out = b.today
|
||||
+ Days::new((months_left * Decimal::from(30)).try_into().unwrap_or(0u64));
|
||||
big(ui, "Runway", format!("{months_left} months"), p.text);
|
||||
// Checked: a sub-cent average (lines an earlier version
|
||||
// booked) makes a runway past any calendar.
|
||||
let months_left = b.kpis.cash.checked_div(-net).map(|m| m.round_dp(1));
|
||||
let out = months_left
|
||||
.and_then(|m| m.checked_mul(Decimal::from(30)))
|
||||
.and_then(|d| u64::try_from(d).ok())
|
||||
.and_then(|d| b.today.checked_add_days(Days::new(d)));
|
||||
big(
|
||||
ui,
|
||||
"Runway",
|
||||
months_left
|
||||
.map_or_else(|| fmt::CANT_COMPUTE.into(), |m| format!("{m} months")),
|
||||
p.text,
|
||||
);
|
||||
ui.add_space(32.0);
|
||||
big(ui, "Cash runs out around", fmt::month(out), p.warning);
|
||||
big(
|
||||
ui,
|
||||
"Cash runs out around",
|
||||
out.map_or_else(|| "beyond any calendar date".into(), fmt::month),
|
||||
p.warning,
|
||||
);
|
||||
} else {
|
||||
big(ui, "Runway", "Cash is growing".into(), p.positive);
|
||||
}
|
||||
@@ -238,10 +253,46 @@ fn runway(ui: &mut Ui, b: &Books) {
|
||||
);
|
||||
}
|
||||
|
||||
/// A recurring entry's ungenerated occurrences dated `from..=to` (and on
|
||||
/// or before its end), found from the occurrence just before `from`
|
||||
/// rather than walking from its start: a weekly entry an earlier version
|
||||
/// started at chrono's first day has millions of occurrences before today,
|
||||
/// and this runs every frame.
|
||||
fn occurrences_from(
|
||||
r: &ledger_core::RecurringEntry,
|
||||
from: NaiveDate,
|
||||
to: NaiveDate,
|
||||
) -> Vec<NaiveDate> {
|
||||
use ledger_core::Frequency;
|
||||
let last = r.end.map_or(to, |e| e.min(to));
|
||||
// How many periods from the start to `from`, rounded down, less one
|
||||
// for a month-end clamp: never past the first occurrence on or after
|
||||
// `from`.
|
||||
let months = |d: NaiveDate| {
|
||||
(i64::from(d.year()) - i64::from(r.start.year())) * 12 + i64::from(d.month())
|
||||
- i64::from(r.start.month())
|
||||
};
|
||||
let k0 = match r.frequency {
|
||||
Frequency::Weekly => (from - r.start).num_days() / 7,
|
||||
Frequency::Monthly => months(from),
|
||||
Frequency::Quarterly => months(from) / 3,
|
||||
Frequency::Yearly => months(from) / 12,
|
||||
} - 1;
|
||||
let Ok(k0) = u32::try_from(k0.max(0)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
(k0..)
|
||||
.map_while(|k| r.frequency.nth(r.start, k).filter(|d| *d <= last))
|
||||
.filter(|d| *d >= from && !r.generated.contains(d))
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct Upcoming {
|
||||
date: NaiveDate,
|
||||
label: String,
|
||||
amount: Decimal,
|
||||
/// None: it can't be computed exactly (a recurring template or a
|
||||
/// document an earlier version journaled, past exact arithmetic).
|
||||
amount: Option<Decimal>,
|
||||
route: Option<Route>,
|
||||
}
|
||||
|
||||
@@ -250,23 +301,18 @@ fn coming_up(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
let horizon = b.today + Days::new(45);
|
||||
let mut items: Vec<Upcoming> = Vec::new();
|
||||
for r in b.ledger.recurring_entries() {
|
||||
let cash: Decimal = r
|
||||
let cash = r
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|(a, _, _)| b.cash_accounts.contains(a))
|
||||
.map(|(_, s, m)| {
|
||||
.try_fold(Decimal::ZERO, |sum, (_, s, m)| {
|
||||
if *s == ledger_core::Side::Debit {
|
||||
m.amount
|
||||
sum.checked_add(m.amount)
|
||||
} else {
|
||||
-m.amount
|
||||
sum.checked_sub(m.amount)
|
||||
}
|
||||
})
|
||||
.sum();
|
||||
for d in r
|
||||
.due(horizon)
|
||||
.into_iter()
|
||||
.filter(|d| *d > b.today - Days::new(1))
|
||||
{
|
||||
});
|
||||
for d in occurrences_from(r, b.today, horizon) {
|
||||
items.push(Upcoming {
|
||||
date: d,
|
||||
label: format!("{} (recurring)", r.description),
|
||||
@@ -275,43 +321,51 @@ fn coming_up(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
});
|
||||
}
|
||||
}
|
||||
// An open document: its balance, or None when it can't be computed
|
||||
// (shown as such, never left out).
|
||||
for id in 1..b.ledger.next_invoice_id() {
|
||||
if let Some(inv) = b.ledger.get_invoice(id)
|
||||
&& !inv.balance().is_zero()
|
||||
{
|
||||
let who = b
|
||||
.ledger
|
||||
.get_customer(inv.customer_id)
|
||||
.map(|c| c.name.clone())
|
||||
.unwrap_or_default();
|
||||
let late = inv.due_date < b.today;
|
||||
items.push(Upcoming {
|
||||
date: inv.due_date,
|
||||
label: format!(
|
||||
"Invoice {id} from {who}{}",
|
||||
if late { " — overdue" } else { "" }
|
||||
),
|
||||
amount: inv.balance(),
|
||||
route: Some(Route::Entry(inv.entry_id)),
|
||||
});
|
||||
let Some(inv) = b.ledger.get_invoice(id) else {
|
||||
continue;
|
||||
};
|
||||
let balance = inv.balance().ok();
|
||||
if balance.is_some_and(|x| x.is_zero()) {
|
||||
continue;
|
||||
}
|
||||
let who = b
|
||||
.ledger
|
||||
.get_customer(inv.customer_id)
|
||||
.map(|c| c.name.clone())
|
||||
.unwrap_or_default();
|
||||
let late = inv.due_date < b.today;
|
||||
items.push(Upcoming {
|
||||
date: inv.due_date,
|
||||
label: format!(
|
||||
"Invoice {id} from {who}{}",
|
||||
if late { " — overdue" } else { "" }
|
||||
),
|
||||
amount: balance,
|
||||
route: Some(Route::Entry(inv.entry_id)),
|
||||
});
|
||||
}
|
||||
for id in 1..b.ledger.next_bill_id() {
|
||||
if let Some(bill) = b.ledger.get_bill(id)
|
||||
&& !bill.balance().is_zero()
|
||||
{
|
||||
let who = b
|
||||
.ledger
|
||||
.get_vendor(bill.vendor_id)
|
||||
.map(|v| v.name.clone())
|
||||
.unwrap_or_default();
|
||||
items.push(Upcoming {
|
||||
date: bill.due_date,
|
||||
label: format!("Bill {id} to {who}"),
|
||||
amount: -bill.balance(),
|
||||
route: Some(Route::Entry(bill.entry_id)),
|
||||
});
|
||||
let Some(bill) = b.ledger.get_bill(id) else {
|
||||
continue;
|
||||
};
|
||||
let balance = bill.balance().ok();
|
||||
if balance.is_some_and(|x| x.is_zero()) {
|
||||
continue;
|
||||
}
|
||||
let who = b
|
||||
.ledger
|
||||
.get_vendor(bill.vendor_id)
|
||||
.map(|v| v.name.clone())
|
||||
.unwrap_or_default();
|
||||
items.push(Upcoming {
|
||||
date: bill.due_date,
|
||||
label: format!("Bill {id} to {who}"),
|
||||
amount: balance.map(|x| -x),
|
||||
route: Some(Route::Entry(bill.entry_id)),
|
||||
});
|
||||
}
|
||||
items.sort_by_key(|i| i.date);
|
||||
let mut go = None;
|
||||
@@ -335,19 +389,22 @@ fn coming_up(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
);
|
||||
return;
|
||||
}
|
||||
let (inflow, outflow): (Decimal, Decimal) =
|
||||
items.iter().fold((Decimal::ZERO, Decimal::ZERO), |a, i| {
|
||||
if i.amount > Decimal::ZERO {
|
||||
(a.0 + i.amount, a.1)
|
||||
} else {
|
||||
(a.0, a.1 - i.amount)
|
||||
// None: an item, or the sum, can't be computed exactly.
|
||||
let (inflow, outflow) = items.iter().fold(
|
||||
(Some(Decimal::ZERO), Some(Decimal::ZERO)),
|
||||
|(inflow, outflow), i| match i.amount {
|
||||
Some(a) if a > Decimal::ZERO => {
|
||||
(inflow.and_then(|x| x.checked_add(a)), outflow)
|
||||
}
|
||||
});
|
||||
Some(a) => (inflow, outflow.and_then(|x| x.checked_sub(a))),
|
||||
None => (None, None),
|
||||
},
|
||||
);
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
"Expected in {} · expected out {}",
|
||||
fmt::dollars(inflow),
|
||||
fmt::dollars(outflow)
|
||||
fmt::dollars_or(inflow),
|
||||
fmt::dollars_or(outflow)
|
||||
))
|
||||
.font(theme::semibold(13.0)),
|
||||
);
|
||||
@@ -378,10 +435,11 @@ fn coming_up(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
p.text,
|
||||
r.width() - 70.0 - 130.0,
|
||||
);
|
||||
let (txt, c) = if it.amount > Decimal::ZERO {
|
||||
(format!("+{}", fmt::money(it.amount)), p.positive)
|
||||
} else {
|
||||
(fmt::money(it.amount), p.text)
|
||||
let (txt, c) = match it.amount {
|
||||
Some(a) if a > Decimal::ZERO => {
|
||||
(format!("+{}", fmt::money(a)), p.positive)
|
||||
}
|
||||
a => (fmt::money_or(a), p.text),
|
||||
};
|
||||
ui.painter().text(
|
||||
r.right_center() - vec2(6.0, 0.0),
|
||||
@@ -411,7 +469,7 @@ fn biggest_outflows(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
.filter(|e| {
|
||||
e.status == ledger_core::EntryStatus::Posted
|
||||
&& e.date > since
|
||||
&& e.cash_effect < Decimal::ZERO
|
||||
&& e.cash_effect.is_some_and(|c| c < Decimal::ZERO)
|
||||
})
|
||||
.collect();
|
||||
out.sort_by_key(|e| e.cash_effect);
|
||||
@@ -449,7 +507,7 @@ fn biggest_outflows(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
ui.painter().text(
|
||||
r.right_center() - vec2(6.0, 0.0),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
fmt::money(e.cash_effect),
|
||||
fmt::money_or(e.cash_effect),
|
||||
theme::semibold(13.0),
|
||||
p.text,
|
||||
);
|
||||
@@ -463,3 +521,207 @@ fn biggest_outflows(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
shell.go(Route::Entry(id));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ledger_core::{Frequency, RecurringEntry};
|
||||
|
||||
fn d(y: i32, m: u32, day: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(y, m, day).unwrap()
|
||||
}
|
||||
|
||||
/// occurrences_from is the recurring entry's due dates in the window,
|
||||
/// exactly, without walking from the start: month ends clamped, ends
|
||||
/// and generated dates honored, a start after the window, and a start
|
||||
/// at chrono's first day.
|
||||
#[test]
|
||||
fn occurrences_in_a_window_are_the_due_dates_in_it() {
|
||||
for frequency in [
|
||||
Frequency::Weekly,
|
||||
Frequency::Monthly,
|
||||
Frequency::Quarterly,
|
||||
Frequency::Yearly,
|
||||
] {
|
||||
for start in [
|
||||
d(2020, 1, 31),
|
||||
d(2024, 2, 29),
|
||||
d(2026, 1, 10),
|
||||
d(2026, 10, 20),
|
||||
d(2027, 1, 1),
|
||||
d(2027, 1, 15),
|
||||
] {
|
||||
for (end, (from, to)) in [None, Some(d(2026, 11, 2))].into_iter().flat_map(|end| {
|
||||
// Windows a few weeks long, years long, and one
|
||||
// opening before the entry starts.
|
||||
[
|
||||
(d(2026, 10, 17), d(2026, 12, 1)),
|
||||
(d(2026, 6, 1), d(2028, 12, 31)),
|
||||
(d(2025, 12, 20), d(2027, 12, 31)),
|
||||
]
|
||||
.map(|w| (end, w))
|
||||
}) {
|
||||
let mut r = RecurringEntry {
|
||||
id: 1,
|
||||
description: "x".into(),
|
||||
lines: vec![],
|
||||
frequency,
|
||||
start,
|
||||
end,
|
||||
generated: Default::default(),
|
||||
};
|
||||
if let Some(first) = frequency.nth(start, 3) {
|
||||
r.generated.insert(first);
|
||||
}
|
||||
let want: Vec<NaiveDate> =
|
||||
r.due(to).into_iter().filter(|x| *x >= from).collect();
|
||||
assert_eq!(
|
||||
occurrences_from(&r, from, to),
|
||||
want,
|
||||
"{frequency:?} {start} {end:?} {from}..{to}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let far = RecurringEntry {
|
||||
id: 1,
|
||||
description: "weekly since chrono's first day".into(),
|
||||
lines: vec![],
|
||||
frequency: Frequency::Weekly,
|
||||
start: NaiveDate::MIN,
|
||||
end: None,
|
||||
generated: Default::default(),
|
||||
};
|
||||
let got = occurrences_from(&far, d(2026, 10, 17), d(2026, 11, 30));
|
||||
assert!((6..=7).contains(&got.len()), "{got:?}");
|
||||
assert!(got.iter().all(|x| x.weekday() == NaiveDate::MIN.weekday()));
|
||||
}
|
||||
|
||||
/// The cash page's burn and runway, from the last three full months:
|
||||
/// burning $1,000.00 a month on $7,000.00 is a 7-month runway, out
|
||||
/// around May 2027 (210 days from Oct 15); an average of zero is cash
|
||||
/// growing, not a runway past any date.
|
||||
#[test]
|
||||
fn runway_is_cash_over_the_average_burn() {
|
||||
use crate::test_support::{Build, find, render};
|
||||
let mut b = Build::new("runway");
|
||||
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
|
||||
b.post(d(2026, 1, 2), cash, capital, 1_000_000);
|
||||
for m in [7, 8, 9] {
|
||||
b.post(d(2026, m, 10), rent, cash, 100_000);
|
||||
}
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, p) = render(books, Route::Cash, |_| {});
|
||||
let net = find(&texts, &fmt::dollars(Decimal::new(-100_000, 2)));
|
||||
assert_eq!(net.color, p.negative);
|
||||
find(&texts, "Runway");
|
||||
find(&texts, "7 months");
|
||||
find(&texts, "May 2027");
|
||||
// Zero on average: growing (July out, August in, September quiet).
|
||||
let mut b = Build::new("runway-flat");
|
||||
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
|
||||
b.post(d(2026, 1, 2), cash, capital, 1_000_000);
|
||||
b.post(d(2026, 7, 10), rent, cash, 100_000);
|
||||
b.post(d(2026, 8, 10), cash, capital, 100_000);
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, p) = render(books, Route::Cash, |_| {});
|
||||
assert_eq!(find(&texts, "Cash is growing").color, p.positive);
|
||||
assert!(!crate::test_support::has(
|
||||
&texts,
|
||||
"beyond any calendar date"
|
||||
));
|
||||
}
|
||||
|
||||
/// "Coming up" lists recurring cash (its cash lines' sign: rent paid
|
||||
/// out is negative, a recurring entry moving no cash zero, never
|
||||
/// "+0.00"), open invoices (overdue only when due before today) and
|
||||
/// open bills (negative), sorted by date, with the expected in and out.
|
||||
#[test]
|
||||
fn coming_up_is_what_cash_expects() {
|
||||
use crate::test_support::{Build, cents, find, has, render};
|
||||
use ledger_core::arap::DocumentLine;
|
||||
use ledger_core::{AccountType, Currency, Frequency, Money, NewRecurring, Side};
|
||||
let mut b = Build::new("coming-up");
|
||||
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
|
||||
let accrued =
|
||||
b.s.add_account("2000", "Accrued", AccountType::Liability, None, false)
|
||||
.unwrap();
|
||||
b.post(d(2026, 1, 2), cash, capital, 1_000_000);
|
||||
let usd = |c: i64| Money::new(cents(c), Currency::USD);
|
||||
for (what, cr, c, day) in [("Rent", cash, 50_000, 20), ("Accrual", accrued, 5_000, 25)] {
|
||||
b.s.register_recurring(NewRecurring {
|
||||
description: what.into(),
|
||||
lines: vec![(rent, Side::Debit, usd(c)), (cr, Side::Credit, usd(c))],
|
||||
frequency: Frequency::Monthly,
|
||||
start: d(2026, 1, day),
|
||||
end: None,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
let line = |c: i64| {
|
||||
vec![DocumentLine {
|
||||
description: "work".into(),
|
||||
amount: cents(c),
|
||||
}]
|
||||
};
|
||||
let acme = b.s.add_customer("Acme").unwrap();
|
||||
let beta = b.s.add_customer("Beta").unwrap();
|
||||
b.s.create_invoice(acme, d(2026, 9, 1), d(2026, 10, 1), line(120_000))
|
||||
.unwrap();
|
||||
b.s.create_invoice(beta, d(2026, 10, 1), d(2026, 10, 15), line(20_000))
|
||||
.unwrap();
|
||||
let supplier = b.s.add_vendor("Supplier").unwrap();
|
||||
b.s.create_bill(supplier, d(2026, 10, 1), d(2026, 11, 5), line(30_000))
|
||||
.unwrap();
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, p) = render(books, Route::Cash, |_| {});
|
||||
find(&texts, "Coming up");
|
||||
find(&texts, "Invoice 1 from Acme \u{2014} overdue");
|
||||
find(&texts, "Invoice 2 from Beta");
|
||||
find(&texts, "Bill 1 to Supplier");
|
||||
find(
|
||||
&texts,
|
||||
"Expected in $1,400.00 \u{b7} expected out $1,300.00",
|
||||
);
|
||||
let plus = |c: i64| format!("+{}", fmt::money(cents(c)));
|
||||
assert_eq!(find(&texts, &plus(120_000)).color, p.positive);
|
||||
assert_eq!(find(&texts, &plus(20_000)).color, p.positive);
|
||||
assert_eq!(find(&texts, &fmt::money(cents(-50_000))).color, p.text);
|
||||
assert_eq!(find(&texts, &fmt::money(cents(-30_000))).color, p.text);
|
||||
assert_eq!(find(&texts, &fmt::money(Decimal::ZERO)).color, p.text);
|
||||
assert!(!has(&texts, &plus(0)));
|
||||
assert!(!has(&texts, &plus(50_000)));
|
||||
assert!(!has(&texts, &plus(30_000)));
|
||||
}
|
||||
|
||||
/// "Biggest payments": posted entries of the last 30 days that took
|
||||
/// cash out, never older ones, deposits, or drafts.
|
||||
#[test]
|
||||
fn biggest_payments_are_recent_posted_outflows() {
|
||||
use crate::test_support::{Build, find, has, render};
|
||||
let mut b = Build::new("outflows");
|
||||
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
|
||||
b.post_as("Opening", d(2026, 1, 2), cash, capital, 1_000_000);
|
||||
b.post_as("Old rent", d(2026, 9, 10), rent, cash, 25_000);
|
||||
b.post_as("October rent", d(2026, 10, 1), rent, cash, 25_000);
|
||||
b.post_as("Deposit", d(2026, 10, 5), cash, capital, 5_000);
|
||||
b.draft("Draft pay", d(2026, 10, 10), rent, cash, 7_000);
|
||||
// Thirty days before today exactly: not in the last 30 days.
|
||||
b.post_as("Edge payment", d(2026, 9, 15), rent, cash, 9_000);
|
||||
// An expense the owner paid: no cash out.
|
||||
b.post_as("Owner paid", d(2026, 10, 12), rent, capital, 4_000);
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, _) = render(books, Route::Cash, |_| {});
|
||||
find(&texts, "Biggest payments, last 30 days");
|
||||
find(&texts, "October rent");
|
||||
for gone in [
|
||||
"Old rent",
|
||||
"Deposit",
|
||||
"Draft pay",
|
||||
"Edge payment",
|
||||
"Owner paid",
|
||||
] {
|
||||
assert!(!has(&texts, gone), "{gone}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user