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
397 lines
14 KiB
Rust
397 lines
14 KiB
Rust
//! A project's snapshot (rules.md B-37 item 7) in the viewer and from the
|
|
//! books server, on the same books: `books.project`'s strings are the
|
|
//! figures the viewer's page draws (its `PageFigures` and `Snap`), to the
|
|
//! cent, to date, by account, by month with the running net, and for the
|
|
//! fiscal year. Both read ledger-core's `project_figures`; this checks
|
|
//! that neither side rearranges them.
|
|
#![cfg(feature = "gui")]
|
|
|
|
use chrono::NaiveDate;
|
|
use ledger_core::{AccountType, Currency, Money, ProjectFacts, ProjectKind, Side};
|
|
use ledger_gui::pages::projects::{Snap, page_figures};
|
|
use ledger_gui::{Source, data};
|
|
use rust_decimal::Decimal;
|
|
use serde_json::{Value, json};
|
|
use std::io::{BufRead, BufReader, Write};
|
|
use std::process::{Command, Stdio};
|
|
|
|
fn d(y: i32, m: u32, day: u32) -> NaiveDate {
|
|
NaiveDate::from_ymd_opt(y, m, day).unwrap()
|
|
}
|
|
|
|
fn usd(c: i64) -> Money {
|
|
Money::new(Decimal::new(c, 2), Currency::USD)
|
|
}
|
|
|
|
/// A decimal as the tools print an amount: two places.
|
|
fn s(v: Decimal) -> String {
|
|
format!("{v:.2}")
|
|
}
|
|
|
|
/// The books server over stdio (`wanderbooks dev-stdio`), one request at
|
|
/// a time.
|
|
struct Server {
|
|
child: std::process::Child,
|
|
stdin: std::process::ChildStdin,
|
|
stdout: BufReader<std::process::ChildStdout>,
|
|
id: u64,
|
|
}
|
|
|
|
impl Server {
|
|
fn start(data: &std::path::Path) -> Self {
|
|
let mut child = Command::new(env!("CARGO_BIN_EXE_wanderbooks"))
|
|
.arg("dev-stdio")
|
|
.arg("--data-dir")
|
|
.arg(data)
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::null())
|
|
.spawn()
|
|
.expect("spawn wanderbooks dev-stdio");
|
|
let stdin = child.stdin.take().unwrap();
|
|
let stdout = BufReader::new(child.stdout.take().unwrap());
|
|
let mut s = Server {
|
|
child,
|
|
stdin,
|
|
stdout,
|
|
id: 0,
|
|
};
|
|
s.ask(
|
|
"initialize",
|
|
json!({"protocolVersion": "2025-06-18", "capabilities": {},
|
|
"clientInfo": {"name": "projects-parity", "version": "0"}}),
|
|
);
|
|
writeln!(
|
|
s.stdin,
|
|
"{}",
|
|
json!({"jsonrpc": "2.0", "method": "notifications/initialized"})
|
|
)
|
|
.unwrap();
|
|
s
|
|
}
|
|
|
|
fn ask(&mut self, method: &str, params: Value) -> Value {
|
|
self.id += 1;
|
|
let msg = json!({"jsonrpc": "2.0", "id": self.id, "method": method, "params": params});
|
|
writeln!(self.stdin, "{msg}").unwrap();
|
|
self.stdin.flush().unwrap();
|
|
let mut line = String::new();
|
|
self.stdout.read_line(&mut line).expect("a response");
|
|
let resp: Value = serde_json::from_str(&line).expect("JSON");
|
|
assert_eq!(resp["id"], self.id, "{resp}");
|
|
resp
|
|
}
|
|
|
|
/// A tool's structured result.
|
|
fn tool(&mut self, name: &str, args: Value) -> Value {
|
|
let r = self.ask("tools/call", json!({"name": name, "arguments": args}));
|
|
let out = &r["result"];
|
|
assert_ne!(out["isError"], true, "{name}: {r}");
|
|
out["structuredContent"].clone()
|
|
}
|
|
}
|
|
|
|
impl Drop for Server {
|
|
fn drop(&mut self) {
|
|
let _ = self.child.kill();
|
|
let _ = self.child.wait();
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_projects_snapshot_is_the_same_in_the_viewer_and_from_the_server() {
|
|
let dir = tempfile::Builder::new()
|
|
.prefix("wb-projects-parity-")
|
|
.tempdir()
|
|
.unwrap();
|
|
let data = dir.path().join("books-data");
|
|
std::fs::write(
|
|
dir.path().join("wanderbooks.toml"),
|
|
"[company]\nname = \"Fernhill Labs\"\nfiscal_year_start = \"01-01\"\n\
|
|
[books]\nreceipt_threshold = \"1000000.00\"\ncash_accounts = [\"1000\"]\n",
|
|
)
|
|
.unwrap();
|
|
let today = d(2026, 10, 15);
|
|
let id = {
|
|
let mut st = ledger_store::Store::create(&data, Currency::USD).unwrap();
|
|
for (code, name, ty) in [
|
|
("1000", "Cash", AccountType::Asset),
|
|
("4000", "Design Services", AccountType::Revenue),
|
|
("6000", "Contractors", AccountType::Expense),
|
|
("6100", "Software", AccountType::Expense),
|
|
("6200", "Rent", AccountType::Expense),
|
|
] {
|
|
st.add_account(code, name, ty, None, false).unwrap();
|
|
}
|
|
let id = st
|
|
.add_project(
|
|
"Kestrel",
|
|
&ProjectFacts {
|
|
kind: Some(ProjectKind::OnSpec),
|
|
started_on: Some(d(2025, 11, 1)),
|
|
..Default::default()
|
|
},
|
|
)
|
|
.unwrap();
|
|
let code =
|
|
|st: &ledger_store::Store, c: &str| st.ledger().chart().find_by_code(c).unwrap().id;
|
|
let mut posted = Vec::new();
|
|
// (date, debit, credit, cents, tagged): last year's sale, this
|
|
// year's costs (one reversed), a refund, and rent (overhead).
|
|
for (date, dr, cr, c, tagged) in [
|
|
(d(2025, 11, 3), "1000", "4000", 100_000, true),
|
|
(d(2026, 2, 9), "6000", "1000", 40_000, true),
|
|
(d(2026, 3, 9), "6100", "1000", 12_345, true),
|
|
(d(2026, 5, 1), "4000", "1000", 10_000, true),
|
|
(d(2026, 6, 30), "6200", "1000", 150_000, false),
|
|
(d(2026, 8, 4), "6000", "1000", 22_222, true),
|
|
] {
|
|
let e = st.create_entry(date, "Line").unwrap();
|
|
let (a, b) = (code(&st, dr), code(&st, cr));
|
|
st.add_line(e, a, Side::Debit, usd(c)).unwrap();
|
|
st.add_line(e, b, Side::Credit, usd(c)).unwrap();
|
|
if tagged {
|
|
st.set_line_class(e, if dr == "1000" { 1 } else { 0 }, Some(id))
|
|
.unwrap();
|
|
}
|
|
st.post_entry(e).unwrap();
|
|
posted.push(e);
|
|
}
|
|
// The software, reversed in September.
|
|
st.reverse_entry(posted[2], d(2026, 9, 2), "Reverse software")
|
|
.unwrap();
|
|
id
|
|
};
|
|
let b = data::load_once(&Source {
|
|
data_dir: data.clone(),
|
|
today: Some(today),
|
|
})
|
|
.unwrap();
|
|
let mut server = Server::start(&data);
|
|
|
|
// To date, and by month over the viewer's chart span.
|
|
let page = page_figures(&b, id, Some(d(2025, 11, 1)), false);
|
|
let t = page.to_date.as_ref().unwrap();
|
|
let snap = Snap::to_date(t);
|
|
let ((start, end), months) = page.months.as_ref().unwrap();
|
|
assert_eq!((*start, *end), (d(2025, 11, 1), today));
|
|
let p = server.tool(
|
|
"books.project",
|
|
json!({"project": "Kestrel", "start": start.to_string(), "end": end.to_string()}),
|
|
);
|
|
let to = &p["to_date"];
|
|
assert_eq!(to["revenue"], s(snap.revenue));
|
|
assert_eq!(to["expenses"], s(snap.expenses));
|
|
assert_eq!(to["net"], s(snap.contribution));
|
|
assert_eq!(
|
|
to["margin_pct"],
|
|
snap.margin_pct
|
|
.map_or(Value::Null, |m| json!(m.to_string()))
|
|
);
|
|
assert_eq!(
|
|
to["unrecovered_cost"],
|
|
t.unrecovered_cost.map_or(Value::Null, |u| json!(s(u)))
|
|
);
|
|
// The figures themselves, so a slip on both sides can't pass: $900
|
|
// earned net of the refund, $622.22 of contractors (the software
|
|
// reversed), $277.78, 30.9% of revenue.
|
|
assert_eq!(
|
|
(to["net"].as_str(), to["margin_pct"].as_str()),
|
|
(Some("277.78"), Some("30.9"))
|
|
);
|
|
let accounts: Vec<(String, String, String)> = t
|
|
.revenue_by_account
|
|
.iter()
|
|
.map(|l| (l.code.clone(), "revenue".to_string(), s(l.amount)))
|
|
.chain(
|
|
t.expenses_by_account
|
|
.iter()
|
|
.map(|l| (l.code.clone(), "expense".to_string(), s(l.amount))),
|
|
)
|
|
.collect();
|
|
let served: Vec<(String, String, String)> = to["by_account"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|a| {
|
|
(
|
|
a["code"].as_str().unwrap().to_string(),
|
|
a["type"].as_str().unwrap().to_string(),
|
|
a["amount"].as_str().unwrap().to_string(),
|
|
)
|
|
})
|
|
.collect();
|
|
assert_eq!(served, accounts);
|
|
let by_month = p["period"]["by_month"].as_array().unwrap();
|
|
assert_eq!(by_month.len(), months.months.len());
|
|
for ((m, ours), net) in by_month
|
|
.iter()
|
|
.zip(&months.months)
|
|
.zip(&months.months_net_to_date)
|
|
{
|
|
assert_eq!(m["month"], ours.start.format("%Y-%m").to_string());
|
|
assert_eq!(m["revenue"], s(ours.revenue), "{m}");
|
|
assert_eq!(m["expenses"], s(ours.expenses), "{m}");
|
|
assert_eq!(m["net_to_date"], s(*net), "{m}");
|
|
}
|
|
assert_eq!(by_month.last().unwrap()["net_to_date"], to["net"]);
|
|
|
|
// This fiscal year, the snapshot's other view: books.project's
|
|
// default period.
|
|
let page = page_figures(&b, id, Some(d(2025, 11, 1)), true);
|
|
let y = page.year.as_ref().unwrap();
|
|
let fy = Snap::period(y);
|
|
let (fs, fe) = b.periods().statement(None, None).unwrap();
|
|
let p = server.tool(
|
|
"books.project",
|
|
json!({"project": "Kestrel", "start": fs.to_string(), "end": fe.to_string()}),
|
|
);
|
|
let period = &p["period"];
|
|
assert_eq!(period["start"], fs.to_string());
|
|
assert_eq!(period["revenue"], s(fy.revenue));
|
|
assert_eq!(period["expenses"], s(fy.expenses));
|
|
assert_eq!(period["net"], s(fy.contribution));
|
|
assert_eq!(
|
|
period["margin_pct"],
|
|
fy.margin_pct.map_or(Value::Null, |m| json!(m.to_string()))
|
|
);
|
|
assert_eq!(period["net"], "-722.22", "a refund and costs, no sale");
|
|
}
|
|
|
|
/// rules.md B-37 item 8: a project's invoiced revenue and billed costs,
|
|
/// made through the books server's own tools, read the same in the viewer
|
|
/// (its snapshot, and the invoice's and bill's pages: each line's
|
|
/// project) and from the server (books.project, books.get_entry).
|
|
#[test]
|
|
fn invoiced_and_billed_project_figures_are_the_same_in_the_viewer_and_from_the_server() {
|
|
let dir = tempfile::Builder::new()
|
|
.prefix("wb-projects-parity-docs-")
|
|
.tempdir()
|
|
.unwrap();
|
|
let data = dir.path().join("books-data");
|
|
std::fs::write(
|
|
dir.path().join("wanderbooks.toml"),
|
|
"[company]\nname = \"Fernhill Labs\"\nfiscal_year_start = \"01-01\"\n\
|
|
[books]\nreceipt_threshold = \"1000000.00\"\ncash_accounts = [\"1000\"]\n",
|
|
)
|
|
.unwrap();
|
|
let today = d(2026, 10, 15);
|
|
{
|
|
let mut st = ledger_store::Store::create(&data, Currency::USD).unwrap();
|
|
st.add_account("1000", "Cash", AccountType::Asset, None, false)
|
|
.unwrap();
|
|
}
|
|
let mut server = Server::start(&data);
|
|
server.tool(
|
|
"books.add_project",
|
|
json!({"name": "Kestrel", "kind": "client", "started_on": "2026-01-05"}),
|
|
);
|
|
server.tool("books.add_project", json!({"name": "Heron"}));
|
|
let cedar = server.tool("books.add_customer", json!({"name": "Cedar Client"}))["id"].clone();
|
|
let dana = server.tool("books.add_vendor", json!({"name": "Dana Illustration"}))["id"].clone();
|
|
let doc = |party: &Value, date: &str, lines: Value| json!({"party_id": party, "date": date, "due_date": date, "lines": lines});
|
|
let inv = server.tool(
|
|
"books.create_invoice",
|
|
doc(
|
|
&cedar,
|
|
"2026-02-02",
|
|
json!([
|
|
{"description": "Discovery", "amount": "1500.00", "class": "Kestrel"},
|
|
{"description": "Heron sketches", "amount": "250.00", "class": "Heron"},
|
|
{"description": "Travel", "amount": "80.00"},
|
|
]),
|
|
),
|
|
);
|
|
let inv2 = server.tool(
|
|
"books.create_invoice",
|
|
doc(
|
|
&cedar,
|
|
"2026-05-04",
|
|
json!([{"description": "Build", "amount": "4321.09", "class": "kestrel"}]),
|
|
),
|
|
);
|
|
let bill = server.tool(
|
|
"books.create_bill",
|
|
doc(
|
|
&dana,
|
|
"2026-03-09",
|
|
json!([
|
|
{"description": "Illustration", "amount": "987.65", "class": "Kestrel"},
|
|
{"description": "Postage", "amount": "12.00"},
|
|
]),
|
|
),
|
|
);
|
|
server.tool(
|
|
"books.receive_payment",
|
|
json!({"document_id": inv["id"], "date": "2026-02-20", "amount": "1830.00", "cash_account": "1000"}),
|
|
);
|
|
let b = data::load_once(&Source {
|
|
data_dir: data.clone(),
|
|
today: Some(today),
|
|
})
|
|
.unwrap();
|
|
let id = b.ledger.find_class_by_name("Kestrel").unwrap().id;
|
|
let page = page_figures(&b, id, Some(d(2026, 1, 5)), false);
|
|
let t = page.to_date.as_ref().unwrap();
|
|
let snap = Snap::to_date(t);
|
|
let p = server.tool(
|
|
"books.project",
|
|
json!({"project": "Kestrel", "start": "2026-01-01", "end": today.to_string()}),
|
|
);
|
|
let to = &p["to_date"];
|
|
assert_eq!(to["revenue"], s(snap.revenue));
|
|
assert_eq!(to["expenses"], s(snap.expenses));
|
|
assert_eq!(to["net"], s(snap.contribution));
|
|
assert_eq!(
|
|
to["margin_pct"],
|
|
snap.margin_pct
|
|
.map_or(Value::Null, |m| json!(m.to_string()))
|
|
);
|
|
// By hand: 1,500.00 + 4,321.09 invoiced, 987.65 billed.
|
|
assert_eq!(
|
|
(
|
|
to["revenue"].as_str(),
|
|
to["expenses"].as_str(),
|
|
to["net"].as_str()
|
|
),
|
|
(Some("5821.09"), Some("987.65"), Some("4833.44"))
|
|
);
|
|
let ((_, _), months) = page.months.as_ref().unwrap();
|
|
let by_month = p["period"]["by_month"].as_array().unwrap();
|
|
assert!(!by_month.is_empty(), "{p}");
|
|
assert_eq!(by_month.len(), months.months.len());
|
|
for (m, ours) in by_month.iter().zip(&months.months) {
|
|
assert_eq!(m["month"], ours.start.format("%Y-%m").to_string());
|
|
assert_eq!(m["revenue"], s(ours.revenue), "{m}");
|
|
assert_eq!(m["expenses"], s(ours.expenses), "{m}");
|
|
}
|
|
// Each document's lines: the viewer's page names the project the
|
|
// server's entry line carries.
|
|
for out in [&inv, &inv2, &bill] {
|
|
let entry = out["entry_id"].as_u64().unwrap();
|
|
let doc = ledger_gui::pages::entry::document_of(&b, entry).unwrap();
|
|
let viewer: Vec<Option<String>> = {
|
|
let mut seen: Vec<Option<String>> = Vec::new();
|
|
for l in doc.lines {
|
|
let name = l
|
|
.class_id
|
|
.and_then(|c| b.ledger.get_class(c))
|
|
.map(|c| c.name.clone());
|
|
if !seen.contains(&name) {
|
|
seen.push(name);
|
|
}
|
|
}
|
|
seen
|
|
};
|
|
let served = server.tool("books.get_entry", json!({"entry_id": entry}));
|
|
let served: Vec<Option<String>> = served["lines"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.filter(|l| l["code"] == "4000" || l["code"] == "6999")
|
|
.map(|l| l["project"].as_str().map(str::to_string))
|
|
.collect();
|
|
assert_eq!(viewer, served, "entry {entry}");
|
|
}
|
|
}
|