Files
wanderbooks/crates/ledger-gui/src/test_support.rs
T
swaitsandClaude Opus 5.5 528c070605 feat: invoices and bills take a project, line by line (B-37 item 8)
A client project's invoiced revenue and a contractor's billed cost could
never count toward the project: books.create_invoice and books.create_bill
posted at once with untagged lines, and only a draft's line takes a class.
Job costing (B-37 item 3) collects a job's billings and the supplier
invoices for its direct costs on its cost sheet, so each document line
now takes an optional project.

The owner decided it on 2026-10-22 (plan D-43, rules.md B-37 item 8):
each line takes one project or none; a document spanning N projects is N
lines, each with its own amount; no percentage split, so every figure is
exact; a cost truly shared among projects names none on the document
and reaches projects only as entries of their own under the company's
monthly allocation convention, when books.conventions has one (otherwise
it stays untagged and the agent asks the human). The reasoning, stated
in B-37: job costing charges a job the costs traceable to it, whole, and
reaches shared costs only by allocation on a stated basis. ASC
340-40-25-7 counts as directly related both the costs traceable to a
contract (25-7(a), (b), (d), (e)) and allocations of costs that relate
directly to it (25-7(c)); 25-8 expenses general and administrative cost.
The books carry the first whole on the document's line and the second as
the allocation convention's own entries; neither is a percentage on the
document (sources/fasb-asc.md, 25-7 and 25-8 added). The handbook's
projects rule and the line's class parameter say the same, and no
handbook sentence lets a shared cost be split across a document's lines.

The accounting: the document's entry posts one revenue (an invoice's) or
expense (a bill's) line per project its lines name, in the order each is
first named, each the sum of that project's lines, and the untagged
lines' sum as one more line (arap::document_parts, conservation checked
by a proptest). A document naming no project therefore posts exactly the
one line every document posted before. The receivable or payable line is
never tagged: it is a balance-sheet line, which item 3 counts nothing;
the payments (receive_payment, pay_bill) move cash against it and take no
project either. Nothing but the projects moves: the P&L, the 1099
worksheet (payments made, B-19) and party totals (what moved the money,
B-35) read the same with or without the tags (twin-books test); the
projects with the untagged lines still partition the P&L.

- ledger-core: DocumentLine.class_id (serde-omitted when none, so old
  documents serialize as before); create_invoice / create_bill split the
  revenue or expense side by project and tag it; an unknown project is
  refused whole (atomically).
- ledger-store: a document line's project is journaled as class_id on
  invoice.created / bill.created, and the entry's line as
  entry.line_class_set right after its entry.line_added (the entry.posted
  lines carry class_id, as a hand-built entry's do). Behind a NEW journal
  feature, document_line_projects (KNOWN_FEATURES, declared by new books,
  asked for before the first journaled line, not even the control
  accounts written on refusal); not `projects`, which the live books
  already declared: the owner consents again at the next upgrade. A
  malformed class_id is corrupt; null or absent is none. Untagged
  documents journal byte for byte as before; old journals replay
  unchanged.
- ledger-mcp: each line takes class (id or name, resolved like
  add_line's, every one before anything is written); the result gains
  notes for a finished or abandoned project, and on an invoice for an
  on-spec project (is there now an agreement? on spec a hoped-for
  payment is no receivable, B-37 item 4), tagged anyway; books lacking
  the feature refuse with format_upgrade_pending. books.get_entry shows a
  line's class_id and project. The handbook's "an invoice or bill takes no
  project yet" caveat now depends on the books: gone where the feature is
  declared, an "until their format upgrade" note where it isn't.
- ledger-gui: an invoice's or bill's page (its entry's) lists the
  document's lines, each project a link that opens it; the demo's client
  invoices are tagged to "Client work", whose snapshot is now its revenue
  less its contractors. Looking at the page in a narrow window found a
  tagged line's tag pushing the amounts past the pane (any tagged entry):
  the name is now cut to leave the tag room, the tag itself at most half
  the cell.
- bookspec: an `invoice` event, and `lines` with `project` on a bill or
  an invoice; example projects-invoice-and-bill-lines-count-by-project,
  worked by hand, both projects client work (Zeta 3,500.00 - 1,200.00 =
  2,300.00; Harbor 200.00;
  untagged -1,750.00; together the P&L's 750.00; Dana's 1099 payments
  1,250.00).
- fuzz: fuzz_store_replay can declare journal features.
- Tests: core, store, MCP, viewer, the P2-served cutover fixture and a
  viewer/server parity test (its month lists the same length, not
  empty); a tagged document's reversal nets its projects to zero, live
  and replayed; books.get_entry's class_id; the handbook served as a
  resource both ways; each fix broken to confirm its test fails
  (docs/testing.md). Docs: rules.md B-27 and B-37 items 3 and 8,
  sources/fasb-asc.md, plan/served.md D-43,
  mcp-interface.md, testing.md, parity.md, plan/STATUS.md.

No proof changed (no kernel arithmetic: document_parts sums with the
existing document_total).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T3gXMVt7XJPi6ens1or9Dj
2026-10-22 19:28:40 -06:00

290 lines
8.8 KiB
Rust

//! 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,
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>, crate::theme::Palette) {
let (texts, _, p) = render_all(books, route, set);
(texts, p)
}
/// [`render`] in a window `width` points wide (a narrow one squeezes the
/// detail pane).
pub(crate) fn render_at(books: Books, route: Route, width: f32) -> Vec<Painted> {
let mut h = Harness::builder()
.with_size(egui::vec2(width, 2400.0))
.build_eframe(|cc| App::with_books(&cc.egui_ctx, books, false, route));
h.run_steps(4);
let ctx = h.ctx.clone();
h.state_mut().settle(&ctx);
h.run_steps(4);
painted(h.output())
}
/// [`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)>,
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,
today: Some(today()),
})
.unwrap();
(dir, books)
}