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/WL-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:
161 files changed
+18938
-1110
No files matched your search
@@ -16,6 +16,22 @@ use ledger_core::reports::profit_and_loss_for_period;
|
||||
use ledger_core::{AccountType, EntryStatus, PeriodStatus, vendor_1099_report};
|
||||
use rust_decimal::Decimal;
|
||||
|
||||
/// A figure the books can't compute (rules.md B-28: books an earlier
|
||||
/// version wrote may hold dates past chrono's calendar or amounts past
|
||||
/// exact arithmetic): a Problem saying so and why, never a guess.
|
||||
fn cant_compute(what: String, why: &ledger_core::LedgerError, target: Option<Route>) -> Attention {
|
||||
Attention {
|
||||
severity: Severity::Problem,
|
||||
title: format!("{what} can't be computed"),
|
||||
detail: format!("{why}."),
|
||||
target,
|
||||
prompt: format!(
|
||||
"In wanderbooks, {} can't be computed ({why}). Find the record behind it and tell me how to correct it.",
|
||||
what.to_lowercase()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything the books need, as items to show.
|
||||
///
|
||||
/// ```text
|
||||
@@ -61,7 +77,11 @@ use rust_decimal::Decimal;
|
||||
/// amortization: no counterparty by nature) (one item: Info under
|
||||
/// suggest, Todo under require; its prompt names
|
||||
/// books.set_entry_party).
|
||||
/// 3. Nothing else: books with none of those yield no items.
|
||||
/// 3. Nothing else: books with none of those yield no items, except
|
||||
/// that a figure behind an item that can't be computed (an
|
||||
/// amortization plan past chrono's last day, an aging past exact
|
||||
/// arithmetic: books an earlier version wrote, rules.md B-28) is one
|
||||
/// Problem item saying so, never a panic or a guess.
|
||||
/// 4. Every item's prompt starts "In wanderbooks," or names
|
||||
/// wanderbooks, and its amounts are the books' exact amounts.
|
||||
/// ```
|
||||
@@ -77,14 +97,14 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
"#{} · {} · {}. Drafts appear in no report until posted.",
|
||||
e.id,
|
||||
fmt::date(e.date),
|
||||
fmt::dollars(e.amount)
|
||||
fmt::dollars_or(e.amount)
|
||||
),
|
||||
target: Some(Route::Entry(e.id)),
|
||||
prompt: format!(
|
||||
"In wanderbooks, review draft entry {} (\"{}\", {}): attach its receipt if it needs one, preview it, and post it if it's right.",
|
||||
e.id,
|
||||
e.description,
|
||||
fmt::dollars(e.amount)
|
||||
fmt::dollars_or(e.amount)
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -95,7 +115,9 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
.filter(|e| e.status == EntryStatus::Posted && e.missing_receipt)
|
||||
.collect();
|
||||
if missing.len() > 3 {
|
||||
let total: Decimal = missing.iter().map(|e| e.amount).sum();
|
||||
let total = missing
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |t, e| t.checked_add(e.amount?));
|
||||
let list: Vec<String> = missing
|
||||
.iter()
|
||||
.map(|e| format!("{} ({}, {})", e.id, e.description, e.date))
|
||||
@@ -105,7 +127,7 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
title: format!("{} without receipts", fmt::count(missing.len(), "entry", "entries")),
|
||||
detail: format!(
|
||||
"{} in entries with no receipt attached ({}).",
|
||||
fmt::dollars(total),
|
||||
fmt::dollars_or(total),
|
||||
b.receipt_rule()
|
||||
),
|
||||
target: Some(Route::Transactions),
|
||||
@@ -123,7 +145,7 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
"#{} · {} · {}: {}.",
|
||||
e.id,
|
||||
fmt::date(e.date),
|
||||
fmt::dollars(e.amount),
|
||||
fmt::dollars_or(e.amount),
|
||||
b.receipt_rule()
|
||||
),
|
||||
target: Some(Route::Entry(e.id)),
|
||||
@@ -131,7 +153,7 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
"In wanderbooks, entry {} (\"{}\", {} on {}) has no receipt. Find it and attach it with books.attach_receipt.",
|
||||
e.id,
|
||||
e.description,
|
||||
fmt::dollars(e.amount),
|
||||
fmt::dollars_or(e.amount),
|
||||
e.date
|
||||
),
|
||||
});
|
||||
@@ -157,9 +179,31 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
}
|
||||
|
||||
for s in b.ledger.schedules() {
|
||||
let due = s.due(today);
|
||||
// A schedule an earlier version journaled may not compute (its
|
||||
// months past chrono's last day): say so, never guess.
|
||||
let due = match s.due(today) {
|
||||
Ok(due) => due,
|
||||
Err(e) => {
|
||||
out.push(cant_compute(
|
||||
format!("Amortization schedule \"{}\"", s.description),
|
||||
&e,
|
||||
Some(Route::Company),
|
||||
));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if !due.is_empty() {
|
||||
let total: Decimal = due.iter().map(|(_, a)| *a).sum();
|
||||
let Some(total) = due
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |t, (_, a)| t.checked_add(*a))
|
||||
else {
|
||||
out.push(cant_compute(
|
||||
format!("Amortization schedule \"{}\"", s.description),
|
||||
&ledger_core::LedgerError::TooLargeToCompute("the months due".into()),
|
||||
Some(Route::Company),
|
||||
));
|
||||
continue;
|
||||
};
|
||||
out.push(Attention {
|
||||
severity: Severity::Todo,
|
||||
title: format!("Amortization due: {}", s.description),
|
||||
@@ -230,7 +274,9 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
}
|
||||
|
||||
// Rules set by law that wanderbooks may no longer know (rules.md;
|
||||
// Stephen, 2026-10-13): research or ask, then update them for everyone.
|
||||
// Stephen, 2026-10-13): the agent finds the figure from the authority
|
||||
// or asks, confirms it, and passes it explicitly (the handbook's
|
||||
// "Rules that change with the law"); the human reports it upstream.
|
||||
for rule in ledger_core::rules::stale_rules(today) {
|
||||
out.push(Attention {
|
||||
severity: Severity::Todo,
|
||||
@@ -241,8 +287,8 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
),
|
||||
target: None,
|
||||
prompt: format!(
|
||||
"wanderbooks' {} is known only through {}. Find the current figure from the official source (see {} in the wanderbooks repo), or ask me or our CPA, and tell me what you found. Then update the rule for everyone: open a pull request at https://github.com/swaits/wanderbooks with the new value and its official source (or at least an issue).",
|
||||
rule.name, rule.known_through, rule.source
|
||||
"In wanderbooks, the {} is known only through {}. Find the current figure from the official authority, {}, or ask me or our CPA, and confirm it with me; then pass it explicitly wherever a tool asks for it. Tell me what you found and its official source, so I can report it upstream and the rule is updated for everyone.",
|
||||
rule.name, rule.known_through, rule.authority
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -309,15 +355,39 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
});
|
||||
}
|
||||
|
||||
let overdue = |rows: Vec<ledger_core::AgingRow>| -> (usize, Decimal) {
|
||||
let late: Vec<Decimal> = rows
|
||||
// Overdue: (parties, total), or why it can't be computed (documents
|
||||
// are restored as journaled, of any size).
|
||||
let overdue = |rows: Result<Vec<ledger_core::AgingRow>, ledger_core::LedgerError>| {
|
||||
let too_large = || ledger_core::LedgerError::TooLargeToCompute("the overdue total".into());
|
||||
let late: Vec<Decimal> = rows?
|
||||
.iter()
|
||||
.map(|r| r.days_30 + r.days_60 + r.days_90 + r.days_90_plus)
|
||||
.map(|r| {
|
||||
[r.days_60, r.days_90, r.days_90_plus]
|
||||
.into_iter()
|
||||
.try_fold(r.days_30, Decimal::checked_add)
|
||||
.ok_or_else(too_large)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.filter(|d| !d.is_zero())
|
||||
.collect();
|
||||
(late.len(), late.iter().sum())
|
||||
let total = late
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |t, d| t.checked_add(*d))
|
||||
.ok_or_else(too_large)?;
|
||||
Ok::<_, ledger_core::LedgerError>((late.len(), total))
|
||||
};
|
||||
let (n, total) = match overdue(b.ledger.ap_aging(today)) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
out.push(cant_compute(
|
||||
"The payables aging".into(),
|
||||
&e,
|
||||
Some(Route::Reports(crate::nav::ReportKind::ApAging)),
|
||||
));
|
||||
(0, Decimal::ZERO)
|
||||
}
|
||||
};
|
||||
let (n, total) = overdue(b.ledger.ap_aging(today));
|
||||
if n > 0 {
|
||||
out.push(Attention {
|
||||
severity: Severity::Problem,
|
||||
@@ -330,7 +400,17 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
prompt: "In wanderbooks, show me the A/P aging and which bills are past due.".into(),
|
||||
});
|
||||
}
|
||||
let (n, total) = overdue(b.ledger.ar_aging(today));
|
||||
let (n, total) = match overdue(b.ledger.ar_aging(today)) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
out.push(cant_compute(
|
||||
"The receivables aging".into(),
|
||||
&e,
|
||||
Some(Route::Reports(crate::nav::ReportKind::ArAging)),
|
||||
));
|
||||
(0, Decimal::ZERO)
|
||||
}
|
||||
};
|
||||
if n > 0 {
|
||||
out.push(Attention {
|
||||
severity: Severity::Problem,
|
||||
@@ -433,8 +513,20 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
}
|
||||
}
|
||||
|
||||
let due = b.depreciation_due(today);
|
||||
if due.amount > Decimal::ZERO {
|
||||
// The register computes unless a contributor basis an earlier version
|
||||
// journaled is past exact arithmetic: then one item says so.
|
||||
let (due, register) = match (b.depreciation_due(today), b.asset_register(today)) {
|
||||
(Ok(due), Ok(register)) => (Some(due), Some(register)),
|
||||
(Err(e), _) | (_, Err(e)) => {
|
||||
out.push(cant_compute(
|
||||
"The fixed asset register".into(),
|
||||
&e,
|
||||
Some(Route::Reports(crate::nav::ReportKind::FixedAssetRegister)),
|
||||
));
|
||||
(None, None)
|
||||
}
|
||||
};
|
||||
if let Some(due) = due.filter(|d| d.amount > Decimal::ZERO) {
|
||||
let months = if due.periods.is_empty() {
|
||||
"every month not yet posted".to_string()
|
||||
} else {
|
||||
@@ -456,8 +548,7 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
),
|
||||
});
|
||||
}
|
||||
let register = b.asset_register(today);
|
||||
let unregistered = register.unregistered_cost();
|
||||
let unregistered = register.map_or(Decimal::ZERO, |r| r.unregistered_cost());
|
||||
if !unregistered.is_zero() {
|
||||
let (title, why) = if unregistered > Decimal::ZERO {
|
||||
(
|
||||
@@ -569,3 +660,80 @@ pub fn find(b: &Books) -> Vec<Attention> {
|
||||
out.sort_by_key(|a| a.severity);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Empty books opened as of `today`.
|
||||
fn books(tag: &str, today: chrono::NaiveDate) -> Books {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("ledger-gui-attention-{}-{tag}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let data_dir = dir.join("books-data");
|
||||
ledger_store::Store::create(&data_dir, ledger_core::Currency::USD).unwrap();
|
||||
let b = crate::data::load_once(&crate::data::Source {
|
||||
data_dir,
|
||||
books_toml: None,
|
||||
today: Some(today),
|
||||
})
|
||||
.unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
b
|
||||
}
|
||||
|
||||
/// INVARIANTS 2 and 4: a dated rule past its review is one Todo item
|
||||
/// whose prompt asks the agent to find the figure from the official
|
||||
/// authority (named, never the repo's copy), confirm it with the human
|
||||
/// and pass it explicitly, and to tell the human so it can be reported
|
||||
/// upstream; before the review there is no such item. No prompt points
|
||||
/// the agent at files, git, GitHub or pull requests.
|
||||
#[test]
|
||||
fn a_stale_rule_asks_for_the_authority_and_the_humans_confirmation() {
|
||||
let rule = ledger_core::rules::THRESHOLD_1099;
|
||||
let review = rule.review_after();
|
||||
assert!(
|
||||
find(&books("fresh", review.pred_opt().unwrap()))
|
||||
.iter()
|
||||
.all(|a| !a.title.contains(rule.name)),
|
||||
"no item before the review date"
|
||||
);
|
||||
let items = find(&books("stale", review));
|
||||
let stale: Vec<_> = items
|
||||
.iter()
|
||||
.filter(|a| a.title == format!("Check the {}", rule.name))
|
||||
.collect();
|
||||
assert_eq!(stale.len(), 1, "{items:?}");
|
||||
let a = stale[0];
|
||||
assert_eq!(a.severity, Severity::Todo);
|
||||
assert!(
|
||||
a.detail.contains(&rule.known_through.to_string()),
|
||||
"{}",
|
||||
a.detail
|
||||
);
|
||||
for want in [
|
||||
"In wanderbooks,",
|
||||
rule.name,
|
||||
&rule.known_through.to_string(),
|
||||
rule.authority,
|
||||
"confirm it with me",
|
||||
"pass it explicitly",
|
||||
"report it upstream",
|
||||
] {
|
||||
assert!(a.prompt.contains(want), "{want:?} missing: {}", a.prompt);
|
||||
}
|
||||
for item in &items {
|
||||
let lower = item.prompt.to_lowercase();
|
||||
for never in ["pull request", ".md", "docs/", rule.source] {
|
||||
assert!(!lower.contains(never), "{never:?} in {}", item.prompt);
|
||||
}
|
||||
for word in lower.split(|c: char| !c.is_alphanumeric()) {
|
||||
assert!(
|
||||
!["git", "github", "repo", "repository", "issue"].contains(&word),
|
||||
"{word:?} in {}",
|
||||
item.prompt
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+132
-69
@@ -9,7 +9,8 @@ use ledger_core::analysis::{balance_history, balance_series};
|
||||
use ledger_core::reports::{balance_sheet_as_of, profit_and_loss_for_period};
|
||||
use ledger_core::{
|
||||
AccountId, AccountType, AssetId, AssetRegister, AssetStatus, BillId, EntryId, EntryStatus,
|
||||
InvoiceId, Ledger, Party, PartyId, PayrollRunId, Side, Vendor1099Line, fixed_asset_register,
|
||||
InvoiceId, Ledger, LedgerError, Party, PartyId, PayrollRunId, Side, Vendor1099Line,
|
||||
fixed_asset_register,
|
||||
};
|
||||
use ledger_store::{Attachment, JournalLine, Reconciliation, Snapshot, Statement, Subject};
|
||||
use rust_decimal::Decimal;
|
||||
@@ -26,8 +27,10 @@ pub struct EntryInfo {
|
||||
pub date: NaiveDate,
|
||||
pub description: String,
|
||||
pub status: EntryStatus,
|
||||
/// Total debits.
|
||||
pub amount: Decimal,
|
||||
/// Total debits; None when they can't be summed exactly (a draft's
|
||||
/// lines are as an earlier version journaled them, of any size:
|
||||
/// rules.md B-28).
|
||||
pub amount: Option<Decimal>,
|
||||
/// Accounts touched, debits first: "6300 Software".
|
||||
pub accounts: Vec<AccountId>,
|
||||
/// Indexes into [`Books::attachments`] of its current receipts: the
|
||||
@@ -44,8 +47,9 @@ pub struct EntryInfo {
|
||||
/// Covered by the receipt policy (the server's rule) and has no receipt.
|
||||
pub missing_receipt: bool,
|
||||
/// Net effect on cash accounts: positive in, negative out, zero if the
|
||||
/// entry doesn't touch cash.
|
||||
pub cash_effect: Decimal,
|
||||
/// entry doesn't touch cash; None when it can't be summed exactly (as
|
||||
/// `amount`).
|
||||
pub cash_effect: Option<Decimal>,
|
||||
/// The counterparty's name: its directory party's label (see
|
||||
/// [`PartyInfo`] for which entries are a party's; several parties'
|
||||
/// labels joined with " & "), else its vendor's or invoice customer's
|
||||
@@ -142,6 +146,9 @@ impl AssetTrail {
|
||||
/// 4. open_invoices = Σ Invoice::balance() over its customer record's
|
||||
/// invoices; open_bills = Σ Bill::balance() over its vendor record's
|
||||
/// bills (any date: what is still owed today).
|
||||
/// 4a. Each of 3 and 4 is None when it can't be summed exactly (a
|
||||
/// document is restored as an earlier version journaled it, of any
|
||||
/// size: rules.md B-28), never a wrong number.
|
||||
/// 5. form_1099: its vendor record's line in
|
||||
/// vendor_1099_report_with(ledger, year, None, cash and financing
|
||||
/// accounts), when it has a vendor
|
||||
@@ -160,10 +167,10 @@ pub struct PartyInfo {
|
||||
pub id: PartyId,
|
||||
pub entries: Vec<EntryId>,
|
||||
pub paid_ytd: Decimal,
|
||||
pub invoiced_ytd: Decimal,
|
||||
pub billed_ytd: Decimal,
|
||||
pub open_invoices: Decimal,
|
||||
pub open_bills: Decimal,
|
||||
pub invoiced_ytd: Option<Decimal>,
|
||||
pub billed_ytd: Option<Decimal>,
|
||||
pub open_invoices: Option<Decimal>,
|
||||
pub open_bills: Option<Decimal>,
|
||||
pub invoices: Vec<InvoiceId>,
|
||||
pub bills: Vec<BillId>,
|
||||
pub payroll_runs: Vec<PayrollRunId>,
|
||||
@@ -629,12 +636,7 @@ impl Books {
|
||||
}
|
||||
}
|
||||
}
|
||||
let amount: Decimal = e
|
||||
.lines()
|
||||
.iter()
|
||||
.filter(|l| l.side == Side::Debit)
|
||||
.map(|l| l.amount.amount)
|
||||
.sum();
|
||||
let amount = ledger_config::ReceiptPolicy::entry_debits(e).ok();
|
||||
let rec = receipts.remove(&id).unwrap_or_default();
|
||||
let vendor = ledger
|
||||
.entry_vendor(id)
|
||||
@@ -648,15 +650,14 @@ impl Books {
|
||||
&& e.reversal_of().is_none()
|
||||
&& rec.is_empty()
|
||||
&& policy.receipt_required(&ledger, e);
|
||||
let cash_effect: Decimal = e
|
||||
let cash_effect = e
|
||||
.lines()
|
||||
.iter()
|
||||
.filter(|l| cash_accounts.contains(&l.account))
|
||||
.map(|l| match l.side {
|
||||
Side::Debit => l.amount.amount,
|
||||
Side::Credit => -l.amount.amount,
|
||||
})
|
||||
.sum();
|
||||
.try_fold(Decimal::ZERO, |sum, l| match l.side {
|
||||
Side::Debit => sum.checked_add(l.amount.amount),
|
||||
Side::Credit => sum.checked_sub(l.amount.amount),
|
||||
});
|
||||
// Core tags every entry with its counterparty (hand tags,
|
||||
// vendor tags, bills, invoices, their payments, reversals).
|
||||
let party_id = ledger.entry_party(id);
|
||||
@@ -689,9 +690,9 @@ impl Books {
|
||||
let mut haystack = format!(
|
||||
"{} {} #{} {}",
|
||||
e.description(),
|
||||
crate::fmt::money(amount),
|
||||
crate::fmt::money_or(amount),
|
||||
id,
|
||||
amount
|
||||
amount.map_or_else(String::new, |a| a.to_string())
|
||||
);
|
||||
for a in &accounts {
|
||||
if let Some(acct) = ledger.chart().get(*a) {
|
||||
@@ -912,8 +913,8 @@ impl Books {
|
||||
}
|
||||
|
||||
/// The fixed asset register on `as_of`, exactly as ledger-core
|
||||
/// computes it.
|
||||
pub fn asset_register(&self, as_of: NaiveDate) -> AssetRegister {
|
||||
/// computes it (refused when its totals can't be computed exactly).
|
||||
pub fn asset_register(&self, as_of: NaiveDate) -> Result<AssetRegister, LedgerError> {
|
||||
fixed_asset_register(&self.ledger, as_of)
|
||||
}
|
||||
|
||||
@@ -960,6 +961,10 @@ impl Books {
|
||||
let l = &self.ledger;
|
||||
let year = self.today.year();
|
||||
let in_year = |d: NaiveDate| d.year() == year;
|
||||
// A sum that can't be computed exactly stays None (INVARIANT 4a).
|
||||
let add = |sum: &mut Option<Decimal>, v: Result<Decimal, LedgerError>| {
|
||||
*sum = sum.and_then(|s| s.checked_add(v.ok()?));
|
||||
};
|
||||
let mut out: BTreeMap<PartyId, PartyInfo> = l
|
||||
.parties()
|
||||
.map(|p| {
|
||||
@@ -967,6 +972,10 @@ impl Books {
|
||||
p.id,
|
||||
PartyInfo {
|
||||
id: p.id,
|
||||
invoiced_ytd: Some(Decimal::ZERO),
|
||||
billed_ytd: Some(Decimal::ZERO),
|
||||
open_invoices: Some(Decimal::ZERO),
|
||||
open_bills: Some(Decimal::ZERO),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
@@ -989,9 +998,9 @@ impl Books {
|
||||
.and_then(|p| out.get_mut(&p))
|
||||
{
|
||||
info.invoices.push(id);
|
||||
info.open_invoices += inv.balance();
|
||||
add(&mut info.open_invoices, inv.balance());
|
||||
if in_year(inv.date) {
|
||||
info.invoiced_ytd += inv.total();
|
||||
add(&mut info.invoiced_ytd, inv.total());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1002,9 +1011,9 @@ impl Books {
|
||||
.and_then(|p| out.get_mut(&p))
|
||||
{
|
||||
info.bills.push(id);
|
||||
info.open_bills += bill.balance();
|
||||
add(&mut info.open_bills, bill.balance());
|
||||
if in_year(bill.date) {
|
||||
info.billed_ytd += bill.total();
|
||||
add(&mut info.billed_ytd, bill.total());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1076,15 +1085,20 @@ impl Books {
|
||||
}
|
||||
|
||||
/// Depreciation due through the last finished month on or before
|
||||
/// `as_of` and not yet posted (see [`DepreciationDue`]).
|
||||
pub fn depreciation_due(&self, as_of: NaiveDate) -> DepreciationDue {
|
||||
let through = if as_of.succ_opt().is_some_and(|d| d.day() == 1) {
|
||||
/// `as_of` and not yet posted (see [`DepreciationDue`]); refused when
|
||||
/// the register can't be computed.
|
||||
pub fn depreciation_due(&self, as_of: NaiveDate) -> Result<DepreciationDue, LedgerError> {
|
||||
// A month's last day, or chrono's last day; else the end of the
|
||||
// month before (none before chrono's first month: its first day).
|
||||
let through = if as_of.succ_opt().is_none_or(|d| d.day() == 1) {
|
||||
as_of
|
||||
} else {
|
||||
NaiveDate::from_ymd_opt(as_of.year(), as_of.month(), 1).expect("valid")
|
||||
- chrono::Days::new(1)
|
||||
as_of
|
||||
.with_day(1)
|
||||
.and_then(|m| m.pred_opt())
|
||||
.unwrap_or(NaiveDate::MIN)
|
||||
};
|
||||
let amount = self.asset_register(through).unposted_depreciation();
|
||||
let amount = self.asset_register(through)?.unposted_depreciation();
|
||||
let mut periods = std::collections::BTreeSet::new();
|
||||
for a in self
|
||||
.ledger
|
||||
@@ -1101,11 +1115,11 @@ impl Books {
|
||||
}
|
||||
}
|
||||
}
|
||||
DepreciationDue {
|
||||
Ok(DepreciationDue {
|
||||
through,
|
||||
amount,
|
||||
periods: periods.into_iter().collect(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1344,11 +1358,21 @@ impl Books {
|
||||
.max()
|
||||
.map_or(self.today, |d| d.max(self.today))
|
||||
};
|
||||
// Years come from entries' dates and today, so chrono holds them;
|
||||
// one past its edge is clipped to them.
|
||||
let year = |y: i32| {
|
||||
(
|
||||
NaiveDate::from_ymd_opt(y, 1, 1).expect("valid"),
|
||||
NaiveDate::from_ymd_opt(y, 1, 1).unwrap_or(if y < 0 {
|
||||
NaiveDate::MIN
|
||||
} else {
|
||||
NaiveDate::MAX
|
||||
}),
|
||||
NaiveDate::from_ymd_opt(y, 12, 31)
|
||||
.expect("valid")
|
||||
.unwrap_or(if y < 0 {
|
||||
NaiveDate::MIN
|
||||
} else {
|
||||
NaiveDate::MAX
|
||||
})
|
||||
.min(last_posted(Some(y))),
|
||||
)
|
||||
};
|
||||
@@ -1436,7 +1460,12 @@ impl Books {
|
||||
let money = ledger_core::parties::money_accounts(l, &self.cash_accounts);
|
||||
let mut by: BTreeMap<AccountId, Decimal> = BTreeMap::new();
|
||||
for e in &posted {
|
||||
let flow = ledger_core::parties::entry_flow(e, &money);
|
||||
// A posted entry's flow computes (its lines are in a line's
|
||||
// range); one that doesn't, activity counts as unresolved
|
||||
// and counts nothing, so neither does what it was for.
|
||||
let Ok(flow) = ledger_core::parties::entry_flow(e, &money) else {
|
||||
continue;
|
||||
};
|
||||
let parts = self.party_what_for(e, party, &flow);
|
||||
for (account, amount) in parts {
|
||||
*by.entry(account).or_default() += amount;
|
||||
@@ -1548,19 +1577,20 @@ impl Books {
|
||||
return flow.what_for.clone();
|
||||
}
|
||||
let resolved = self.party_share(e, party);
|
||||
// Posted lines are in a line's range, so these sums and products
|
||||
// compute; one past exact arithmetic counts nothing, as an entry
|
||||
// whose shares don't resolve.
|
||||
let target = if flow.net.is_zero() {
|
||||
e.lines()
|
||||
.iter()
|
||||
.filter(|l| l.side == Side::Debit)
|
||||
.map(|l| l.amount.amount)
|
||||
.sum::<Decimal>()
|
||||
match ledger_config::ReceiptPolicy::entry_debits(e) {
|
||||
Ok(t) => t,
|
||||
Err(_) => return Vec::new(),
|
||||
}
|
||||
} else {
|
||||
flow.net
|
||||
};
|
||||
if target.is_zero() {
|
||||
let Some(fraction) = resolved.checked_div(target) else {
|
||||
return Vec::new();
|
||||
}
|
||||
let fraction = resolved / target;
|
||||
};
|
||||
let money_share = if flow.net.is_zero() {
|
||||
Decimal::ZERO
|
||||
} else {
|
||||
@@ -1578,11 +1608,20 @@ impl Books {
|
||||
if me.is_some_and(|m| m.capital == a || m.distributions == Some(a)) {
|
||||
own.push((a, v));
|
||||
} else if !member_line(a) {
|
||||
scaled.push((a, (v * fraction).round_dp_with_strategy(2, ToZero)));
|
||||
let Some(part) = v.checked_mul(fraction) else {
|
||||
return Vec::new();
|
||||
};
|
||||
scaled.push((a, part.round_dp_with_strategy(2, ToZero)));
|
||||
}
|
||||
}
|
||||
let have: Decimal = own.iter().chain(&scaled).map(|(_, v)| *v).sum();
|
||||
let left = money_share - have;
|
||||
let Some(left) = own
|
||||
.iter()
|
||||
.chain(&scaled)
|
||||
.try_fold(Decimal::ZERO, |t, (_, v)| t.checked_add(*v))
|
||||
.and_then(|have| money_share.checked_sub(have))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !left.is_zero() {
|
||||
match scaled.first_mut() {
|
||||
Some(first) => first.1 += left,
|
||||
@@ -1750,23 +1789,44 @@ impl Books {
|
||||
/// A party's money month by month over `span`: every month the span
|
||||
/// touches, each month's activity clipped to the span (so the months
|
||||
/// sum to the span's paid and received exactly).
|
||||
///
|
||||
/// Every month the span touches is one activity scan, so callers clip
|
||||
/// the span to the months they show ([`Books::last_months`]): books
|
||||
/// an earlier version wrote may run from chrono's first day (rules.md
|
||||
/// B-28). Chrono's last month ends the walk, never a panic.
|
||||
pub fn party_months(&self, party: PartyId, span: (NaiveDate, NaiveDate)) -> Vec<PartyMonth> {
|
||||
let mut out = Vec::new();
|
||||
let mut m = NaiveDate::from_ymd_opt(span.0.year(), span.0.month(), 1).expect("valid");
|
||||
while m <= span.1 {
|
||||
let end = (m + chrono::Months::new(1) - chrono::Days::new(1)).min(span.1);
|
||||
let start = m.max(span.0);
|
||||
let mut m = span.0.with_day(1);
|
||||
while let Some(month) = m.filter(|m| *m <= span.1) {
|
||||
let next = month.checked_add_months(chrono::Months::new(1));
|
||||
let end = next
|
||||
.and_then(|n| n.pred_opt())
|
||||
.unwrap_or(NaiveDate::MAX)
|
||||
.min(span.1);
|
||||
let start = month.max(span.0);
|
||||
let a = self.activity(party, (start, end));
|
||||
out.push(PartyMonth {
|
||||
month: m,
|
||||
month,
|
||||
paid: a.paid,
|
||||
received: a.received,
|
||||
});
|
||||
m = m + chrono::Months::new(1);
|
||||
m = next;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The last `n` months of `span` (n >= 1): the span from the first of
|
||||
/// the month n - 1 months before its end, or the whole span when it is
|
||||
/// shorter.
|
||||
pub fn last_months(span: (NaiveDate, NaiveDate), n: u32) -> (NaiveDate, NaiveDate) {
|
||||
let first = span
|
||||
.1
|
||||
.with_day(1)
|
||||
.and_then(|m| m.checked_sub_months(chrono::Months::new(n.saturating_sub(1))))
|
||||
.unwrap_or(NaiveDate::MIN);
|
||||
(span.0.max(first), span.1)
|
||||
}
|
||||
|
||||
/// Blob store path for an attachment.
|
||||
pub fn blob_root(&self) -> PathBuf {
|
||||
self.data_dir.join("blobs")
|
||||
@@ -1776,31 +1836,34 @@ impl Books {
|
||||
/// An entry flow's what_for apportioned to one party's `share` of its net:
|
||||
/// the whole of it when the share is the net; else each account's amount
|
||||
/// times share / net, rounded toward zero to the cent, the cents left over
|
||||
/// going to the first account, so the parts sum to `share` exactly.
|
||||
/// going to the first account, so the parts sum to `share` exactly. None
|
||||
/// when amount times share is past exact arithmetic (both near the line
|
||||
/// limit), never a panic or a rounded guess.
|
||||
pub fn share_of_what_for(
|
||||
flow: &ledger_core::parties::EntryFlow,
|
||||
share: Decimal,
|
||||
) -> Vec<(AccountId, Decimal)> {
|
||||
) -> Option<Vec<(AccountId, Decimal)>> {
|
||||
use rust_decimal::RoundingStrategy::ToZero;
|
||||
if share == flow.net || flow.what_for.is_empty() {
|
||||
return flow.what_for.clone();
|
||||
return Some(flow.what_for.clone());
|
||||
}
|
||||
if flow.net.is_zero() || share.is_zero() {
|
||||
return Vec::new();
|
||||
return Some(Vec::new());
|
||||
}
|
||||
let mut parts: Vec<(AccountId, Decimal)> = flow
|
||||
.what_for
|
||||
.iter()
|
||||
.map(|(a, v)| {
|
||||
(
|
||||
*a,
|
||||
(*v * share / flow.net).round_dp_with_strategy(2, ToZero),
|
||||
)
|
||||
let part = v.checked_mul(share)?.checked_div(flow.net)?;
|
||||
Some((*a, part.round_dp_with_strategy(2, ToZero)))
|
||||
})
|
||||
.collect();
|
||||
let left = share - parts.iter().map(|(_, v)| *v).sum::<Decimal>();
|
||||
parts[0].1 += left;
|
||||
parts
|
||||
.collect::<Option<_>>()?;
|
||||
let have = parts
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |t, (_, v)| t.checked_add(*v))?;
|
||||
let left = share.checked_sub(have)?;
|
||||
parts[0].1 = parts[0].1.checked_add(left)?;
|
||||
Some(parts)
|
||||
}
|
||||
|
||||
/// Every registered asset's trail, from the journal (depreciation,
|
||||
|
||||
@@ -113,7 +113,13 @@ pub fn balance_line(ui: &mut Ui, points: &[(NaiveDate, Decimal)], until: NaiveDa
|
||||
// X labels: first, last, and a few between.
|
||||
let n_labels = ((plot.width() / 90.0) as usize).clamp(1, 4);
|
||||
for i in 0..=n_labels {
|
||||
let d = first + chrono::Days::new(((days * i as f64) / n_labels as f64).round() as u64);
|
||||
// At most `last` (a one-day chart is one day wide, and its first day
|
||||
// may be chrono's last).
|
||||
let d = first
|
||||
.checked_add_days(chrono::Days::new(
|
||||
((days * i as f64) / n_labels as f64).round() as u64,
|
||||
))
|
||||
.map_or(last, |d| d.min(last));
|
||||
let align = match i {
|
||||
0 => Align2::LEFT_TOP,
|
||||
i if i == n_labels => Align2::RIGHT_TOP,
|
||||
@@ -165,7 +171,9 @@ pub fn balance_line(ui: &mut Ui, points: &[(NaiveDate, Decimal)], until: NaiveDa
|
||||
&& plot.x_range().contains(hp.x)
|
||||
{
|
||||
let frac = ((hp.x - plot.left()) / plot.width()) as f64;
|
||||
let day = first + chrono::Days::new((frac * days).round() as u64);
|
||||
let day = first
|
||||
.checked_add_days(chrono::Days::new((frac * days).round() as u64))
|
||||
.map_or(last, |d| d.min(last));
|
||||
let bal = points
|
||||
.iter()
|
||||
.take_while(|(d, _)| *d <= day)
|
||||
@@ -418,3 +426,69 @@ pub fn sparkline(painter: &Painter, rect: Rect, values: &[f64], color: Color32)
|
||||
.collect();
|
||||
painter.add(Shape::line(pts, Stroke::new(1.5, color)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui_kittest::Harness;
|
||||
|
||||
fn d(y: i32, m: u32, day: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(y, m, day).unwrap()
|
||||
}
|
||||
|
||||
/// Every text a frame painted, with where it was painted.
|
||||
fn painted(out: &egui::FullOutput) -> Vec<(String, egui::Pos2, f32)> {
|
||||
fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Pos2, f32)>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => {
|
||||
out.push((t.galley.text().to_string(), t.pos, t.galley.size().x))
|
||||
}
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut texts = Vec::new();
|
||||
for c in &out.shapes {
|
||||
walk(&c.shape, &mut texts);
|
||||
}
|
||||
texts
|
||||
}
|
||||
|
||||
/// charts::balance_line: the x axis is labeled with its first day, its
|
||||
/// last, and days evenly between (rounded); hovering shows the balance on
|
||||
/// the hovered day.
|
||||
#[test]
|
||||
fn the_balance_chart_labels_its_days_and_shows_the_hovered_one() {
|
||||
let points = vec![
|
||||
(d(2026, 1, 1), Decimal::new(10_000, 2)),
|
||||
(d(2026, 1, 11), Decimal::new(5_000, 2)),
|
||||
];
|
||||
let mut h = Harness::builder()
|
||||
.with_size(egui::vec2(800.0, 300.0))
|
||||
.build_ui(move |ui| balance_line(ui, &points, d(2026, 1, 11), 200.0));
|
||||
crate::theme::install_fonts(&h.ctx);
|
||||
crate::theme::apply(&h.ctx, false);
|
||||
h.run();
|
||||
let texts = painted(h.output());
|
||||
let labels: Vec<&str> = texts.iter().map(|(t, _, _)| t.as_str()).collect();
|
||||
// Ten days, four gaps (the plot is wide): 0, 2.5, 5, 7.5, 10 rounded.
|
||||
for want in ["Jan 1", "Jan 4", "Jan 6", "Jan 9", "Jan 11"] {
|
||||
assert!(labels.contains(&want), "{want} not in {labels:?}");
|
||||
}
|
||||
// The plot runs from the first label's left edge to the last's right.
|
||||
let (_, first, _) = texts.iter().find(|(t, _, _)| t == "Jan 1").unwrap();
|
||||
let (_, last, w) = texts.iter().find(|(t, _, _)| t == "Jan 11").unwrap();
|
||||
let (left, right) = (first.x, last.x + w);
|
||||
for (frac, day) in [(0.3, d(2026, 1, 4)), (0.5, d(2026, 1, 6))] {
|
||||
h.hover_at(egui::pos2(left + (right - left) * frac, first.y - 40.0));
|
||||
h.run();
|
||||
let texts = painted(h.output());
|
||||
let want = crate::fmt::date(day);
|
||||
assert!(
|
||||
texts.iter().any(|(t, _, _)| *t == want),
|
||||
"{want} not shown at {frac}: {:?}",
|
||||
texts.iter().map(|(t, _, _)| t).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,21 @@ pub fn money(d: Decimal) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the viewer shows for a figure the books can't compute (rules.md
|
||||
/// B-28: an earlier version's draft lines, shares, or bases past exact
|
||||
/// arithmetic): said in words, never a number.
|
||||
pub const CANT_COMPUTE: &str = "too large to compute";
|
||||
|
||||
/// [`money`], or [`CANT_COMPUTE`] for a figure the books can't compute.
|
||||
pub fn money_or(d: Option<Decimal>) -> String {
|
||||
d.map_or_else(|| CANT_COMPUTE.to_string(), money)
|
||||
}
|
||||
|
||||
/// [`dollars`], or [`CANT_COMPUTE`] for a figure the books can't compute.
|
||||
pub fn dollars_or(d: Option<Decimal>) -> String {
|
||||
d.map_or_else(|| CANT_COMPUTE.to_string(), dollars)
|
||||
}
|
||||
|
||||
/// Accounting style: negatives in parentheses, `(1,234.56)`.
|
||||
pub fn accounting(d: Decimal) -> String {
|
||||
let s = group(d.abs());
|
||||
@@ -217,6 +232,18 @@ mod tests {
|
||||
use super::*;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// money_or / dollars_or: a figure as money_ or dollars does, and one
|
||||
/// the books can't compute in words, never a number (rules.md B-28).
|
||||
#[test]
|
||||
fn a_figure_or_why_not() {
|
||||
let v = Decimal::new(-123_456, 2);
|
||||
assert_eq!(money_or(Some(v)), money(v));
|
||||
assert_eq!(dollars_or(Some(v)), dollars(v));
|
||||
assert_eq!(money_or(None), CANT_COMPUTE);
|
||||
assert_eq!(dollars_or(None), CANT_COMPUTE);
|
||||
assert_eq!(CANT_COMPUTE, "too large to compute");
|
||||
}
|
||||
|
||||
fn dec(s: &str) -> Decimal {
|
||||
Decimal::from_str(s).unwrap()
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ pub mod nav;
|
||||
pub mod pages;
|
||||
pub mod palette;
|
||||
mod receipts;
|
||||
#[cfg(test)]
|
||||
mod test_support;
|
||||
mod theme;
|
||||
mod widgets;
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ use crate::fmt;
|
||||
use crate::nav::{ReportKind, Route};
|
||||
use crate::theme::{self, pal};
|
||||
use crate::widgets;
|
||||
use chrono::{Datelike, NaiveDate};
|
||||
use chrono::NaiveDate;
|
||||
use egui::{Color32, CornerRadius, Margin, RichText, Sense, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
use ledger_core::{Asset, AssetId, AssetRegister, AssetRegisterRow, AssetStatus, TaxBasisRule};
|
||||
@@ -59,7 +59,16 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec<Notice> {
|
||||
let mut out = Vec::new();
|
||||
let unposted = r.unposted_depreciation();
|
||||
if unposted > Decimal::ZERO {
|
||||
let due = b.depreciation_due(r.as_of);
|
||||
let due = match b.depreciation_due(r.as_of) {
|
||||
Ok(due) => due,
|
||||
Err(e) => {
|
||||
out.push(Notice {
|
||||
problem: true,
|
||||
text: format!("Depreciation due can't be computed: {e}."),
|
||||
});
|
||||
return out;
|
||||
}
|
||||
};
|
||||
let due_amount = due.amount.clamp(Decimal::ZERO, unposted);
|
||||
if due_amount > Decimal::ZERO {
|
||||
out.push(Notice {
|
||||
@@ -398,16 +407,7 @@ fn date_controls(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) -> NaiveDate {
|
||||
ui.label(
|
||||
RichText::new(format!("{} As of", icon::CALENDAR_BLANK)).font(theme::semibold(13.5)),
|
||||
);
|
||||
let mut d =
|
||||
jiff::civil::Date::new(as_of.year() as i16, as_of.month() as i8, as_of.day() as i8)
|
||||
.expect("valid date");
|
||||
ui.add(
|
||||
egui_extras::DatePickerButton::new(&mut d)
|
||||
.id_salt("assets_as_of")
|
||||
.calendar_week(false),
|
||||
);
|
||||
let picked = NaiveDate::from_ymd_opt(i32::from(d.year()), d.month() as u32, d.day() as u32)
|
||||
.expect("valid date");
|
||||
let picked = widgets::date_picker(ui, "assets_as_of", as_of);
|
||||
if picked != as_of {
|
||||
shell.state.assets.as_of = Some(picked);
|
||||
}
|
||||
@@ -458,7 +458,20 @@ pub fn show_register(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
}
|
||||
let as_of = date_controls(ui, b, shell);
|
||||
ui.add_space(12.0);
|
||||
let r = b.asset_register(as_of);
|
||||
let r = match b.asset_register(as_of) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
widgets::card(ui, |ui| {
|
||||
widgets::empty(
|
||||
ui,
|
||||
icon::PACKAGE,
|
||||
"The register can't be computed",
|
||||
&format!("{e}. Ask the bookkeeper to find the record behind it."),
|
||||
)
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
super::grid(ui, 4, 200.0, 4, |i, ui| {
|
||||
let (label, value, how, sub) = match i {
|
||||
0 => (
|
||||
@@ -722,8 +735,9 @@ fn reconciliation(ui: &mut Ui, b: &Books, r: &AssetRegister, shell: &mut Shell<'
|
||||
);
|
||||
let d = r.unposted_depreciation();
|
||||
// Only the month under way: not a problem, just not yet.
|
||||
let accruing =
|
||||
d > Decimal::ZERO && b.depreciation_due(r.as_of).amount <= Decimal::ZERO;
|
||||
let accruing = d > Decimal::ZERO
|
||||
&& b.depreciation_due(r.as_of)
|
||||
.is_ok_and(|due| due.amount <= Decimal::ZERO);
|
||||
let color = if accruing { p.muted } else { diff_color(d) };
|
||||
line(ui, "Difference (not yet posted)", d, true, color);
|
||||
});
|
||||
@@ -814,11 +828,11 @@ pub fn show_asset(ui: &mut Ui, b: &Books, id: AssetId, shell: &mut Shell<'_>) {
|
||||
return;
|
||||
};
|
||||
let trail = b.asset_trail(id);
|
||||
// Err: the register's totals can't be computed (a contributor basis an
|
||||
// earlier version journaled, past exact arithmetic); said, never guessed.
|
||||
let today = b
|
||||
.asset_register(b.today)
|
||||
.rows
|
||||
.into_iter()
|
||||
.find(|r| r.asset_id == id);
|
||||
.map(|r| r.rows.into_iter().find(|r| r.asset_id == id));
|
||||
let mut go: Option<Route> = None;
|
||||
page(ui, "asset", |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
@@ -962,13 +976,21 @@ pub fn show_asset(ui: &mut Ui, b: &Books, id: AssetId, shell: &mut Shell<'_>) {
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
if let Some(r) = &today {
|
||||
k(ui, &format!("Accumulated, {}", fmt::date_short(b.today)));
|
||||
money(ui, r.accumulated, false);
|
||||
ui.end_row();
|
||||
k(ui, "Book value today");
|
||||
money(ui, r.book_value, true);
|
||||
ui.end_row();
|
||||
match &today {
|
||||
Ok(Some(r)) => {
|
||||
k(ui, &format!("Accumulated, {}", fmt::date_short(b.today)));
|
||||
money(ui, r.accumulated, false);
|
||||
ui.end_row();
|
||||
k(ui, "Book value today");
|
||||
money(ui, r.book_value, true);
|
||||
ui.end_row();
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
k(ui, "Book value today");
|
||||
ui.label(format!("can't be computed: {e}"));
|
||||
ui.end_row();
|
||||
}
|
||||
}
|
||||
k(ui, "Posted in the books");
|
||||
money(ui, trail.posted(), false);
|
||||
@@ -1139,7 +1161,7 @@ pub fn show_asset(ui: &mut Ui, b: &Books, id: AssetId, shell: &mut Shell<'_>) {
|
||||
fmt::date(info.date),
|
||||
info.id,
|
||||
info.description,
|
||||
fmt::dollars(info.amount)
|
||||
fmt::dollars_or(info.amount)
|
||||
))
|
||||
.font(theme::regular(13.0)),
|
||||
)
|
||||
@@ -1315,3 +1337,97 @@ pub(crate) fn facts(ui: &mut Ui, add: impl FnOnce(&mut Ui, &dyn Fn(&mut Ui, &str
|
||||
add(ui, &k);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::{Build, Painted, beside, cents, d, find, render, today};
|
||||
use ledger_core::{Currency, Money, NewAsset};
|
||||
|
||||
/// Two assets bought 2026-01-01 for $1,200.00 over 12 months and
|
||||
/// $2,400.00 over 24 (both $100.00 a month), no depreciation posted.
|
||||
fn two_assets(tag: &str) -> (crate::test_support::TempDir, Books, Vec<AssetId>) {
|
||||
let mut b = Build::new(tag);
|
||||
let mut add =
|
||||
|code: &str, name: &str, ty| b.s.add_account(code, name, ty, None, false).unwrap();
|
||||
let equipment = add("1500", "Equipment", ledger_core::AccountType::Asset);
|
||||
let accum = add(
|
||||
"1510",
|
||||
"Accumulated Depreciation",
|
||||
ledger_core::AccountType::Asset,
|
||||
);
|
||||
let depreciation = add("6100", "Depreciation", ledger_core::AccountType::Expense);
|
||||
let (cash, capital) = (b.cash, b.capital);
|
||||
b.post(d(2026, 1, 1), cash, capital, 1_000_000);
|
||||
b.post(d(2026, 1, 1), equipment, cash, 360_000);
|
||||
let ids = [(120_000, 12), (240_000, 24)]
|
||||
.into_iter()
|
||||
.map(|(cost, months)| {
|
||||
b.s.register_asset(NewAsset {
|
||||
description: format!("Thing {months}"),
|
||||
purchase_date: d(2026, 1, 1),
|
||||
cost: Money::new(cents(cost), Currency::USD),
|
||||
salvage_value: Money::new(Decimal::ZERO, Currency::USD),
|
||||
useful_life_months: months,
|
||||
cost_account: equipment,
|
||||
accum_depr_account: accum,
|
||||
expense_account: depreciation,
|
||||
})
|
||||
.unwrap()
|
||||
})
|
||||
.collect();
|
||||
let (dir, books) = b.books();
|
||||
(dir, books, ids)
|
||||
}
|
||||
|
||||
fn register_on(
|
||||
tag: &str,
|
||||
as_of: Option<NaiveDate>,
|
||||
) -> (Vec<Painted>, Color32, Color32, Color32) {
|
||||
let (_dir, books, _) = two_assets(tag);
|
||||
let (texts, p) = render(books, Route::Assets, |s| s.assets.as_of = as_of);
|
||||
(texts, p.warning, p.muted, p.positive)
|
||||
}
|
||||
|
||||
/// The register on its date, reconciled to the books: its cost, and
|
||||
/// the depreciation the schedules have accrued but the books don't
|
||||
/// carry: a problem when some is due through a finished month, just
|
||||
/// accruing when only the month under way has any, agreeing when none.
|
||||
#[test]
|
||||
fn the_register_reconciles_to_the_books_on_its_date() {
|
||||
let (texts, warning, muted, positive) = register_on("register-today", None);
|
||||
find(&texts, "Fixed assets");
|
||||
find(&texts, "Reconciliation to the books");
|
||||
assert_eq!(
|
||||
beside(&texts, "Cost in the register").text,
|
||||
fmt::money(cents(360_000))
|
||||
);
|
||||
// Due through September: a problem.
|
||||
assert_eq!(beside(&texts, "Difference (not yet posted)").color, warning);
|
||||
// January 15th: nothing due through December, half a month accruing.
|
||||
let (texts, _, muted2, _) = register_on("register-jan", Some(d(2026, 1, 15)));
|
||||
assert_eq!(muted2, muted);
|
||||
assert_eq!(beside(&texts, "Difference (not yet posted)").color, muted);
|
||||
// Before the purchase: nothing to post, the books agree.
|
||||
let (texts, _, _, _) = register_on("register-before", Some(d(2025, 12, 31)));
|
||||
let none = beside(&texts, "Difference (not yet posted)");
|
||||
assert_eq!(none.text, fmt::money(Decimal::ZERO));
|
||||
assert_eq!(none.color, positive);
|
||||
}
|
||||
|
||||
/// One asset's page shows its own book value today, not another's.
|
||||
#[test]
|
||||
fn an_assets_page_shows_its_own_book_value() {
|
||||
for i in 0..2 {
|
||||
let (_dir, books, ids) = two_assets(&format!("asset-page-{i}"));
|
||||
let a = books.ledger.get_asset(ids[i]).unwrap().clone();
|
||||
let want = ledger_core::book_value(&a, today());
|
||||
let (texts, _) = render(books, Route::Asset(ids[i]), |_| {});
|
||||
assert_eq!(
|
||||
beside(&texts, "Book value today").text,
|
||||
fmt::dollars(want),
|
||||
"asset {i}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -341,13 +341,30 @@ fn schedules(ui: &mut Ui, b: &Books) {
|
||||
|ui| {
|
||||
for s in list {
|
||||
let total = s.total.amount;
|
||||
let remaining = s.remaining();
|
||||
let frac: f32 = if total.is_zero() {
|
||||
1.0
|
||||
} else {
|
||||
((total - remaining) / total).try_into().unwrap_or(0.0)
|
||||
// A schedule an earlier version journaled may not compute
|
||||
// (months past chrono's last day): said, never guessed.
|
||||
let (remaining, due) = match (s.remaining(), s.due(b.today)) {
|
||||
(Ok(r), Ok(d)) => (r, d),
|
||||
(Err(e), _) | (_, Err(e)) => {
|
||||
ui.label(RichText::new(&s.description).font(theme::semibold(13.5)));
|
||||
ui.label(
|
||||
RichText::new(format!("Its plan can't be computed: {e}."))
|
||||
.font(theme::regular(12.0))
|
||||
.color(p.negative),
|
||||
);
|
||||
ui.add_space(8.0);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let recognized = total.checked_sub(remaining);
|
||||
let frac: f32 = match recognized {
|
||||
_ if total.is_zero() => 1.0,
|
||||
Some(r) => r
|
||||
.checked_div(total)
|
||||
.and_then(|x| x.try_into().ok())
|
||||
.unwrap_or(0.0),
|
||||
None => 0.0,
|
||||
};
|
||||
let due = s.due(b.today);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(RichText::new(&s.description).font(theme::semibold(13.5)));
|
||||
ui.label(
|
||||
@@ -369,7 +386,7 @@ fn schedules(ui: &mut Ui, b: &Books) {
|
||||
frac,
|
||||
&format!(
|
||||
"{} of {} recognized · {} left",
|
||||
fmt::dollars(total - remaining),
|
||||
fmt::dollars_or(recognized),
|
||||
fmt::dollars(total),
|
||||
fmt::dollars(remaining)
|
||||
),
|
||||
@@ -393,12 +410,11 @@ fn recurring(ui: &mut Ui, b: &Books) {
|
||||
|_| {},
|
||||
|ui| {
|
||||
for r in list {
|
||||
let amount: Decimal = r
|
||||
let amount = r
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|(_, s, _)| *s == ledger_core::Side::Debit)
|
||||
.map(|(_, _, m)| m.amount)
|
||||
.sum();
|
||||
.try_fold(Decimal::ZERO, |t, (_, _, m)| t.checked_add(m.amount));
|
||||
let next = (0..)
|
||||
.map_while(|k| {
|
||||
r.frequency
|
||||
@@ -412,7 +428,7 @@ fn recurring(ui: &mut Ui, b: &Books) {
|
||||
RichText::new(format!(
|
||||
"{} · {}",
|
||||
fmt::words(&format!("{:?}", r.frequency)),
|
||||
fmt::dollars(amount)
|
||||
fmt::dollars_or(amount)
|
||||
))
|
||||
.font(theme::regular(12.0))
|
||||
.color(p.muted),
|
||||
@@ -520,21 +536,24 @@ fn parties(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
ui.label(RichText::new("No customers yet.").color(p.muted));
|
||||
}
|
||||
for c in customers {
|
||||
let owed: Decimal = (1..b.ledger.next_invoice_id())
|
||||
// None: a balance, or their sum, can't be computed.
|
||||
let owed = (1..b.ledger.next_invoice_id())
|
||||
.filter_map(|i| b.ledger.get_invoice(i))
|
||||
.filter(|i| i.customer_id == c.id)
|
||||
.map(|i| i.balance())
|
||||
.sum();
|
||||
.try_fold(Decimal::ZERO, |t, i| t.checked_add(i.balance().ok()?));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
name(ui, &c.name, b.ledger.party_of_customer(c.id));
|
||||
ui.with_layout(
|
||||
egui::Layout::right_to_left(egui::Align::Center),
|
||||
|ui| {
|
||||
if !owed.is_zero() {
|
||||
if !owed.is_some_and(|o| o.is_zero()) {
|
||||
ui.label(
|
||||
RichText::new(format!("owes {}", fmt::dollars(owed)))
|
||||
.font(theme::regular(12.5))
|
||||
.color(p.muted),
|
||||
RichText::new(format!(
|
||||
"owes {}",
|
||||
fmt::dollars_or(owed)
|
||||
))
|
||||
.font(theme::regular(12.5))
|
||||
.color(p.muted),
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -549,3 +568,94 @@ fn parties(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
shell.go(r);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::{Build, beside, cents, d, find, has, render_all};
|
||||
use ledger_core::arap::DocumentLine;
|
||||
use ledger_core::{AccountType, Currency, Frequency, Money, NewRecurring, NewSchedule, Side};
|
||||
|
||||
/// The company page: each amortization schedule's recognized share as
|
||||
/// a bar (three of twelve months posted: a quarter), each recurring
|
||||
/// entry, and each customer with what they owe, theirs alone.
|
||||
#[test]
|
||||
fn the_company_page_says_what_each_record_holds() {
|
||||
let mut b = Build::new("company");
|
||||
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
|
||||
let prepaid =
|
||||
b.s.add_account("1300", "Prepaid", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let insurance =
|
||||
b.s.add_account("6300", "Insurance", AccountType::Expense, None, false)
|
||||
.unwrap();
|
||||
b.post(d(2026, 1, 2), cash, capital, 1_000_000);
|
||||
b.post(d(2026, 1, 2), prepaid, cash, 120_000);
|
||||
let usd = |c: i64| Money::new(cents(c), Currency::USD);
|
||||
b.s.register_schedule(NewSchedule {
|
||||
description: "Insurance plan".into(),
|
||||
kind: ledger_core::ScheduleKind::PrepaidExpense,
|
||||
total: usd(120_000),
|
||||
start: d(2026, 1, 1),
|
||||
months: 12,
|
||||
balance_account: prepaid,
|
||||
pl_account: insurance,
|
||||
})
|
||||
.unwrap();
|
||||
b.s.run_schedules(d(2026, 3, 31)).unwrap();
|
||||
b.s.register_recurring(NewRecurring {
|
||||
description: "Office rent".into(),
|
||||
lines: vec![
|
||||
(rent, Side::Debit, usd(50_000)),
|
||||
(cash, Side::Credit, usd(50_000)),
|
||||
],
|
||||
frequency: Frequency::Monthly,
|
||||
start: d(2026, 1, 20),
|
||||
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.add_customer("Gamma").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, 9, 1), d(2026, 10, 1), line(20_000))
|
||||
.unwrap();
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, rects, p) = render_all(books, Route::Company, |_| {});
|
||||
find(&texts, "Amortization schedules");
|
||||
let label = find(
|
||||
&texts,
|
||||
"$300.00 of $1,200.00 recognized \u{b7} $900.00 left",
|
||||
);
|
||||
// The bar just above it: the track, and the part done.
|
||||
let near = |fill: egui::Color32| {
|
||||
rects
|
||||
.iter()
|
||||
.filter(|(r, f)| {
|
||||
*f == fill
|
||||
&& r.height() <= 8.5
|
||||
&& (label.pos.y - r.max.y) >= 0.0
|
||||
&& (label.pos.y - r.max.y) < 12.0
|
||||
})
|
||||
.map(|(r, _)| r.width())
|
||||
.fold(0.0f32, f32::max)
|
||||
};
|
||||
let (track, done) = (near(p.hover), near(p.accent));
|
||||
assert!(track > 100.0, "track {track}");
|
||||
assert!((done / track - 0.25).abs() < 0.01, "{done} of {track}");
|
||||
find(&texts, "Recurring entries");
|
||||
find(&texts, "Office rent");
|
||||
find(&texts, "Vendors");
|
||||
find(&texts, "Customers");
|
||||
assert_eq!(beside(&texts, "Acme").text, "owes $1,200.00");
|
||||
assert_eq!(beside(&texts, "Beta").text, "owes $200.00");
|
||||
assert!(!has(&texts, "owes $0.00"));
|
||||
}
|
||||
}
|
||||
@@ -202,7 +202,7 @@ fn tile(
|
||||
Some(x) => format!(
|
||||
"#{e} · {} · {}",
|
||||
fmt::date_short(x.date),
|
||||
fmt::dollars(x.amount)
|
||||
fmt::dollars_or(x.amount)
|
||||
),
|
||||
None => format!("#{e}"),
|
||||
},
|
||||
@@ -544,7 +544,7 @@ fn links_section(ui: &mut Ui, b: &Books, a: &Attachment, go: &mut Option<Route>)
|
||||
RichText::new(format!(
|
||||
"{} · {}",
|
||||
fmt::date(x.date),
|
||||
fmt::dollars(x.amount)
|
||||
fmt::dollars_or(x.amount)
|
||||
))
|
||||
.font(theme::regular(11.5))
|
||||
.color(p.muted),
|
||||
@@ -563,3 +563,27 @@ fn links_section(ui: &mut Ui, b: &Books, a: &Attachment, go: &mut Option<Route>)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::{Build, d, find, render};
|
||||
|
||||
/// A document's page lists what it is linked to: an entry with its date
|
||||
/// and amount.
|
||||
#[test]
|
||||
fn a_document_lists_the_entry_it_is_linked_to() {
|
||||
let mut b = Build::new("document-links");
|
||||
let (cash, capital) = (b.cash, b.capital);
|
||||
let e = b.post(d(2026, 1, 2), cash, capital, 100_000);
|
||||
let (att, _, _) =
|
||||
b.s.file_document("other", "note.pdf", "application/pdf", b"%PDF note", None)
|
||||
.unwrap();
|
||||
b.s.link_attachment(att, ledger_store::Subject::Entry(e))
|
||||
.unwrap();
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, _) = render(books, Route::Document(att), |_| {});
|
||||
find(&texts, "LINKED TO");
|
||||
find(&texts, "Jan 2, 2026 \u{b7} $1,000.00");
|
||||
}
|
||||
}
|
||||
@@ -173,8 +173,8 @@ pub fn detail(ui: &mut Ui, b: &Books, e: &EntryInfo, shell: &mut Shell<'_>) {
|
||||
k(ui, "Amount");
|
||||
widgets::copyable(
|
||||
ui,
|
||||
RichText::new(fmt::dollars(e.amount)).font(theme::semibold(14.0)),
|
||||
&fmt::plain(&fmt::dollars(e.amount)).unwrap_or_default(),
|
||||
RichText::new(fmt::dollars_or(e.amount)).font(theme::semibold(14.0)),
|
||||
&fmt::plain(&fmt::dollars_or(e.amount)).unwrap_or_default(),
|
||||
);
|
||||
ui.end_row();
|
||||
if let Some(c) = &created {
|
||||
@@ -221,7 +221,9 @@ pub fn detail(ui: &mut Ui, b: &Books, e: &EntryInfo, shell: &mut Shell<'_>) {
|
||||
widgets::amount_cell(ui, "Debit", amt_w, p.muted, false, false);
|
||||
widgets::amount_cell(ui, "Credit", amt_w, p.muted, false, false);
|
||||
});
|
||||
let (mut dr, mut cr) = (Decimal::ZERO, Decimal::ZERO);
|
||||
// None: past exact arithmetic (a draft line an earlier
|
||||
// version journaled, of any size: rules.md B-28).
|
||||
let (mut dr, mut cr) = (Some(Decimal::ZERO), Some(Decimal::ZERO));
|
||||
for line in entry.lines() {
|
||||
ui.horizontal(|ui| {
|
||||
let w = ui.available_width() - amt_w * 2.0 - 16.0;
|
||||
@@ -262,11 +264,11 @@ pub fn detail(ui: &mut Ui, b: &Books, e: &EntryInfo, shell: &mut Shell<'_>) {
|
||||
let a = fmt::money(line.amount.amount);
|
||||
let (d, c) = match line.side {
|
||||
Side::Debit => {
|
||||
dr += line.amount.amount;
|
||||
dr = dr.and_then(|t| t.checked_add(line.amount.amount));
|
||||
(a, String::new())
|
||||
}
|
||||
Side::Credit => {
|
||||
cr += line.amount.amount;
|
||||
cr = cr.and_then(|t| t.checked_add(line.amount.amount));
|
||||
(String::new(), a)
|
||||
}
|
||||
};
|
||||
@@ -277,21 +279,24 @@ pub fn detail(ui: &mut Ui, b: &Books, e: &EntryInfo, shell: &mut Shell<'_>) {
|
||||
widgets::rule(ui);
|
||||
ui.horizontal(|ui| {
|
||||
let w = ui.available_width() - amt_w * 2.0 - 16.0;
|
||||
let balanced = dr == cr;
|
||||
let totalled = dr.is_some() && cr.is_some();
|
||||
let balanced = totalled && dr == cr;
|
||||
let (r, _) = ui.allocate_exact_size(vec2(w, 22.0), egui::Sense::hover());
|
||||
ui.painter().text(
|
||||
r.left_center(),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
if balanced {
|
||||
format!("{} Balanced", icon::CHECK)
|
||||
} else {
|
||||
} else if totalled {
|
||||
"Out of balance".into()
|
||||
} else {
|
||||
"Too large to total".into()
|
||||
},
|
||||
theme::regular(12.0),
|
||||
if balanced { p.positive } else { p.negative },
|
||||
);
|
||||
widgets::amount_cell(ui, &fmt::money(dr), amt_w, p.text, true, false);
|
||||
widgets::amount_cell(ui, &fmt::money(cr), amt_w, p.text, true, false);
|
||||
widgets::amount_cell(ui, &fmt::money_or(dr), amt_w, p.text, true, false);
|
||||
widgets::amount_cell(ui, &fmt::money_or(cr), amt_w, p.text, true, false);
|
||||
});
|
||||
});
|
||||
ui.add_space(18.0);
|
||||
@@ -524,3 +529,50 @@ pub fn share_text(s: &crate::books::EntryParty) -> String {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::{Build, d, find, old_books, render};
|
||||
|
||||
/// An entry's totals line: "Balanced" when its debits equal its
|
||||
/// credits, "Out of balance" when they don't, "Too large to total"
|
||||
/// when a side is past exact arithmetic (a draft an earlier version
|
||||
/// journaled); its totals right-aligned under the lines' columns.
|
||||
#[test]
|
||||
fn an_entrys_totals_say_whether_it_balances() {
|
||||
let mut b = Build::new("entry-totals");
|
||||
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
|
||||
let _ = rent;
|
||||
let posted = b.post(d(2026, 1, 2), cash, capital, 100_000);
|
||||
let usd = |c: i64| ledger_core::Money::new(Decimal::new(c, 2), ledger_core::Currency::USD);
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, p) = render(books, Route::Entry(posted), |_| {});
|
||||
assert_eq!(
|
||||
find(&texts, &format!("{} Balanced", icon::CHECK)).color,
|
||||
p.positive
|
||||
);
|
||||
// Each column's amounts end at one edge: the lines' and the total's.
|
||||
let mut edges: Vec<i32> = texts
|
||||
.iter()
|
||||
.filter(|t| t.text == fmt::money(Decimal::new(100_000, 2)))
|
||||
.map(|t| (t.pos.x + t.width).round() as i32)
|
||||
.collect();
|
||||
assert_eq!(edges.len(), 4, "two lines and two totals");
|
||||
edges.sort_unstable();
|
||||
edges.dedup();
|
||||
assert_eq!(edges.len(), 2, "two columns: {edges:?}");
|
||||
let mut b = Build::new("entry-unbalanced");
|
||||
let (cash, rent) = (b.cash, b.rent);
|
||||
let draft = b.s.create_entry(d(2026, 3, 1), "half").unwrap();
|
||||
b.s.add_line(draft, rent, Side::Debit, usd(1_000)).unwrap();
|
||||
b.s.add_line(draft, cash, Side::Credit, usd(500)).unwrap();
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, p) = render(books, Route::Entry(draft), |_| {});
|
||||
assert_eq!(find(&texts, "Out of balance").color, p.negative);
|
||||
// Its debits past exact arithmetic, its credits $1.00.
|
||||
let (_dir, books) = old_books("x_draft_max_lines");
|
||||
let (texts, p) = render(books, Route::Entry(1), |_| {});
|
||||
assert_eq!(find(&texts, "Too large to total").color, p.negative);
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,14 @@ fn amount(p: &Value) -> String {
|
||||
|
||||
fn entry_text(b: &Books, id: u64) -> String {
|
||||
b.entry(id)
|
||||
.map(|e| format!("#{} {} ({})", e.id, e.description, fmt::dollars(e.amount)))
|
||||
.map(|e| {
|
||||
format!(
|
||||
"#{} {} ({})",
|
||||
e.id,
|
||||
e.description,
|
||||
fmt::dollars_or(e.amount)
|
||||
)
|
||||
})
|
||||
.unwrap_or_else(|| format!("#{id}"))
|
||||
}
|
||||
|
||||
@@ -1085,3 +1092,21 @@ fn detail(ui: &mut Ui, b: &Books, line: &JournalLine, shell: &mut Shell<'_>) {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::{Build, d, find, render};
|
||||
|
||||
/// The journal names an entry it posted by number, description and
|
||||
/// amount.
|
||||
#[test]
|
||||
fn the_journal_names_a_posted_entry() {
|
||||
let mut b = Build::new("journal-posted");
|
||||
let (cash, capital) = (b.cash, b.capital);
|
||||
let e = b.post_as("Opening deposit", d(2026, 1, 2), cash, capital, 100_000);
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, _) = render(books, Route::Journal, |_| {});
|
||||
find(&texts, &format!("Posted #{e} Opening deposit ($1,000.00)"));
|
||||
}
|
||||
}
|
||||
@@ -579,7 +579,14 @@ pub fn show_list(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
|
||||
/// A number tile on a party's page: label, amount, how it's computed,
|
||||
/// and the line under it.
|
||||
type Tile = (String, Decimal, String, Option<(String, egui::Color32)>);
|
||||
/// (label, value, how, sub); the value None when it can't be computed
|
||||
/// exactly (documents restored as an earlier version journaled them).
|
||||
type Tile = (
|
||||
String,
|
||||
Option<Decimal>,
|
||||
String,
|
||||
Option<(String, egui::Color32)>,
|
||||
);
|
||||
|
||||
/// One party, completely.
|
||||
pub fn show_party(ui: &mut Ui, b: &Books, id: PartyId, shell: &mut Shell<'_>) {
|
||||
@@ -665,20 +672,20 @@ pub fn show_party(ui: &mut Ui, b: &Books, id: PartyId, shell: &mut Shell<'_>) {
|
||||
let mut tiles: Vec<Tile> = Vec::new();
|
||||
tiles.push((
|
||||
"Paid out".into(),
|
||||
flow.paid,
|
||||
Some(flow.paid),
|
||||
format!("{label}, {span_words}: what this party's posted entries moved out of cash, cards, and what's owed back to whoever paid for the company (net of refunds and reversals of payments)."),
|
||||
Some((label.clone(), p.muted)),
|
||||
));
|
||||
tiles.push((
|
||||
"Received in".into(),
|
||||
flow.received,
|
||||
Some(flow.received),
|
||||
format!("{label}, {span_words}: what this party's posted entries brought into cash and those accounts (net of reversals)."),
|
||||
Some((label.clone(), p.muted)),
|
||||
));
|
||||
let net = flow.net();
|
||||
tiles.push((
|
||||
"Net".into(),
|
||||
net.abs(),
|
||||
Some(net.abs()),
|
||||
"Paid out less received in.".into(),
|
||||
Some((
|
||||
if net < Decimal::ZERO {
|
||||
@@ -716,7 +723,7 @@ pub fn show_party(ui: &mut Ui, b: &Books, id: PartyId, shell: &mut Shell<'_>) {
|
||||
"What the company still owes on its bills today.".into(),
|
||||
(!info.bills.is_empty()).then(|| {
|
||||
(
|
||||
format!("{} billed in {year}", fmt::dollars(info.billed_ytd)),
|
||||
format!("{} billed in {year}", fmt::dollars_or(info.billed_ytd)),
|
||||
p.muted,
|
||||
)
|
||||
}),
|
||||
@@ -742,7 +749,7 @@ pub fn show_party(ui: &mut Ui, b: &Books, id: PartyId, shell: &mut Shell<'_>) {
|
||||
};
|
||||
tiles.push((
|
||||
format!("1099 amount, {tax_year}"),
|
||||
l.paid,
|
||||
Some(l.paid),
|
||||
"Cash paid in the calendar year, from the 1099 worksheet (ledger-core): posted entries tagged with its vendor record, net of refunds and reversals. Card payments aren't counted (the card issuer reports them).".into(),
|
||||
Some(sub),
|
||||
));
|
||||
@@ -754,13 +761,15 @@ pub fn show_party(ui: &mut Ui, b: &Books, id: PartyId, shell: &mut Shell<'_>) {
|
||||
ui,
|
||||
widgets::Kpi {
|
||||
label,
|
||||
value: fmt::dollars(*value),
|
||||
value: fmt::dollars_or(*value),
|
||||
sub: sub.clone(),
|
||||
spark: None,
|
||||
how,
|
||||
},
|
||||
);
|
||||
r.context_menu(|ui| widgets::copy_item(ui, "Copy amount", &value.to_string()));
|
||||
if let Some(v) = value {
|
||||
r.context_menu(|ui| widgets::copy_item(ui, "Copy amount", &v.to_string()));
|
||||
}
|
||||
});
|
||||
|
||||
// A member's page is their capital account statement too.
|
||||
@@ -1218,10 +1227,10 @@ fn entries_card(ui: &mut Ui, b: &Books, info: &PartyInfo, go: &mut Option<Route>
|
||||
sub = format!(
|
||||
"Their share, {} of {}, with {} · {sub}",
|
||||
super::entry::share_text(mine),
|
||||
fmt::dollars(e.amount),
|
||||
fmt::dollars_or(e.amount),
|
||||
others.join(" & ")
|
||||
);
|
||||
amount = mine.resolved.map(|v| v.abs()).unwrap_or(e.amount);
|
||||
amount = mine.resolved.map(|v| v.abs()).or(e.amount);
|
||||
}
|
||||
let resp = row(
|
||||
ui,
|
||||
@@ -1231,7 +1240,7 @@ fn entries_card(ui: &mut Ui, b: &Books, info: &PartyInfo, go: &mut Option<Route>
|
||||
(format!("#{}", e.id), 64.0, false, p.muted),
|
||||
(e.description.clone(), 0.0, false, text),
|
||||
(kind, 150.0, false, if draft { p.warning } else { p.muted }),
|
||||
(fmt::money(amount), amt, true, text),
|
||||
(fmt::money_or(amount), amt, true, text),
|
||||
],
|
||||
Some((sub.as_str(), p.faint)),
|
||||
false,
|
||||
@@ -1239,7 +1248,9 @@ fn entries_card(ui: &mut Ui, b: &Books, info: &PartyInfo, go: &mut Option<Route>
|
||||
);
|
||||
resp.context_menu(|ui| {
|
||||
widgets::copy_item(ui, "Copy entry number", &format!("#{}", e.id));
|
||||
widgets::copy_item(ui, "Copy amount", &e.amount.to_string());
|
||||
if let Some(a) = e.amount {
|
||||
widgets::copy_item(ui, "Copy amount", &a.to_string());
|
||||
}
|
||||
});
|
||||
if resp.on_hover_text("Open this entry").clicked() {
|
||||
*go = Some(Route::Entry(e.id));
|
||||
@@ -1290,8 +1301,8 @@ fn documents_card(ui: &mut Ui, b: &Books, info: &PartyInfo, go: &mut Option<Rout
|
||||
i.date,
|
||||
i.due_date,
|
||||
i.status,
|
||||
i.total(),
|
||||
i.balance(),
|
||||
i.total().ok(),
|
||||
i.balance().ok(),
|
||||
i.entry_id,
|
||||
)
|
||||
});
|
||||
@@ -1305,15 +1316,15 @@ fn documents_card(ui: &mut Ui, b: &Books, info: &PartyInfo, go: &mut Option<Rout
|
||||
i.date,
|
||||
i.due_date,
|
||||
i.status,
|
||||
i.total(),
|
||||
i.balance(),
|
||||
i.total().ok(),
|
||||
i.balance().ok(),
|
||||
i.entry_id,
|
||||
)
|
||||
});
|
||||
let mut docs: Vec<_> = invoices.chain(bills).collect();
|
||||
docs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
for (name, date, due, status, total, balance, entry) in docs {
|
||||
let late = !balance.is_zero() && due < b.today;
|
||||
let late = !balance.is_some_and(|x| x.is_zero()) && due < b.today;
|
||||
let resp = row(
|
||||
ui,
|
||||
w,
|
||||
@@ -1327,8 +1338,8 @@ fn documents_card(ui: &mut Ui, b: &Books, info: &PartyInfo, go: &mut Option<Rout
|
||||
if late { p.warning } else { p.text },
|
||||
),
|
||||
(fmt::words(&format!("{status:?}")), 90.0, false, p.muted),
|
||||
(fmt::money(total), amt, true, p.text),
|
||||
(fmt::money(balance), amt, true, p.text),
|
||||
(fmt::money_or(total), amt, true, p.text),
|
||||
(fmt::money_or(balance), amt, true, p.text),
|
||||
],
|
||||
None,
|
||||
false,
|
||||
@@ -1389,7 +1400,7 @@ fn payroll_card(ui: &mut Ui, b: &Books, party: &Party, info: &PartyInfo, go: &mu
|
||||
(format!("Run {}", run.id), 80.0, false, p.muted),
|
||||
(l.employee_name.clone(), 0.0, false, p.text),
|
||||
(fmt::money(l.gross_pay), amt, true, p.text),
|
||||
(fmt::money(l.net_pay()), amt, true, p.text),
|
||||
(fmt::money_or(l.net_pay().ok()), amt, true, p.text),
|
||||
],
|
||||
None,
|
||||
false,
|
||||
@@ -1501,15 +1512,18 @@ fn what_for_card(ui: &mut Ui, b: &Books, flow: &PartyFlow, label: &str, go: &mut
|
||||
/// Out versus in, month by month over the period ([`Books::party_months`]).
|
||||
fn months_card(ui: &mut Ui, b: &Books, id: PartyId, span: (NaiveDate, NaiveDate), label: &str) {
|
||||
let p = pal(ui.ctx());
|
||||
let months = b.party_months(id, span);
|
||||
// All time can be long: the chart shows the last 24 months of it.
|
||||
let shown: Vec<_> = months.iter().rev().take(24).rev().collect();
|
||||
// All time can be long (from chrono's first day, in books an earlier
|
||||
// version wrote): the chart shows the last 24 months of it, and only
|
||||
// those are computed.
|
||||
let clipped = crate::books::Books::last_months(span, 24);
|
||||
let months = b.party_months(id, clipped);
|
||||
let shown: Vec<_> = months.iter().collect();
|
||||
widgets::titled_card(
|
||||
ui,
|
||||
"By month",
|
||||
|ui| {
|
||||
ui.label(
|
||||
RichText::new(if months.len() > shown.len() {
|
||||
RichText::new(if clipped.0 > span.0 {
|
||||
format!("{label}, last {} months", shown.len())
|
||||
} else {
|
||||
label.to_string()
|
||||
@@ -1548,3 +1562,123 @@ fn months_card(ui: &mut Ui, b: &Books, id: PartyId, span: (NaiveDate, NaiveDate)
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::{Build, cents, d, find, render};
|
||||
use ledger_core::arap::DocumentLine;
|
||||
|
||||
/// A customer's page: the entries tagged with them, and their invoices,
|
||||
/// a due date marked late only for an invoice still owed after it.
|
||||
#[test]
|
||||
fn a_customers_page_lists_entries_and_marks_late_invoices() {
|
||||
let mut b = Build::new("party-docs");
|
||||
let cash = b.cash;
|
||||
let acme = b.s.add_customer("Acme").unwrap();
|
||||
let line = |c: i64| {
|
||||
vec![DocumentLine {
|
||||
description: "work".into(),
|
||||
amount: cents(c),
|
||||
}]
|
||||
};
|
||||
// Owed, not yet due; owed, due today; paid, past due; owed, past
|
||||
// due.
|
||||
b.s.create_invoice(acme, d(2026, 10, 1), d(2026, 11, 30), line(10_000))
|
||||
.unwrap();
|
||||
b.s.create_invoice(acme, d(2026, 10, 1), d(2026, 10, 15), line(5_000))
|
||||
.unwrap();
|
||||
let paid =
|
||||
b.s.create_invoice(acme, d(2026, 8, 1), d(2026, 8, 31), line(20_000))
|
||||
.unwrap();
|
||||
b.s.receive_payment(paid, d(2026, 8, 20), cents(20_000), cash)
|
||||
.unwrap();
|
||||
b.s.create_invoice(acme, d(2026, 9, 1), d(2026, 9, 30), line(30_000))
|
||||
.unwrap();
|
||||
let (_dir, books) = b.books();
|
||||
let party = books.ledger.party_of_customer(acme).unwrap();
|
||||
let (texts, p) = render(books, Route::Party(party), |_| {});
|
||||
find(&texts, "Entries");
|
||||
// Four invoices and the payment.
|
||||
find(&texts, "5 entries");
|
||||
find(&texts, "Invoices and bills");
|
||||
for due in [
|
||||
d(2026, 11, 30),
|
||||
d(2026, 10, 15),
|
||||
d(2026, 8, 31),
|
||||
d(2026, 9, 30),
|
||||
] {
|
||||
let shown = texts.iter().filter(|t| t.text == fmt::date(due)).count();
|
||||
assert_eq!(shown, 1, "{due}");
|
||||
}
|
||||
assert_eq!(find(&texts, &fmt::date(d(2026, 11, 30))).color, p.text);
|
||||
assert_eq!(find(&texts, &fmt::date(d(2026, 10, 15))).color, p.text);
|
||||
assert_eq!(find(&texts, &fmt::date(d(2026, 8, 31))).color, p.text);
|
||||
assert_eq!(find(&texts, &fmt::date(d(2026, 9, 30))).color, p.warning);
|
||||
}
|
||||
|
||||
/// An employee's page lists the payroll runs that name them.
|
||||
#[test]
|
||||
fn an_employees_page_lists_their_payroll_runs() {
|
||||
let mut b = Build::new("party-payroll");
|
||||
let (cash, capital) = (b.cash, b.capital);
|
||||
b.post(d(2026, 1, 2), cash, capital, 1_000_000);
|
||||
let pat = b.s.add_party("Pat", &[Role::Employee]).unwrap();
|
||||
b.s.run_payroll(
|
||||
d(2026, 3, 31),
|
||||
vec![ledger_core::PayrollLine {
|
||||
employee_name: "Pat".into(),
|
||||
employee: Some(pat),
|
||||
gross_pay: cents(100_000),
|
||||
federal_withholding: cents(10_000),
|
||||
state_withholding: Decimal::ZERO,
|
||||
ss_employee: Decimal::ZERO,
|
||||
medicare_employee: Decimal::ZERO,
|
||||
ss_employer: Decimal::ZERO,
|
||||
medicare_employer: Decimal::ZERO,
|
||||
other_deductions: Decimal::ZERO,
|
||||
}],
|
||||
cash,
|
||||
)
|
||||
.unwrap();
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, _) = render(books, Route::Party(pat), |_| {});
|
||||
find(&texts, "Payroll runs");
|
||||
}
|
||||
|
||||
/// A party's "By month" chart: all time over more than two years shows
|
||||
/// its last 24 months, and says so; a shorter period, all of it.
|
||||
#[test]
|
||||
fn the_by_month_chart_says_when_it_shows_the_last_months() {
|
||||
let mut b = Build::new("party-months");
|
||||
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
|
||||
b.post(d(2023, 1, 2), cash, capital, 1_000_000);
|
||||
let sam = b.s.add_party("Sam", &[Role::Contractor]).unwrap();
|
||||
for date in [d(2023, 6, 1), d(2026, 3, 1)] {
|
||||
let e = b.post(date, rent, cash, 10_000);
|
||||
b.s.set_entry_party(e, Some(sam)).unwrap();
|
||||
}
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, _) = render(books, Route::Party(sam), |s| {
|
||||
s.parties.period = PartyPeriod::AllTime
|
||||
});
|
||||
find(&texts, "By month");
|
||||
assert!(
|
||||
texts.iter().any(|t| t.text.ends_with(", last 24 months")),
|
||||
"{:?}",
|
||||
texts.iter().map(|t| &t.text).collect::<Vec<_>>()
|
||||
);
|
||||
let mut b = Build::new("party-months-short");
|
||||
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
|
||||
b.post(d(2026, 1, 2), cash, capital, 1_000_000);
|
||||
let sam = b.s.add_party("Sam", &[Role::Contractor]).unwrap();
|
||||
let e = b.post(d(2026, 3, 1), rent, cash, 10_000);
|
||||
b.s.set_entry_party(e, Some(sam)).unwrap();
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, _) = render(books, Route::Party(sam), |s| {
|
||||
s.parties.period = PartyPeriod::AllTime
|
||||
});
|
||||
find(&texts, "By month");
|
||||
assert!(!texts.iter().any(|t| t.text.contains(", last ")));
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,9 @@ use rust_decimal::Decimal;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn pct(part: Decimal, whole: Decimal) -> Option<Decimal> {
|
||||
(!whole.is_zero()).then(|| (part / whole * Decimal::from(100)).round_dp(1))
|
||||
part.checked_div(whole)?
|
||||
.checked_mul(Decimal::from(100))
|
||||
.map(|x| x.round_dp(1))
|
||||
}
|
||||
|
||||
pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
|
||||
@@ -289,6 +291,9 @@ fn by_customer(ui: &mut Ui, b: &Books) {
|
||||
let p = pal(ui.ctx());
|
||||
let (ys, ye) = b.fiscal_ytd();
|
||||
let mut by: BTreeMap<String, Decimal> = BTreeMap::new();
|
||||
// An invoice an earlier version journaled may be past exact arithmetic:
|
||||
// then the card says so instead of charting a wrong share.
|
||||
let mut cant: Option<String> = None;
|
||||
for id in 1..b.ledger.next_invoice_id() {
|
||||
if let Some(inv) = b.ledger.get_invoice(id)
|
||||
&& inv.date >= ys
|
||||
@@ -299,9 +304,17 @@ fn by_customer(ui: &mut Ui, b: &Books) {
|
||||
.get_customer(inv.customer_id)
|
||||
.map(|c| c.name.clone())
|
||||
.unwrap_or_default();
|
||||
*by.entry(who).or_default() += inv.total();
|
||||
let sum = by.entry(who).or_default();
|
||||
match inv.total().ok().and_then(|t| sum.checked_add(t)) {
|
||||
Some(t) => *sum = t,
|
||||
None => cant = Some(format!("invoice {id}'s total can't be computed exactly")),
|
||||
}
|
||||
}
|
||||
}
|
||||
let total = rows_total(&by);
|
||||
if total.is_none() && cant.is_none() {
|
||||
cant = Some("the invoices' total can't be computed exactly".into());
|
||||
}
|
||||
let mut rows: Vec<(String, Decimal)> = by.into_iter().collect();
|
||||
rows.sort_by_key(|r| std::cmp::Reverse(r.1));
|
||||
widgets::titled_card(
|
||||
@@ -309,6 +322,10 @@ fn by_customer(ui: &mut Ui, b: &Books) {
|
||||
"Invoiced by customer, this year",
|
||||
|_| {},
|
||||
|ui| {
|
||||
if let Some(why) = &cant {
|
||||
widgets::empty(ui, icon::USERS, "Can't be computed", why);
|
||||
return;
|
||||
}
|
||||
if rows.is_empty() {
|
||||
widgets::empty(
|
||||
ui,
|
||||
@@ -318,7 +335,7 @@ fn by_customer(ui: &mut Ui, b: &Books) {
|
||||
);
|
||||
return;
|
||||
}
|
||||
let total: Decimal = rows.iter().map(|r| r.1).sum();
|
||||
let total = total.unwrap_or_default();
|
||||
if let Some((top, v)) = rows.first() {
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
@@ -335,6 +352,12 @@ fn by_customer(ui: &mut Ui, b: &Books) {
|
||||
);
|
||||
}
|
||||
|
||||
/// The sum of the customers' totals, None past exact arithmetic.
|
||||
fn rows_total(by: &BTreeMap<String, Decimal>) -> Option<Decimal> {
|
||||
by.values()
|
||||
.try_fold(Decimal::ZERO, |t, v| t.checked_add(*v))
|
||||
}
|
||||
|
||||
fn by_class(ui: &mut Ui, b: &Books) {
|
||||
let p = pal(ui.ctx());
|
||||
let (ys, ye) = b.fiscal_ytd();
|
||||
@@ -381,3 +404,41 @@ fn by_class(ui: &mut Ui, b: &Books) {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::{Build, cents, d, find, render};
|
||||
use ledger_core::arap::DocumentLine;
|
||||
|
||||
/// pct: part of whole as a percent, to one place; none of nothing.
|
||||
#[test]
|
||||
fn a_percent_of_a_whole() {
|
||||
assert_eq!(pct(cents(2_500), cents(20_000)), Some(Decimal::new(125, 1)));
|
||||
assert_eq!(pct(cents(1), cents(3)), Some(Decimal::new(333, 1)));
|
||||
assert_eq!(pct(cents(1), Decimal::ZERO), None);
|
||||
assert_eq!(pct(Decimal::MAX, Decimal::new(1, 2)), None);
|
||||
}
|
||||
|
||||
/// "Invoiced by customer, this year": this fiscal year's invoices only.
|
||||
#[test]
|
||||
fn invoiced_by_customer_is_this_years() {
|
||||
let mut b = Build::new("profit-customers");
|
||||
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, 3, 1), d(2026, 3, 31), line(30_000))
|
||||
.unwrap();
|
||||
b.s.create_invoice(beta, d(2025, 6, 1), d(2025, 6, 30), line(100_000))
|
||||
.unwrap();
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, _) = render(books, Route::Profit, |_| {});
|
||||
find(&texts, "Invoiced by customer, this year");
|
||||
find(&texts, "Acme is 100% of invoiced income.");
|
||||
}
|
||||
}
|
||||
@@ -349,6 +349,25 @@ fn col_title(s: NaiveDate, e: NaiveDate, columns: Columns) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most columns a split report shows.
|
||||
const MAX_COLUMNS: i64 = 240;
|
||||
|
||||
/// How many columns splitting `s..=e` by `columns` makes, when that is
|
||||
/// more than [`MAX_COLUMNS`]; counted from the months, before building
|
||||
/// any (a range across chrono's calendar is millions of months).
|
||||
fn too_many_columns(s: NaiveDate, e: NaiveDate, columns: Columns) -> Option<i64> {
|
||||
let per = match columns {
|
||||
Columns::Total => return None,
|
||||
Columns::Month => 1,
|
||||
Columns::Quarter => 3,
|
||||
Columns::Year => 12,
|
||||
};
|
||||
let months = (i64::from(e.year()) - i64::from(s.year())) * 12 + i64::from(e.month())
|
||||
- i64::from(s.month());
|
||||
let n = months / per + 1;
|
||||
(n > MAX_COLUMNS).then_some(n)
|
||||
}
|
||||
|
||||
/// The column ranges for a range and split (with the prior period second
|
||||
/// when comparing a single column).
|
||||
fn column_ranges(st: &State, b: &Books) -> Vec<(NaiveDate, NaiveDate, String)> {
|
||||
@@ -379,29 +398,26 @@ fn column_ranges(st: &State, b: &Books) -> Vec<(NaiveDate, NaiveDate, String)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The period compared against, if any: None too when it falls before
|
||||
/// chrono's first day (a range from the books' first entry, which an
|
||||
/// earlier version may have dated there: rules.md B-28).
|
||||
fn prior(st: &State, s: NaiveDate, e: NaiveDate) -> Option<(NaiveDate, NaiveDate)> {
|
||||
match st.compare {
|
||||
Compare::None => None,
|
||||
Compare::PriorYear => Some((s - Months::new(12), e - Months::new(12))),
|
||||
Compare::PriorYear => Some((
|
||||
s.checked_sub_months(Months::new(12))?,
|
||||
e.checked_sub_months(Months::new(12))?,
|
||||
)),
|
||||
Compare::PriorPeriod => {
|
||||
let days = (e - s).num_days() + 1;
|
||||
let pe = s - Days::new(1);
|
||||
Some((pe - Days::new(days as u64 - 1), pe))
|
||||
let pe = s.checked_sub_days(Days::new(1))?;
|
||||
Some((pe.checked_sub_days(Days::new(days as u64 - 1))?, pe))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Cols = [(NaiveDate, NaiveDate, String)];
|
||||
|
||||
fn to_jiff(d: NaiveDate) -> jiff::civil::Date {
|
||||
jiff::civil::Date::new(d.year() as i16, d.month() as i8, d.day() as i8).expect("valid date")
|
||||
}
|
||||
|
||||
fn from_jiff(d: jiff::civil::Date) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(i32::from(d.year()), d.month() as u32, d.day() as u32)
|
||||
.expect("valid date")
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Builders.
|
||||
|
||||
@@ -756,7 +772,11 @@ fn owners_equity(b: &Books, s: NaiveDate, e: NaiveDate) -> Table {
|
||||
row(
|
||||
&mut t,
|
||||
Kind::Line,
|
||||
&format!("Balance, {}", fmt::date(s - Days::new(1))),
|
||||
&match s.pred_opt() {
|
||||
Some(day_before) => format!("Balance, {}", fmt::date(day_before)),
|
||||
// Nothing is dated before chrono's first day.
|
||||
None => "Opening balance".into(),
|
||||
},
|
||||
&|m| m.beginning,
|
||||
);
|
||||
row(&mut t, Kind::Line, "Contributions", &|m| m.contributions);
|
||||
@@ -782,7 +802,8 @@ fn owners_equity(b: &Books, s: NaiveDate, e: NaiveDate) -> Table {
|
||||
ledger_core::analysis::accounts_of_type(&b.ledger, &[AccountType::Equity]);
|
||||
let (mut tb, mut te) = (Decimal::ZERO, Decimal::ZERO);
|
||||
for a in eq {
|
||||
let begin = b.balance_on(a, s - Days::new(1));
|
||||
// Nothing is dated before chrono's first day: nothing to begin with.
|
||||
let begin = s.pred_opt().map_or(Decimal::ZERO, |d| b.balance_on(a, d));
|
||||
let end = b.balance_on(a, e);
|
||||
tb += begin;
|
||||
te += end;
|
||||
@@ -804,7 +825,9 @@ fn owners_equity(b: &Books, s: NaiveDate, e: NaiveDate) -> Table {
|
||||
],
|
||||
);
|
||||
}
|
||||
let ni_begin = balance_sheet_as_of(&b.ledger, s - Days::new(1))
|
||||
let ni_begin = s
|
||||
.pred_opt()
|
||||
.and_then(|d| balance_sheet_as_of(&b.ledger, d).ok())
|
||||
.map(|bs| bs.current_earnings)
|
||||
.unwrap_or_default();
|
||||
let ni_end = balance_sheet_as_of(&b.ledger, e)
|
||||
@@ -901,7 +924,20 @@ fn tax(b: &Books, s: NaiveDate, e: NaiveDate) -> Table {
|
||||
t
|
||||
}
|
||||
|
||||
fn aging(rows: Vec<ledger_core::AgingRow>, as_of: NaiveDate) -> Table {
|
||||
/// A report the books can't compute (rules.md B-28: books an earlier
|
||||
/// version wrote may hold amounts past exact arithmetic): no figures, and a
|
||||
/// note saying why, never a guess.
|
||||
fn cant_compute(mut t: Table, why: &ledger_core::LedgerError) -> Table {
|
||||
t.note(format!(
|
||||
"This report can't be computed: {why}. Ask the bookkeeper to find the record behind it."
|
||||
));
|
||||
t
|
||||
}
|
||||
|
||||
fn aging(
|
||||
rows: Result<Vec<ledger_core::AgingRow>, ledger_core::LedgerError>,
|
||||
as_of: NaiveDate,
|
||||
) -> Table {
|
||||
let mut t = Table::new(vec![
|
||||
"Current".into(),
|
||||
"1–30".into(),
|
||||
@@ -910,18 +946,30 @@ fn aging(rows: Vec<ledger_core::AgingRow>, as_of: NaiveDate) -> Table {
|
||||
"Over 90".into(),
|
||||
"Total".into(),
|
||||
]);
|
||||
let rows = match rows {
|
||||
Ok(rows) => rows,
|
||||
Err(e) => return cant_compute(t, &e),
|
||||
};
|
||||
let too_large = || ledger_core::LedgerError::TooLargeToCompute("the aging's totals".into());
|
||||
let mut tot = [Decimal::ZERO; 6];
|
||||
for r in &rows {
|
||||
let total = match r.total() {
|
||||
Ok(total) => total,
|
||||
Err(e) => return cant_compute(t, &e),
|
||||
};
|
||||
let v = [
|
||||
r.current,
|
||||
r.days_30,
|
||||
r.days_60,
|
||||
r.days_90,
|
||||
r.days_90_plus,
|
||||
r.total(),
|
||||
total,
|
||||
];
|
||||
for (i, x) in v.iter().enumerate() {
|
||||
tot[i] += x;
|
||||
match tot[i].checked_add(*x) {
|
||||
Some(sum) => tot[i] = sum,
|
||||
None => return cant_compute(t, &too_large()),
|
||||
}
|
||||
}
|
||||
t.row(
|
||||
Kind::Line,
|
||||
@@ -951,7 +999,6 @@ fn aging(rows: Vec<ledger_core::AgingRow>, as_of: NaiveDate) -> Table {
|
||||
/// with its rule (and citation) in the detail; the tax basis total is the
|
||||
/// register's.
|
||||
fn asset_register(b: &Books, as_of: NaiveDate) -> Table {
|
||||
let r = b.asset_register(as_of);
|
||||
let mut t = Table::new(vec![
|
||||
"Cost".into(),
|
||||
"Accumulated".into(),
|
||||
@@ -960,6 +1007,10 @@ fn asset_register(b: &Books, as_of: NaiveDate) -> Table {
|
||||
"Tax basis".into(),
|
||||
"Built-in gain (loss)".into(),
|
||||
]);
|
||||
let r = match b.asset_register(as_of) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return cant_compute(t, &e),
|
||||
};
|
||||
let none3 = || vec![Cell::none(), Cell::none(), Cell::none()];
|
||||
if r.rows.is_empty() {
|
||||
t.note(format!(
|
||||
@@ -1271,19 +1322,9 @@ fn report(ui: &mut Ui, b: &Books, kind: ReportKind, shell: &mut Shell<'_>, picke
|
||||
});
|
||||
if let Range::Custom(s, e) = st.range {
|
||||
room(ui, 250.0);
|
||||
let (mut js, mut je) = (to_jiff(s), to_jiff(e));
|
||||
ui.add(
|
||||
egui_extras::DatePickerButton::new(&mut js)
|
||||
.id_salt("from")
|
||||
.calendar_week(false),
|
||||
);
|
||||
let s = widgets::date_picker(ui, "from", s);
|
||||
ui.label(RichText::new("to").color(p.muted));
|
||||
ui.add(
|
||||
egui_extras::DatePickerButton::new(&mut je)
|
||||
.id_salt("to")
|
||||
.calendar_week(false),
|
||||
);
|
||||
let (s, e) = (from_jiff(js), from_jiff(je));
|
||||
let e = widgets::date_picker(ui, "to", e);
|
||||
st.range = Range::Custom(s.min(e), e.max(s));
|
||||
}
|
||||
if splittable {
|
||||
@@ -1317,9 +1358,22 @@ fn report(ui: &mut Ui, b: &Books, kind: ReportKind, shell: &mut Shell<'_>, picke
|
||||
ui.add_space(18.0);
|
||||
|
||||
let (s, e) = st.range.dates(b);
|
||||
// A split over a range from the books' first entry, which an earlier
|
||||
// version may have dated thousands of years back (rules.md B-28),
|
||||
// would be more columns than anyone can read or the frame can build:
|
||||
// shown as one total, with a note saying so.
|
||||
let split_note = splittable
|
||||
.then(|| too_many_columns(s, e, st.columns))
|
||||
.flatten()
|
||||
.map(|n| {
|
||||
format!(
|
||||
"Split {} ways ({n} columns); more than {MAX_COLUMNS} can't be shown, so this is the total. Choose a shorter range to split it.",
|
||||
fmt::words(&format!("{:?}", st.columns)).to_lowercase()
|
||||
)
|
||||
});
|
||||
let state = State {
|
||||
range: st.range,
|
||||
columns: if splittable {
|
||||
columns: if splittable && split_note.is_none() {
|
||||
st.columns
|
||||
} else {
|
||||
Columns::Total
|
||||
@@ -1433,7 +1487,10 @@ fn report(ui: &mut Ui, b: &Books, kind: ReportKind, shell: &mut Shell<'_>, picke
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(t) = table {
|
||||
if let Some(mut t) = table {
|
||||
if let Some(n) = split_note {
|
||||
t.note(n);
|
||||
}
|
||||
render(ui, &t, &PdfInfo::new(b, kind.title(), &subtitle), shell);
|
||||
}
|
||||
if let Some(k) = pick {
|
||||
@@ -2031,6 +2088,85 @@ fn vendor_1099(ui: &mut Ui, b: &Books, year: i32, shell: &mut Shell<'_>) {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
/// A report shows the range and split chosen: last year's P&L by
|
||||
/// month has a column for each of last year's months, not this year's.
|
||||
#[test]
|
||||
fn a_report_shows_the_range_and_split_chosen() {
|
||||
use crate::test_support::{Build, d, find, has, render};
|
||||
let mut b = Build::new("report-range");
|
||||
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
|
||||
b.post(d(2025, 1, 2), cash, capital, 1_000_000);
|
||||
b.post(d(2025, 3, 2), rent, cash, 10_000);
|
||||
let (_dir, books) = b.books();
|
||||
let (texts, _) = render(books, Route::Reports(ReportKind::ProfitAndLoss), |s| {
|
||||
s.reports.range = Range::Custom(d(2025, 1, 1), d(2025, 12, 31));
|
||||
s.reports.columns = Columns::Month;
|
||||
});
|
||||
find(&texts, "Mar 2025");
|
||||
assert!(!has(&texts, "Mar 2026"));
|
||||
}
|
||||
|
||||
/// prior: the period before, as long as the range in days, ending the
|
||||
/// day before it starts; or the same days a year before; none before
|
||||
/// chrono's first day.
|
||||
#[test]
|
||||
fn the_prior_period_is_as_long_and_just_before() {
|
||||
let d = |y, m, day| NaiveDate::from_ymd_opt(y, m, day).unwrap();
|
||||
let mut st = State::default();
|
||||
assert_eq!(prior(&st, d(2026, 4, 1), d(2026, 6, 30)), None);
|
||||
st.compare = Compare::PriorPeriod;
|
||||
// 91 days: the 91 days through March 31.
|
||||
assert_eq!(
|
||||
prior(&st, d(2026, 4, 1), d(2026, 6, 30)),
|
||||
Some((d(2025, 12, 31), d(2026, 3, 31)))
|
||||
);
|
||||
assert_eq!(
|
||||
prior(&st, d(2026, 3, 1), d(2026, 3, 1)),
|
||||
Some((d(2026, 2, 28), d(2026, 2, 28)))
|
||||
);
|
||||
assert_eq!(prior(&st, NaiveDate::MIN, d(2026, 1, 1)), None);
|
||||
st.compare = Compare::PriorYear;
|
||||
assert_eq!(
|
||||
prior(&st, d(2026, 4, 1), d(2026, 6, 30)),
|
||||
Some((d(2025, 4, 1), d(2025, 6, 30)))
|
||||
);
|
||||
assert_eq!(prior(&st, NaiveDate::MIN, d(2026, 1, 1)), None);
|
||||
}
|
||||
|
||||
/// too_many_columns: a split's column count, counted from the months
|
||||
/// (each started interval a column), only when past MAX_COLUMNS.
|
||||
#[test]
|
||||
fn too_many_columns_counts_the_columns_only_past_the_limit() {
|
||||
let d = |y, m, day| NaiveDate::from_ymd_opt(y, m, day).unwrap();
|
||||
assert_eq!(
|
||||
too_many_columns(d(2006, 1, 1), d(2026, 12, 31), Columns::Total),
|
||||
None
|
||||
);
|
||||
// 240 months, January 2007 through December 2026: at the limit.
|
||||
assert_eq!(
|
||||
too_many_columns(d(2007, 1, 15), d(2026, 12, 1), Columns::Month),
|
||||
None
|
||||
);
|
||||
// 241 months.
|
||||
assert_eq!(
|
||||
too_many_columns(d(2006, 12, 31), d(2026, 12, 1), Columns::Month),
|
||||
Some(241)
|
||||
);
|
||||
// 3,000 years by quarter, and by year.
|
||||
assert_eq!(
|
||||
too_many_columns(d(-500, 2, 1), d(2499, 11, 30), Columns::Quarter),
|
||||
Some((2999 * 12 + 9) / 3 + 1)
|
||||
);
|
||||
assert_eq!(
|
||||
too_many_columns(d(-500, 2, 1), d(2499, 11, 30), Columns::Year),
|
||||
Some((2999 * 12 + 9) / 12 + 1)
|
||||
);
|
||||
assert_eq!(
|
||||
too_many_columns(d(2000, 1, 1), d(2239, 12, 31), Columns::Year),
|
||||
None
|
||||
);
|
||||
}
|
||||
use super::*;
|
||||
|
||||
/// The fixed asset register report's tax columns are the register's:
|
||||
@@ -2049,7 +2185,7 @@ mod tests {
|
||||
today: Some(today),
|
||||
})
|
||||
.unwrap();
|
||||
let r = ledger_core::fixed_asset_register(&b.ledger, today);
|
||||
let r = ledger_core::fixed_asset_register(&b.ledger, today).unwrap();
|
||||
assert!(!r.rows.is_empty(), "the demo has an asset");
|
||||
assert_eq!(r.missing_tax_basis, 0, "the demo's asset has a tax basis");
|
||||
let t = asset_register(&b, today);
|
||||
|
||||
@@ -138,13 +138,13 @@ fn row(ui: &mut Ui, b: &Books, e: &EntryInfo, on: bool, since_update: f64) -> eg
|
||||
widgets::copy_item(
|
||||
ui,
|
||||
"Copy amount",
|
||||
&fmt::plain(&fmt::money(e.amount)).unwrap_or_default(),
|
||||
&fmt::plain(&fmt::money_or(e.amount)).unwrap_or_default(),
|
||||
);
|
||||
if !e.cash_effect.is_zero() {
|
||||
if !e.cash_effect.is_some_and(|c| c.is_zero()) {
|
||||
widgets::copy_item(
|
||||
ui,
|
||||
"Copy cash effect",
|
||||
&fmt::plain(&fmt::money(e.cash_effect)).unwrap_or_default(),
|
||||
&fmt::plain(&fmt::money_or(e.cash_effect)).unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
widgets::copy_item(ui, "Copy entry number", &format!("#{}", e.id));
|
||||
@@ -182,12 +182,11 @@ fn row(ui: &mut Ui, b: &Books, e: &EntryInfo, on: bool, since_update: f64) -> eg
|
||||
// icon and the amount. Cash in reads green with a plus, cash out with
|
||||
// a minus; entries that don't move cash show their size, muted.
|
||||
let text_left = left + 44.0;
|
||||
let (amount, color) = if e.cash_effect > rust_decimal::Decimal::ZERO {
|
||||
(format!("+{}", fmt::money(e.cash_effect)), p.positive)
|
||||
} else if e.cash_effect < rust_decimal::Decimal::ZERO {
|
||||
(fmt::money(e.cash_effect), p.text)
|
||||
} else {
|
||||
(fmt::money(e.amount), p.muted)
|
||||
let (amount, color) = match e.cash_effect {
|
||||
Some(c) if c > rust_decimal::Decimal::ZERO => (format!("+{}", fmt::money(c)), p.positive),
|
||||
Some(c) if c < rust_decimal::Decimal::ZERO => (fmt::money(c), p.text),
|
||||
Some(_) => (fmt::money_or(e.amount), p.muted),
|
||||
None => (fmt::CANT_COMPUTE.to_string(), p.muted),
|
||||
};
|
||||
let amount_w = painter
|
||||
.layout_no_wrap(amount.clone(), theme::semibold(14.0), color)
|
||||
@@ -295,3 +294,68 @@ fn filters(ui: &mut Ui, b: &Books, st: &mut State) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_support::{Build, d, find, harness, has, painted};
|
||||
|
||||
/// A transaction row: cash in green with a plus, cash out with its
|
||||
/// minus, an entry moving no cash its size, muted; the description
|
||||
/// 44 points right of the date; and its menu offers the cash effect
|
||||
/// only when there is one.
|
||||
#[test]
|
||||
fn a_transaction_row_says_how_it_moved_cash() {
|
||||
let mut b = Build::new("transactions");
|
||||
let (cash, capital, rent) = (b.cash, b.capital, b.rent);
|
||||
b.post_as("Deposit in", d(2026, 10, 2), cash, capital, 100_000);
|
||||
b.post_as("Rent out", d(2026, 10, 3), rent, cash, 25_000);
|
||||
b.post_as("Owner paid rent", d(2026, 10, 4), rent, capital, 4_000);
|
||||
let (_dir, books) = b.books();
|
||||
let mut h = harness(books, Route::Transactions);
|
||||
let texts = painted(h.output());
|
||||
let p = crate::theme::pal(&h.ctx);
|
||||
let money = |c: i64| fmt::money(rust_decimal::Decimal::new(c, 2));
|
||||
assert_eq!(
|
||||
find(&texts, &format!("+{}", money(100_000))).color,
|
||||
p.positive
|
||||
);
|
||||
assert_eq!(find(&texts, &money(-25_000)).color, p.text);
|
||||
assert_eq!(find(&texts, &money(4_000)).color, p.muted);
|
||||
assert!(!has(&texts, &format!("+{}", money(-25_000))));
|
||||
// The description beside its day: 44 points right of the date.
|
||||
let desc = find(&texts, "Deposit in");
|
||||
let day = texts
|
||||
.iter()
|
||||
.filter(|t| t.text == "2" && (t.pos.y - desc.pos.y).abs() < 30.0)
|
||||
.min_by(|a, b| a.pos.x.total_cmp(&b.pos.x))
|
||||
.expect("the day");
|
||||
assert!(
|
||||
(desc.pos.x - day.pos.x - 44.0).abs() < 1.0,
|
||||
"{} vs {}",
|
||||
desc.pos.x,
|
||||
day.pos.x
|
||||
);
|
||||
// The menus: "Copy cash effect" for cash moved, none for none.
|
||||
for (row, offered) in [("Deposit in", true), ("Owner paid rent", false)] {
|
||||
let at = find(&painted(h.output()), row).pos + egui::vec2(4.0, 4.0);
|
||||
h.hover_at(at);
|
||||
h.run_steps(2);
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton {
|
||||
pos: at,
|
||||
button: egui::PointerButton::Secondary,
|
||||
pressed,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
h.run_steps(2);
|
||||
}
|
||||
let menu = painted(h.output());
|
||||
let item = |label: &str| menu.iter().any(|t| t.text.ends_with(label));
|
||||
assert!(item("Copy entry number"), "{row}: no menu");
|
||||
assert_eq!(item("Copy cash effect"), offered, "{row}");
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -309,7 +309,7 @@ pub fn search(b: &Books, query: &str) -> Vec<Item> {
|
||||
out.push(Item {
|
||||
icon: icon::RECEIPT,
|
||||
title: format!("#{} {}", e.id, e.description),
|
||||
detail: format!("{} · {}", fmt::date(e.date), fmt::dollars(e.amount)),
|
||||
detail: format!("{} · {}", fmt::date(e.date), fmt::dollars_or(e.amount)),
|
||||
route: Route::Entry(e.id),
|
||||
score: score + bonus,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Test support: books built through the store, the viewer on one page,
|
||||
//! and what that page painted (text, place, color), for tests that check
|
||||
//! what a page says, not only that it renders.
|
||||
|
||||
use crate::app::{App, PageState};
|
||||
use crate::books::Books;
|
||||
use crate::nav::Route;
|
||||
use crate::{Source, data};
|
||||
use chrono::NaiveDate;
|
||||
use egui::{Color32, Pos2};
|
||||
use egui_kittest::Harness;
|
||||
use ledger_core::{AccountId, AccountType, Currency, Money, Side};
|
||||
use ledger_store::Store;
|
||||
use rust_decimal::Decimal;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
pub(crate) fn d(y: i32, m: u32, day: u32) -> NaiveDate {
|
||||
NaiveDate::from_ymd_opt(y, m, day).unwrap()
|
||||
}
|
||||
|
||||
/// Dollars and cents as cents.
|
||||
pub(crate) fn cents(c: i64) -> Decimal {
|
||||
Decimal::new(c, 2)
|
||||
}
|
||||
|
||||
/// The day the test books are viewed on.
|
||||
pub(crate) fn today() -> NaiveDate {
|
||||
d(2026, 10, 15)
|
||||
}
|
||||
|
||||
/// A scratch directory, removed when dropped.
|
||||
pub(crate) struct TempDir(pub PathBuf);
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
static DIRS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// A store to build test books in, and the accounts most tests use.
|
||||
pub(crate) struct Build {
|
||||
pub dir: TempDir,
|
||||
pub s: Store,
|
||||
pub cash: AccountId,
|
||||
pub capital: AccountId,
|
||||
pub rent: AccountId,
|
||||
}
|
||||
|
||||
impl Build {
|
||||
pub(crate) fn new(tag: &str) -> Build {
|
||||
let n = DIRS.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = TempDir(
|
||||
std::env::temp_dir().join(format!("ledger-gui-unit-{tag}-{}-{n}", std::process::id())),
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir.0);
|
||||
let mut s = Store::create(&dir.0.join("books-data"), Currency::USD).unwrap();
|
||||
let mut add =
|
||||
|code: &str, name: &str, ty| s.add_account(code, name, ty, None, false).unwrap();
|
||||
let cash = add("1000", "Cash", AccountType::Asset);
|
||||
let capital = add("3000", "Owner Capital", AccountType::Equity);
|
||||
let rent = add("6000", "Rent", AccountType::Expense);
|
||||
Build {
|
||||
dir,
|
||||
s,
|
||||
cash,
|
||||
capital,
|
||||
rent,
|
||||
}
|
||||
}
|
||||
|
||||
/// Post Dr `dr` / Cr `cr` `c` cents on `date`, with a receipt.
|
||||
pub(crate) fn post(&mut self, date: NaiveDate, dr: AccountId, cr: AccountId, c: i64) -> u64 {
|
||||
self.post_as("test", date, dr, cr, c)
|
||||
}
|
||||
|
||||
/// A draft, Dr `dr` / Cr `cr` `c` cents on `date`, described `what`.
|
||||
pub(crate) fn draft(
|
||||
&mut self,
|
||||
what: &str,
|
||||
date: NaiveDate,
|
||||
dr: AccountId,
|
||||
cr: AccountId,
|
||||
c: i64,
|
||||
) -> u64 {
|
||||
let usd = Money::new(cents(c), Currency::USD);
|
||||
let e = self.s.create_entry(date, what).unwrap();
|
||||
self.s.add_line(e, dr, Side::Debit, usd).unwrap();
|
||||
self.s.add_line(e, cr, Side::Credit, usd).unwrap();
|
||||
e
|
||||
}
|
||||
|
||||
/// [`Self::post`], described `what`.
|
||||
pub(crate) fn post_as(
|
||||
&mut self,
|
||||
what: &str,
|
||||
date: NaiveDate,
|
||||
dr: AccountId,
|
||||
cr: AccountId,
|
||||
c: i64,
|
||||
) -> u64 {
|
||||
let usd = Money::new(cents(c), Currency::USD);
|
||||
let e = self.s.create_entry(date, what).unwrap();
|
||||
self.s.add_line(e, dr, Side::Debit, usd).unwrap();
|
||||
self.s.add_line(e, cr, Side::Credit, usd).unwrap();
|
||||
self.s
|
||||
.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF r", None)
|
||||
.unwrap();
|
||||
self.s.post_entry(e).unwrap();
|
||||
e
|
||||
}
|
||||
|
||||
/// The books as the viewer loads them, on [`today`].
|
||||
pub(crate) fn books(self) -> (TempDir, Books) {
|
||||
let data_dir = self.dir.0.join("books-data");
|
||||
drop(self.s);
|
||||
let books = data::load_once(&Source {
|
||||
data_dir,
|
||||
books_toml: None,
|
||||
today: Some(today()),
|
||||
})
|
||||
.unwrap();
|
||||
(self.dir, books)
|
||||
}
|
||||
}
|
||||
|
||||
/// One text a frame painted.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Painted {
|
||||
pub text: String,
|
||||
pub pos: Pos2,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
pub color: Color32,
|
||||
}
|
||||
|
||||
impl Painted {
|
||||
/// The middle of its line.
|
||||
pub(crate) fn mid_y(&self) -> f32 {
|
||||
self.pos.y + self.height / 2.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Every filled rectangle a frame painted, with its fill.
|
||||
pub(crate) fn rects(out: &egui::FullOutput) -> Vec<(egui::Rect, Color32)> {
|
||||
fn walk(s: &egui::Shape, out: &mut Vec<(egui::Rect, Color32)>) {
|
||||
match s {
|
||||
egui::Shape::Rect(r) => out.push((r.rect, r.fill)),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut all = Vec::new();
|
||||
for c in &out.shapes {
|
||||
walk(&c.shape, &mut all);
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
/// Every text a frame painted.
|
||||
pub(crate) fn painted(out: &egui::FullOutput) -> Vec<Painted> {
|
||||
fn walk(s: &egui::Shape, out: &mut Vec<Painted>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => {
|
||||
let color = t
|
||||
.override_text_color
|
||||
.or_else(|| t.galley.job.sections.first().map(|s| s.format.color))
|
||||
.unwrap_or(t.fallback_color);
|
||||
out.push(Painted {
|
||||
text: t.galley.text().to_string(),
|
||||
pos: t.pos,
|
||||
width: t.galley.size().x,
|
||||
height: t.galley.size().y,
|
||||
color,
|
||||
});
|
||||
}
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut texts = Vec::new();
|
||||
for c in &out.shapes {
|
||||
walk(&c.shape, &mut texts);
|
||||
}
|
||||
texts
|
||||
}
|
||||
|
||||
/// The viewer on `route`, with page state set by `set`, after it has
|
||||
/// settled: what it painted, and its palette.
|
||||
pub(crate) fn render(
|
||||
books: Books,
|
||||
route: Route,
|
||||
set: impl FnOnce(&mut PageState),
|
||||
) -> (Vec<Painted>, &'static crate::theme::Palette) {
|
||||
let (texts, _, p) = render_all(books, route, set);
|
||||
(texts, p)
|
||||
}
|
||||
|
||||
/// [`render`], with the filled rectangles too.
|
||||
pub(crate) fn render_all(
|
||||
books: Books,
|
||||
route: Route,
|
||||
set: impl FnOnce(&mut PageState),
|
||||
) -> (
|
||||
Vec<Painted>,
|
||||
Vec<(egui::Rect, Color32)>,
|
||||
&'static crate::theme::Palette,
|
||||
) {
|
||||
let mut h = Harness::builder()
|
||||
.with_size(egui::vec2(1400.0, 2400.0))
|
||||
.build_eframe(|cc| App::with_books(&cc.egui_ctx, books, false, route));
|
||||
set(h.state_mut().state_mut());
|
||||
h.run_steps(4);
|
||||
let p = crate::theme::pal(&h.ctx);
|
||||
(painted(h.output()), rects(h.output()), p)
|
||||
}
|
||||
|
||||
/// The viewer on `route`, to drive: settled, fonts and theme as the app
|
||||
/// sets them.
|
||||
pub(crate) fn harness(books: Books, route: Route) -> Harness<'static, App> {
|
||||
let mut h = Harness::builder()
|
||||
.with_size(egui::vec2(1400.0, 2400.0))
|
||||
.build_eframe(|cc| App::with_books(&cc.egui_ctx, books, false, route));
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
/// The painted text `text`, which must be there.
|
||||
pub(crate) fn find<'a>(texts: &'a [Painted], text: &str) -> &'a Painted {
|
||||
texts.iter().find(|t| t.text == text).unwrap_or_else(|| {
|
||||
panic!(
|
||||
"{text:?} not painted: {:?}",
|
||||
texts.iter().map(|t| &t.text).collect::<Vec<_>>()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `text` was painted.
|
||||
pub(crate) fn has(texts: &[Painted], text: &str) -> bool {
|
||||
texts.iter().any(|t| t.text == text)
|
||||
}
|
||||
|
||||
/// The text painted on the same line as `label`, to its right (a row's
|
||||
/// amount).
|
||||
pub(crate) fn beside<'a>(texts: &'a [Painted], label: &str) -> &'a Painted {
|
||||
let l = find(texts, label);
|
||||
texts
|
||||
.iter()
|
||||
.filter(|t| (t.mid_y() - l.mid_y()).abs() < 3.0 && t.pos.x > l.pos.x + l.width)
|
||||
.min_by(|a, b| a.pos.x.total_cmp(&b.pos.x))
|
||||
.unwrap_or_else(|| panic!("nothing beside {label:?}"))
|
||||
}
|
||||
|
||||
/// The books of ledger-store's old-books fixture `name` (written by main
|
||||
/// 188c90ea), as the viewer loads them.
|
||||
pub(crate) fn old_books(name: &str) -> (TempDir, Books) {
|
||||
let from = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../ledger-store/tests/fixtures/old-books")
|
||||
.join(name);
|
||||
let n = DIRS.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = TempDir(std::env::temp_dir().join(format!(
|
||||
"ledger-gui-unit-old-{name}-{}-{n}",
|
||||
std::process::id()
|
||||
)));
|
||||
let _ = std::fs::remove_dir_all(&dir.0);
|
||||
let data_dir = dir.0.join("books-data");
|
||||
std::fs::create_dir_all(data_dir.join("blobs")).unwrap();
|
||||
std::fs::copy(from.join("journal.jsonl"), data_dir.join("journal.jsonl")).unwrap();
|
||||
let books = data::load_once(&Source {
|
||||
data_dir,
|
||||
books_toml: None,
|
||||
today: Some(today()),
|
||||
})
|
||||
.unwrap();
|
||||
(dir, books)
|
||||
}
|
||||
@@ -564,3 +564,25 @@ pub fn fit_font(
|
||||
}
|
||||
font((size * width / measured).floor().max(floor))
|
||||
}
|
||||
|
||||
/// A date picker for `d` (`id` its egui id salt), returning the date
|
||||
/// picked. The picker's calendar holds years -9999 through 9999; a date
|
||||
/// outside them (books an earlier version wrote may hold one, rules.md
|
||||
/// B-28) is shown as text and kept, never truncated into another year.
|
||||
pub fn date_picker(ui: &mut Ui, id: &str, d: chrono::NaiveDate) -> chrono::NaiveDate {
|
||||
use chrono::Datelike;
|
||||
let jiff_date = i16::try_from(d.year())
|
||||
.ok()
|
||||
.and_then(|y| jiff::civil::Date::new(y, d.month() as i8, d.day() as i8).ok());
|
||||
let Some(mut j) = jiff_date else {
|
||||
ui.label(crate::fmt::date(d));
|
||||
return d;
|
||||
};
|
||||
ui.add(
|
||||
egui_extras::DatePickerButton::new(&mut j)
|
||||
.id_salt(id)
|
||||
.calendar_week(false),
|
||||
);
|
||||
chrono::NaiveDate::from_ymd_opt(i32::from(j.year()), j.month() as u32, j.day() as u32)
|
||||
.unwrap_or(d)
|
||||
}
|
||||
Reference in new issue
Block a user