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:
51 files changed
+3201
-166
No files matched your search
@@ -60,6 +60,7 @@ pub const KNOWN_FEATURES: &[&str] = &[
|
||||
DISPOSAL_BEFORE_SERVICE,
|
||||
DEPRECIATION_CATCH_UP,
|
||||
PROJECTS,
|
||||
DOCUMENT_LINE_PROJECTS,
|
||||
];
|
||||
|
||||
/// Feature: `period.closed` closes to members with `"rounding":
|
||||
@@ -155,6 +156,13 @@ pub const ASSET_BASIS: &str = "asset_basis";
|
||||
/// silently).
|
||||
pub const PROJECTS: &str = "projects";
|
||||
|
||||
/// Feature: an `invoice.created` or `bill.created` line naming its project
|
||||
/// (`class_id`, rules.md B-37 item 8). An older version would restore the
|
||||
/// document without its lines' projects, silently. Its own feature, not
|
||||
/// `projects`': books that consented to projects before it existed must
|
||||
/// consent again before a document names one.
|
||||
pub const DOCUMENT_LINE_PROJECTS: &str = "document_line_projects";
|
||||
|
||||
/// The line type that declares the journal format.
|
||||
pub const FORMAT_SET: &str = "journal.format_set";
|
||||
|
||||
@@ -742,6 +750,44 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The version the live books run (every feature through `projects`)
|
||||
/// stops at a declaration of `document_line_projects` as newer, never
|
||||
/// restoring an invoice or bill without its lines' projects; and books
|
||||
/// that declared `projects` alone still wait for it (B-27, D-39).
|
||||
#[test]
|
||||
fn document_line_projects_is_its_own_feature() {
|
||||
assert!(KNOWN_FEATURES.contains(&DOCUMENT_LINE_PROJECTS));
|
||||
assert_ne!(DOCUMENT_LINE_PROJECTS, PROJECTS);
|
||||
let before: Vec<&str> = KNOWN_FEATURES
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|f| *f != DOCUMENT_LINE_PROJECTS)
|
||||
.collect();
|
||||
let l = line(
|
||||
FORMAT_SET,
|
||||
json!({"format": 2, "features": [PROJECTS, DOCUMENT_LINE_PROJECTS]}),
|
||||
);
|
||||
match declared_knowing(&l, &before) {
|
||||
Err(StoreError::NewerJournal { need, .. }) => {
|
||||
assert_eq!(need, "journal features document_line_projects")
|
||||
}
|
||||
other => panic!("expected NewerJournal, got {other:?}"),
|
||||
}
|
||||
let with_projects = JournalFormat {
|
||||
format: 2,
|
||||
features: before.iter().map(|f| f.to_string()).collect(),
|
||||
};
|
||||
assert!(matches!(
|
||||
with_projects.require_feature(DOCUMENT_LINE_PROJECTS),
|
||||
Err(StoreError::FormatUpgradePending { .. })
|
||||
));
|
||||
let up = with_projects.upgrade().expect("waits for it");
|
||||
assert_eq!(
|
||||
up.adds(),
|
||||
vec!["the journal feature document_line_projects"]
|
||||
);
|
||||
}
|
||||
|
||||
/// This version's format: the newest it reads, every feature it
|
||||
/// knows, each once, sorted (what new books and an upgrade declare).
|
||||
#[test]
|
||||
|
||||
@@ -2816,10 +2816,7 @@ impl Store {
|
||||
}
|
||||
|
||||
/// Journal an auto-posted two-line entry (debit one account, credit
|
||||
/// another for the same amount) through the standard entry.created /
|
||||
/// entry.line_added / entry.posted flow. Returns the predicted entry id
|
||||
/// and the journaled lines; the caller mutates the ledger afterwards
|
||||
/// and applies the lines to SQLite.
|
||||
/// another for the same amount): [`Self::journal_auto_lines`].
|
||||
fn journal_auto_entry(
|
||||
&mut self,
|
||||
date: NaiveDate,
|
||||
@@ -2827,10 +2824,32 @@ impl Store {
|
||||
debit_account: AccountId,
|
||||
credit_account: AccountId,
|
||||
amount: Decimal,
|
||||
) -> Result<(EntryId, Vec<JournalLine>), StoreError> {
|
||||
self.journal_auto_lines(
|
||||
date,
|
||||
description,
|
||||
&[
|
||||
(debit_account, Side::Debit, amount, None),
|
||||
(credit_account, Side::Credit, amount, None),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Journal an auto-posted entry of `lines` (account, side, amount,
|
||||
/// project) through the standard entry.created / entry.line_added /
|
||||
/// entry.posted flow, a tagged line's `entry.line_class_set` right
|
||||
/// after its `entry.line_added` (as `books.add_line` journals one).
|
||||
/// Returns the predicted entry id and the journaled lines; the caller
|
||||
/// mutates the ledger afterwards and applies the lines to SQLite.
|
||||
fn journal_auto_lines(
|
||||
&mut self,
|
||||
date: NaiveDate,
|
||||
description: &str,
|
||||
lines: &[(AccountId, Side, Decimal, Option<ClassId>)],
|
||||
) -> Result<(EntryId, Vec<JournalLine>), StoreError> {
|
||||
let entry_id = self.ledger.next_entry_id();
|
||||
let base = self.base_currency;
|
||||
let mut journaled = Vec::with_capacity(4);
|
||||
let mut journaled = Vec::with_capacity(lines.len() * 2 + 2);
|
||||
journaled.push(self.append_journal(
|
||||
"entry.created",
|
||||
json!({
|
||||
@@ -2839,7 +2858,7 @@ impl Store {
|
||||
"description": description,
|
||||
}),
|
||||
)?);
|
||||
for (account, side) in [(debit_account, Side::Debit), (credit_account, Side::Credit)] {
|
||||
for (index, &(account, side, amount, class)) in lines.iter().enumerate() {
|
||||
journaled.push(self.append_journal(
|
||||
"entry.line_added",
|
||||
json!({
|
||||
@@ -2853,7 +2872,30 @@ impl Store {
|
||||
"currency": base.code(),
|
||||
}),
|
||||
)?);
|
||||
if let Some(class) = class {
|
||||
journaled.push(self.append_journal(
|
||||
"entry.line_class_set",
|
||||
json!({
|
||||
"entry_id": entry_id,
|
||||
"line_index": index as u64,
|
||||
"class_id": class,
|
||||
}),
|
||||
)?);
|
||||
}
|
||||
}
|
||||
let posted: Vec<Value> = lines
|
||||
.iter()
|
||||
.map(|&(account, side, amount, class_id)| {
|
||||
journal_line_json(&ledger_core::JournalLine {
|
||||
account,
|
||||
side,
|
||||
amount: Money::new(amount, base),
|
||||
foreign_currency: None,
|
||||
foreign_amount: None,
|
||||
class_id,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
journaled.push(self.append_journal(
|
||||
"entry.posted",
|
||||
json!({
|
||||
@@ -2861,15 +2903,22 @@ impl Store {
|
||||
"date": date.to_string(),
|
||||
"description": description,
|
||||
"reversal_of": Option::<u64>::None,
|
||||
"lines": [
|
||||
plain_line_json(debit_account, Side::Debit, Money::new(amount, base)),
|
||||
plain_line_json(credit_account, Side::Credit, Money::new(amount, base)),
|
||||
],
|
||||
"lines": posted,
|
||||
}),
|
||||
)?);
|
||||
Ok((entry_id, journaled))
|
||||
}
|
||||
|
||||
/// The feature a document's lines need (rules.md B-27): a line naming
|
||||
/// a project is `document_line_projects`'s; a document naming none is
|
||||
/// written as every version before it wrote one.
|
||||
fn ensure_document_lines(&self, lines: &[DocumentLine]) -> Result<(), StoreError> {
|
||||
if lines.iter().any(|l| l.class_id.is_some()) {
|
||||
self.ensure_feature(crate::format::DOCUMENT_LINE_PROJECTS)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a customer. Journaled as `customer.added`.
|
||||
pub fn add_customer(&mut self, name: &str) -> Result<CustomerId, StoreError> {
|
||||
self.rehearse(|l| l.add_customer(name))?;
|
||||
@@ -2927,13 +2976,19 @@ impl Store {
|
||||
if let Some(pid) = self.ledger.closed_period_containing(date) {
|
||||
return Err(LedgerError::ClosedPeriod(pid, date.to_string()).into());
|
||||
}
|
||||
self.ensure_document_lines(&lines)?;
|
||||
let ar = self.ensure_control_account(&ledger_core::RECEIVABLES)?;
|
||||
let revenue = self.ensure_control_account(&ledger_core::REVENUE)?;
|
||||
let invoice_id = self.ledger.next_invoice_id();
|
||||
let total: Decimal = lines.iter().map(|l| l.amount).sum();
|
||||
let description = format!("Invoice {invoice_id}");
|
||||
let (entry_id, mut journaled) =
|
||||
self.journal_auto_entry(date, &description, ar, revenue, total)?;
|
||||
let mut posting = vec![(ar, Side::Debit, total, None)];
|
||||
posting.extend(
|
||||
arap::document_parts(&lines, "the invoice")?
|
||||
.into_iter()
|
||||
.map(|(class, amount)| (revenue, Side::Credit, amount, class)),
|
||||
);
|
||||
let (entry_id, mut journaled) = self.journal_auto_lines(date, &description, &posting)?;
|
||||
let doc_lines: Vec<Value> = lines.iter().map(document_line_json).collect();
|
||||
journaled.push(self.append_journal(
|
||||
"invoice.created",
|
||||
@@ -2987,13 +3042,18 @@ impl Store {
|
||||
if let Some(pid) = self.ledger.closed_period_containing(date) {
|
||||
return Err(LedgerError::ClosedPeriod(pid, date.to_string()).into());
|
||||
}
|
||||
self.ensure_document_lines(&lines)?;
|
||||
let expense = self.ensure_control_account(&ledger_core::GENERAL_EXPENSES)?;
|
||||
let ap = self.ensure_control_account(&ledger_core::PAYABLES)?;
|
||||
let bill_id = self.ledger.next_bill_id();
|
||||
let total: Decimal = lines.iter().map(|l| l.amount).sum();
|
||||
let description = format!("Bill {bill_id}");
|
||||
let (entry_id, mut journaled) =
|
||||
self.journal_auto_entry(date, &description, expense, ap, total)?;
|
||||
let mut posting: Vec<_> = arap::document_parts(&lines, "the bill")?
|
||||
.into_iter()
|
||||
.map(|(class, amount)| (expense, Side::Debit, amount, class))
|
||||
.collect();
|
||||
posting.push((ap, Side::Credit, total, None));
|
||||
let (entry_id, mut journaled) = self.journal_auto_lines(date, &description, &posting)?;
|
||||
let doc_lines: Vec<Value> = lines.iter().map(document_line_json).collect();
|
||||
journaled.push(self.append_journal(
|
||||
"bill.created",
|
||||
@@ -5422,10 +5482,16 @@ fn plain_line_json(account: AccountId, side: Side, amount: Money) -> Value {
|
||||
/// One invoice/bill document line as journal JSON. Amounts are decimal
|
||||
/// strings, never floats.
|
||||
fn document_line_json(l: &DocumentLine) -> Value {
|
||||
json!({
|
||||
let mut v = json!({
|
||||
"description": l.description,
|
||||
"amount": l.amount.to_string(),
|
||||
})
|
||||
});
|
||||
// Its project, behind the feature document_line_projects (rules.md
|
||||
// B-27, B-37 item 8); a line naming none is written as before it.
|
||||
if let Some(c) = l.class_id {
|
||||
v["class_id"] = json!(c);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Parse the `lines` array of an invoice/bill journal payload back into
|
||||
@@ -5442,6 +5508,18 @@ fn parse_document_lines(p: &Value) -> Result<Vec<DocumentLine>, StoreError> {
|
||||
amount: get_str(l, "amount")?
|
||||
.parse()
|
||||
.map_err(|_| StoreError::JournalCorrupt("bad line amount".into()))?,
|
||||
// Absent (every document before document_line_projects)
|
||||
// or null: no project.
|
||||
class_id: match l.get("class_id") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(c) => Some(
|
||||
c.as_u64()
|
||||
.and_then(|c| ClassId::try_from(c).ok())
|
||||
.ok_or_else(|| {
|
||||
StoreError::JournalCorrupt("bad document line class_id".into())
|
||||
})?,
|
||||
),
|
||||
},
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
|
||||
Reference in new issue
Block a user