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
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-10-22 19:28:40 -06:00
1 parent e19df28bf2
commit 528c070605
51 files changed
+3201 -166

No files matched your search

+77 -9
View File
@@ -30,6 +30,10 @@
//! control or format characters, no line breaks), cut on a
//! character; a company with no name (empty, or the settings'
//! default name) is "a new company" (plan/served.md 4.1).
//! 6. A section says an invoice's or bill's lines take a project only
//! for books that declared the journal feature
//! `document_line_projects`; for the rest, that they wait for their
//! format upgrade (rules.md B-27, B-37 item 8).
//! ```
use crate::settings::Settings;
@@ -119,12 +123,22 @@ pub fn title(markdown: &str) -> &str {
/// reading order.
pub const ALL: &str = "all";
/// The section `id` (or [`ALL`]), rendered for these settings and the
/// books' base currency (None: no such section).
pub fn section(id: &str, settings: &Settings, currency: &str) -> Option<String> {
/// The section `id` (or [`ALL`]), rendered for these settings, the
/// books' base currency, and whether they declared the journal feature
/// `document_line_projects` (None: no such section).
pub fn section(
id: &str,
settings: &Settings,
currency: &str,
document_line_projects: bool,
) -> Option<String> {
let render = |md: &str| {
md.replace("{evidence_rule}", &evidence_rule(settings, currency))
.replace("{period_rule}", &period_rule())
.replace(
"{document_projects}",
document_projects_rule(document_line_projects),
)
};
if id == ALL {
let parts: Vec<String> = SECTIONS.iter().map(|(_, md)| render(md)).collect();
@@ -147,6 +161,17 @@ pub fn period_rule() -> String {
)
}
/// How an invoice's or bill's lines reach a project (rules.md B-37 item
/// 8), for books that declared the journal feature
/// `document_line_projects` or not yet (INVARIANT 6).
pub fn document_projects_rule(declared: bool) -> &'static str {
if declared {
"Tag an invoice's or bill's lines the same way (books.create_invoice and books.create_bill take class on each line): its revenue or cost counts toward the project, and it stays an invoice or bill in the agings; its payments take no project. Each line names one project or none: a document spanning several projects is one line per project, each with its own amount, never a percentage; a cost truly shared among projects names none on the document and reaches them only as entries of their own under the company's monthly allocation convention, when books.conventions has one. An invoice line naming an on-spec project returns a note: ask the human whether there is now an agreement, since a hoped-for payment is no receivable."
} else {
"An invoice or a bill takes no project in these books until their format upgrade (books.start's format_upgrade): link its document to the project, and when its lines must count, book it as a hand-built entry instead (books.draft_entry, books.add_line class), which then is no invoice or bill in the agings: ask the human which matters more."
}
}
/// The receipt rule in force (INVARIANT 2).
pub fn evidence_rule(settings: &Settings, currency: &str) -> String {
format!(
@@ -478,22 +503,65 @@ mod tests {
assert!(ids.insert(*id), "duplicate section {id}");
assert!(md.starts_with("# "), "{id} has no title");
assert!(!title(md).is_empty());
let text = section(id, &s, "USD").unwrap();
let text = section(id, &s, "USD", true).unwrap();
assert!(!text.contains("{evidence_rule}"), "{id}");
assert!(!text.contains("{period_rule}"), "{id}");
assert!(!text.contains("{document_projects}"), "{id}");
}
// The default period, in the descriptions' own words (B-30).
assert!(
section("tracing-figures", &s, "USD")
section("tracing-figures", &s, "USD", true)
.unwrap()
.contains(ledger_core::calendar::PeriodKind::Statement.describe())
);
assert!(
section("evidence-and-receipts", &s, "USD")
section("evidence-and-receipts", &s, "USD", true)
.unwrap()
.contains("every entry needs at least one receipt")
);
assert!(section("nope", &s, "USD").is_none());
assert!(section("nope", &s, "USD", true).is_none());
}
/// INVARIANT 6: the projects section tells books that declared
/// document_line_projects to tag an invoice's or bill's lines, and the
/// rest that it waits for their format upgrade; no other section
/// changes.
#[test]
fn document_projects_follow_the_books_feature() {
let s = settings("Co", Decimal::ZERO);
let with = section("projects", &s, "USD", true).unwrap();
let without = section("projects", &s, "USD", false).unwrap();
assert!(
with.contains("books.create_invoice and books.create_bill take class on each line")
);
assert!(!with.contains("takes no project"));
// The owner's decision (B-37 item 8, D-43): one project or none a
// line, no percentage split, a shared cost by the allocation
// convention.
assert!(with.contains("Each line names one project or none"));
assert!(with.contains("never a percentage"));
assert!(with.contains("monthly allocation convention, when books.conventions has one"));
assert!(with.contains("ask the human whether there is now an agreement"));
// No sentence may let the agent split a shared cost across a
// document's lines (D-43).
for text in [&with, &without] {
assert!(!text.contains("split a shared cost across lines"), "{text}");
assert!(text.contains("is never split on an invoice, a bill or an entry"));
assert!(
text.contains(
"when books.conventions has none, leave it untagged and ask the human"
)
);
}
assert!(without.contains("takes no project in these books until their format upgrade"));
assert!(!without.contains("take class on each line"));
for (id, _) in SECTIONS.iter().filter(|(id, _)| *id != "projects") {
assert_eq!(
section(id, &s, "USD", true),
section(id, &s, "USD", false),
"{id}"
);
}
}
/// A section's title is its heading's text, as the index and the
@@ -514,10 +582,10 @@ mod tests {
#[test]
fn the_whole_handbook_is_every_section_in_order() {
let s = settings("Co", Decimal::new(2500, 2));
let all = section(ALL, &s, "USD").unwrap();
let all = section(ALL, &s, "USD", true).unwrap();
let mut at = 0;
for (id, _) in SECTIONS {
let one = section(id, &s, "USD").unwrap();
let one = section(id, &s, "USD", true).unwrap();
let found = all[at..]
.find(&one)
.unwrap_or_else(|| panic!("{id} missing or out of order"));
+86 -30
View File
@@ -794,6 +794,16 @@ impl BooksServer {
self.live().current()
}
/// Whether the books declared the journal feature
/// `document_line_projects` (the handbook's projects section says how
/// an invoice's or bill's lines reach a project by it).
fn document_line_projects(&self) -> bool {
self.lock().is_ok_and(|s| {
s.journal_format()
.has_feature(ledger_store::format::DOCUMENT_LINE_PROJECTS)
})
}
/// The books' base currency code, e.g. "USD".
fn currency(&self) -> &str {
self.store.currency.code()
@@ -2636,6 +2646,54 @@ fn resolve_class(store: &Store, class: &str) -> Result<u32, String> {
}
}
/// An invoice's or bill's lines as the tool takes them: each amount
/// parsed and each project resolved ([`resolve_class`]) before anything is
/// written.
fn document_lines(
store: &Store,
lines: Vec<DocumentLineParam>,
) -> Result<Vec<DocumentLine>, String> {
lines
.into_iter()
.map(|l| {
Ok(DocumentLine {
description: l.description,
amount: parse_amount(&l.amount)?,
class_id: l
.class
.as_deref()
.map(|c| resolve_class(store, c))
.transpose()?,
})
})
.collect()
}
/// A document's notes, each project once, in the order first named: its
/// late-tag note ([`projects::late_tag_note`]) for a finished or abandoned
/// project, and on an invoice ([`projects::on_spec_invoice_note`]) one for
/// an on-spec project (rules.md B-37 items 4, 5 and 8).
fn document_notes(
ledger: &ledger_core::Ledger,
lines: &[DocumentLine],
invoice: bool,
) -> Vec<String> {
let mut named: Vec<u32> = Vec::new();
for c in lines.iter().filter_map(|l| l.class_id) {
if !named.contains(&c) {
named.push(c);
}
}
let mut notes = Vec::new();
for c in named {
notes.extend(projects::late_tag_note(ledger, c));
if invoice {
notes.extend(projects::on_spec_invoice_note(ledger, c));
}
}
notes
}
/// Preview lines with resulting balances for raw (account, side, amount) lines.
fn preview_lines_for(
store: &Store,
@@ -2967,10 +3025,12 @@ impl BooksServer {
params: Parameters<HandbookParams>,
) -> Result<Json<HandbookOut>, String> {
let settings = self.settings();
let declared = self.document_line_projects();
let sections = handbook::SECTIONS
.iter()
.map(|(id, _)| {
let text = handbook::section(id, &settings, self.currency()).unwrap_or_default();
let text =
handbook::section(id, &settings, self.currency(), declared).unwrap_or_default();
HandbookSectionOut {
id: id.to_string(),
title: handbook::title(&text).to_string(),
@@ -2982,7 +3042,7 @@ impl BooksServer {
let section = match params.0.section.as_deref().map(str::trim) {
None => None,
Some(id) => {
let text = handbook::section(id, &settings, self.currency()).ok_or_else(|| {
let text = handbook::section(id, &settings, self.currency(), declared).ok_or_else(|| {
let ids: Vec<&str> = handbook::SECTIONS.iter().map(|(id, _)| *id).collect();
format!(
"no handbook section {id:?}: the sections are {}, or \"{}\" for all of them",
@@ -4119,6 +4179,11 @@ impl BooksServer {
Side::Credit => "credit".to_string(),
},
amount: money(l.amount.amount),
class_id: l.class_id,
project: l
.class_id
.and_then(|c| store.ledger().get_class(c))
.map(|c| c.name.clone()),
}
})
.collect();
@@ -8489,7 +8554,7 @@ impl BooksServer {
#[tool(
name = "books.create_invoice",
title = "Create and post an invoice",
description = "Create a sales invoice. Auto-posts Dr Accounts Receivable / Cr Revenue. Lines are {description, amount} with decimal-string amounts.",
description = "Create a sales invoice. Auto-posts Dr Accounts Receivable / Cr Revenue. Lines are {description, amount, class?} with decimal-string amounts; class (a project: name or id, books.projects) tags that line's revenue: one revenue line per project, the untagged lines' as one; the receivable line is never tagged. Its result gains notes for a finished, abandoned or on-spec project (on spec: is there now an agreement?), tagged anyway.",
annotations(
read_only_hint = false,
destructive_hint = true,
@@ -8502,16 +8567,7 @@ impl BooksServer {
) -> Result<Json<CreateDocumentOut>, String> {
let p = params.0;
let mut store = self.lock()?;
let lines: Vec<DocumentLine> = p
.lines
.into_iter()
.map(|l| {
Ok(DocumentLine {
description: l.description,
amount: parse_amount(&l.amount)?,
})
})
.collect::<Result<_, String>>()?;
let lines = document_lines(&store, p.lines)?;
let first_new = store.ledger().next_account_id();
let id = store
.create_invoice(
@@ -8530,13 +8586,14 @@ impl BooksServer {
total: inv.total().map_err(|e| e.to_string())?.to_string(),
entry_id: inv.entry_id,
warnings: created_uncategorized(store.ledger(), first_new),
notes: document_notes(store.ledger(), &inv.lines, true),
}))
}
#[tool(
name = "books.create_bill",
title = "Create and post a bill",
description = "Create a vendor bill. Auto-posts Dr General Expenses / Cr Accounts Payable. Lines are {description, amount} with decimal-string amounts.",
description = "Create a vendor bill. Auto-posts Dr General Expenses / Cr Accounts Payable. Lines are {description, amount, class?} with decimal-string amounts; class (a project: name or id, books.projects) tags that line's cost: one expense line per project, the untagged lines' as one; the payable line is never tagged. Its result gains notes for a finished or abandoned project, tagged anyway.",
annotations(
read_only_hint = false,
destructive_hint = true,
@@ -8549,16 +8606,7 @@ impl BooksServer {
) -> Result<Json<CreateDocumentOut>, String> {
let p = params.0;
let mut store = self.lock()?;
let lines: Vec<DocumentLine> = p
.lines
.into_iter()
.map(|l| {
Ok(DocumentLine {
description: l.description,
amount: parse_amount(&l.amount)?,
})
})
.collect::<Result<_, String>>()?;
let lines = document_lines(&store, p.lines)?;
let first_new = store.ledger().next_account_id();
let id = store
.create_bill(
@@ -8577,6 +8625,7 @@ impl BooksServer {
total: bill.total().map_err(|e| e.to_string())?.to_string(),
entry_id: bill.entry_id,
warnings: created_uncategorized(store.ledger(), first_new),
notes: document_notes(store.ledger(), &bill.lines, false),
}))
}
@@ -9926,8 +9975,13 @@ impl BooksServer {
}
_ if path.starts_with(&format!("{}/", handbook::URI)) => {
let id = &path[handbook::URI.len() + 1..];
handbook::section(id, &self.settings(), self.currency())
.ok_or_else(|| format!("unknown handbook section: {id}"))
handbook::section(
id,
&self.settings(),
self.currency(),
self.document_line_projects(),
)
.ok_or_else(|| format!("unknown handbook section: {id}"))
}
_ if path.starts_with("books://receipts/") => {
let id: u64 = path
@@ -11212,10 +11266,12 @@ mod tests {
handbook::connect_text(&settings, "USD"),
));
for (id, _) in handbook::SECTIONS {
texts.push((
format!("handbook {id}"),
handbook::section(id, &settings, "USD").unwrap(),
));
for declared in [true, false] {
texts.push((
format!("handbook {id}"),
handbook::section(id, &settings, "USD", declared).unwrap(),
));
}
}
}
// Every tool the text names is one there is.
+15
View File
@@ -161,6 +161,21 @@ pub(super) fn late_tag_note(ledger: &Ledger, id: ClassId) -> Option<String> {
))
}
/// The note `books.create_invoice` gives for a line naming an on-spec
/// project (rules.md B-37 items 4 and 8): on spec, a hoped-for payment is
/// no receivable and no income until received, so an invoice for one
/// means there is now an agreement, or it shouldn't be an invoice.
pub(super) fn on_spec_invoice_note(ledger: &Ledger, id: ClassId) -> Option<String> {
let f = ledger.project_facts(id)?;
if f.kind != Some(ProjectKind::OnSpec) {
return None;
}
let name = &ledger.get_class(id)?.name;
Some(format!(
"project {name} is on spec: an invoice books a receivable and income, so is there now an agreement to be paid? If so, update its kind (books.update_project); if not, tell the human: on spec, a hoped-for payment is recorded only when received"
))
}
#[tool_router(router = projects_router, vis = "pub(super)")]
impl BooksServer {
#[tool(
+21
View File
@@ -1931,6 +1931,13 @@ pub struct EntryLineOut {
pub side: String,
/// Amount, decimal string.
pub amount: String,
/// The project (class) id the line is tagged with, if any (books.add_line
/// class, an invoice's or bill's line class).
#[serde(skip_serializing_if = "Option::is_none")]
pub class_id: Option<u32>,
/// That project's name.
#[serde(skip_serializing_if = "Option::is_none")]
pub project: Option<String>,
}
/// Result of `books.get_entry`: the full entry with lines and receipts.
@@ -3063,6 +3070,15 @@ pub struct DocumentLineParam {
pub description: String,
/// Line amount, decimal string.
pub amount: String,
/// The one project (name or id, as books.projects lists them) the
/// line's revenue (an invoice's) or cost (a bill's) belongs to, or
/// none. Several projects are several lines, each with its own amount,
/// never a percentage; a shared cost names none (the allocation
/// convention's own entries reach the projects). The posted
/// entry's revenue or expense line for it carries the tag; the
/// receivable or payable line never does.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub class: Option<String>,
}
/// Parameters for `books.create_invoice` / `books.create_bill`.
@@ -3091,6 +3107,11 @@ pub struct CreateDocumentOut {
/// (Revenue 4000, General Expenses 6999) has no tax category yet.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
/// One per finished or abandoned project a line names, as
/// `books.add_line`'s `note`, and on an invoice one per on-spec
/// project a line names (is there now an agreement?): tagged anyway.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notes: Vec<String>,
}
/// Parameters for `books.receive_payment` / `books.pay_bill`.