diff --git a/crates/ledger-import/src/bank_csv.rs b/crates/ledger-import/src/bank_csv.rs index eb64e976..f3f77245 100644 --- a/crates/ledger-import/src/bank_csv.rs +++ b/crates/ledger-import/src/bank_csv.rs @@ -118,7 +118,7 @@ pub fn parse_bank_csv_with( 4 => { // Money out in the third column, money in in the fourth. match (!fields[2].is_empty(), !fields[3].is_empty()) { - (true, false) => -parse_amount(fields[2])?, + (true, false) => ledger_core::money::neg(parse_amount(fields[2])?), (false, true) => parse_amount(fields[3])?, (false, false) => Decimal::ZERO, (true, true) => { @@ -227,7 +227,7 @@ fn parse_amount(s: &str) -> Result { return Err(bad()); } if neg { - amount = -amount; + amount = ledger_core::money::neg(amount); } Ok(amount) } diff --git a/crates/ledger-import/src/iif.rs b/crates/ledger-import/src/iif.rs index db1d4e11..478c1bbf 100644 --- a/crates/ledger-import/src/iif.rs +++ b/crates/ledger-import/src/iif.rs @@ -994,10 +994,7 @@ pub fn journal_to_iif( /// Debit positive, credit negative (Intuit: "Debit amounts are always /// positive, credit amounts are always negative"). fn signed(side: Side, amount: Decimal) -> Decimal { - match side { - Side::Debit => amount, - Side::Credit => -amount, - } + ledger_core::money::signed_amount(side, amount) } /// Two decimal places, no thousands separators. diff --git a/crates/ledger-import/src/invoice_pdf.rs b/crates/ledger-import/src/invoice_pdf.rs index 57cb33be..13210751 100644 --- a/crates/ledger-import/src/invoice_pdf.rs +++ b/crates/ledger-import/src/invoice_pdf.rs @@ -266,7 +266,7 @@ pub fn template_data(doc: &InvoiceDoc) -> Result { "total": dollars(doc.total), "settled": doc.settled.iter().map(|(label, a)| serde_json::json!({ "label": label, - "amount": dollars(-*a), + "amount": dollars(ledger_core::money::neg(*a)), })).collect::>(), "balance_label": "Balance due", "balance": dollars(doc.balance), diff --git a/crates/ledger-import/src/report.rs b/crates/ledger-import/src/report.rs index 27771448..57294795 100644 --- a/crates/ledger-import/src/report.rs +++ b/crates/ledger-import/src/report.rs @@ -13,6 +13,8 @@ use chrono::{Datelike, NaiveDate}; use ledger_core::RETAINED_EARNINGS_CODE; +use ledger_core::kernel::total_of; +use ledger_core::money::{add_in_range, sub_in_range}; use ledger_core::reports::{ BalanceSheetStatement, CashFlowSection, CashFlowStatement, MembersEquityStatement, ProfitAndLossStatement, StatementLine, TrialBalance, @@ -275,9 +277,14 @@ pub fn balance_sheet( .iter() .map(|l| one(RowKind::Line, format!("{} {}", l.code, l.name), l.amount)), ); - let retained: Decimal = retained.iter().map(|l| l.amount).sum::() - + bs.current_earnings - - earnings.net_income_ytd; + let retained: Decimal = sub_in_range( + add_in_range( + total_of(retained.iter(), |l| l.amount) + .expect("figures drawn from the books are in range, so their sum is"), + bs.current_earnings, + ), + earnings.net_income_ytd, + ); if !retained.is_zero() { rows.push(one(RowKind::Line, "Retained earnings", retained)); } @@ -288,7 +295,7 @@ pub fn balance_sheet( )); } else { rows.extend(account_lines(&bs.equity)); - let prior = bs.current_earnings - earnings.unclosed; + let prior = sub_in_range(bs.current_earnings, earnings.unclosed); if !prior.is_zero() { rows.push(one( RowKind::Line, @@ -307,7 +314,7 @@ pub fn balance_sheet( rows.push(one( RowKind::Total, format!("Total liabilities and {}", equity_name.to_lowercase()), - bs.total_liabilities + bs.total_equity, + add_in_range(bs.total_liabilities, bs.total_equity), )); statement( "Balance Sheet", @@ -482,7 +489,11 @@ pub fn members_equity(me: &MembersEquityStatement) -> Statement { row(RowKind::Line, "Beginning balance", pick(&|c| c.beginning)), row(RowKind::Line, "Contributions", pick(&|c| c.contributions)), row(RowKind::Line, "Net income (loss)", pick(&|c| c.net_income)), - row(RowKind::Line, "Distributions", pick(&|c| -c.distributions)), + row( + RowKind::Line, + "Distributions", + pick(&|c| ledger_core::money::neg(c.distributions)), + ), ]; if !me.total.other.is_zero() { rows.push(row(RowKind::Line, "Other changes", pick(&|c| c.other))); @@ -501,7 +512,13 @@ pub fn members_equity(me: &MembersEquityStatement) -> Statement { /// difference where they disagree (meals at 50%, penalties at 0%), and any /// account still needing a category. pub fn tax_summary(ts: &ledger_core::TaxSummary) -> Statement { - let diff = |b: Decimal, t: Decimal| if b == t { None } else { Some(b - t) }; + let diff = |b: Decimal, t: Decimal| { + if b == t { + None + } else { + Some(sub_in_range(b, t)) + } + }; let lines = |ls: &[ledger_core::TaxSummaryLine]| -> Vec { ls.iter() .map(|l| { @@ -519,8 +536,10 @@ pub fn tax_summary(ts: &ledger_core::TaxSummary) -> Statement { .collect() }; let total = |kind, label: &str, ls: &[ledger_core::TaxSummaryLine]| { - let b: Decimal = ls.iter().map(|l| l.book).sum(); - let t: Decimal = ls.iter().map(|l| l.tax).sum(); + let b: Decimal = total_of(ls.iter(), |l| l.book) + .expect("figures drawn from the books are in range, so their sum is"); + let t: Decimal = total_of(ls.iter(), |l| l.tax) + .expect("figures drawn from the books are in range, so their sum is"); row(kind, label, vec![Some(b), Some(t), diff(b, t)]) }; let mut rows = vec![section("Income")]; diff --git a/crates/ledger-import/src/templates.rs b/crates/ledger-import/src/templates.rs index 3f0ead70..1b477cdd 100644 --- a/crates/ledger-import/src/templates.rs +++ b/crates/ledger-import/src/templates.rs @@ -115,10 +115,17 @@ fn acct(code: &str, name: &str, t: &str, tax: Option<&str>) -> ChartRow { /// Equal shares for `n` owners as percents to two places, the last /// absorbing the remainder so they sum to exactly 100. fn equal_shares(n: usize) -> Vec { - let each = (Decimal::from(100) / Decimal::from(n as u64)).round_dp(2); + use ledger_core::kernel::{Amount, Rounding, round_places, total}; + let hundred = Decimal::from(100); + let Some(each) = Amount::checked_div(hundred, Decimal::from(n as u64)) + .and_then(|q| round_places(q, 2, Rounding::HalfToEven)) + else { + return Vec::new(); // no owners: no shares (the raw `/` panicked here) + }; let mut v = vec![each; n]; if let Some((last, rest)) = v.split_last_mut() { - *last = Decimal::from(100) - rest.iter().sum::(); + let given = total(rest.iter().copied()).expect("fewer than a hundred percent, n times"); + *last = Amount::checked_sub(hundred, given).expect("a hundred minus the shares given fits"); } v } diff --git a/crates/ledger-import/src/xlsx.rs b/crates/ledger-import/src/xlsx.rs index 288fdfda..d67d94c7 100644 --- a/crates/ledger-import/src/xlsx.rs +++ b/crates/ledger-import/src/xlsx.rs @@ -387,11 +387,11 @@ fn general_journal( match line.side { ledger_core::Side::Debit => { number(sheet, row, 5, line.amount.amount, &f.plain)?; - debits += line.amount.amount; + debits = ledger_core::money::add_in_range(debits, line.amount.amount); } ledger_core::Side::Credit => { number(sheet, row, 6, line.amount.amount, &f.plain)?; - credits += line.amount.amount; + credits = ledger_core::money::add_in_range(credits, line.amount.amount); } } row += 1; diff --git a/crates/ledger-mcp/src/server.rs b/crates/ledger-mcp/src/server.rs index fe3a7e61..7e2d51f5 100644 --- a/crates/ledger-mcp/src/server.rs +++ b/crates/ledger-mcp/src/server.rs @@ -1343,11 +1343,7 @@ fn preview_lines_for( .account_balance(*account_id) .map_err(|e| e.to_string())?; let normal = account.account_type.normal_side(); - let delta = if *side == normal { - amount.amount - } else { - -amount.amount - }; + let delta = ledger_core::money::on_side(normal, *side, amount.amount); let after = ledger_core::money::add_exact(before, delta, "the account's balance after the line") .map_err(|e| e.to_string())?; diff --git a/crates/ledger-mcp/src/tools/assets.rs b/crates/ledger-mcp/src/tools/assets.rs index 1d14f8a4..e2c20988 100644 --- a/crates/ledger-mcp/src/tools/assets.rs +++ b/crates/ledger-mcp/src/tools/assets.rs @@ -150,7 +150,7 @@ fn basis_out(a: &ledger_core::Asset) -> Result, String> { sec704c_1c_note: loss.map(|l| { format!( "a built-in loss of {}: it counts only for the contributing member(s); for the others the basis is treated as the value at contribution (IRC §704(c)(1)(C))", - money(-l) + money(ledger_core::money::neg(l)) ) }), sec704c_method: b.sec704c_method.map(|m| m.key().to_string()), @@ -748,7 +748,10 @@ impl BooksServer { accumulated_posted: figure(|r| r.accumulated_posted), accumulated_scheduled_through: figure(|r| r.accumulated_scheduled), unposted_depreciation: figure(|r| { - r.accumulated_scheduled - r.accumulated_posted + ledger_core::money::sub_in_range( + r.accumulated_scheduled, + r.accumulated_posted, + ) }), book_value: figure(|r| r.book_value), schedule_error, @@ -930,7 +933,7 @@ impl BooksServer { proceeds.amount, preview.catch_up_depreciation, if preview.gain_loss < Decimal::ZERO { - -preview.gain_loss + ledger_core::money::neg(preview.gain_loss) } else { Decimal::ZERO }, diff --git a/crates/ledger-mcp/src/tools/documents.rs b/crates/ledger-mcp/src/tools/documents.rs index d6c61f54..3b615d72 100644 --- a/crates/ledger-mcp/src/tools/documents.rs +++ b/crates/ledger-mcp/src/tools/documents.rs @@ -7,6 +7,7 @@ use super::*; use ledger_core::Terms; use ledger_core::arap::{self, PartySnapshot}; +use ledger_core::kernel::Amount; /// A document's id. fn doc_id(doc: ledger_core::DocRef) -> u64 { @@ -934,8 +935,7 @@ impl BooksServer { if !keep { continue; } - owed = owed - .checked_add(st.outstanding) + owed = Amount::checked_add(owed, st.outstanding) .ok_or("the total is too large to compute")?; rows.push(( due, diff --git a/crates/ledger-mcp/src/tools/evidence.rs b/crates/ledger-mcp/src/tools/evidence.rs index ff33e10f..c6889dbd 100644 --- a/crates/ledger-mcp/src/tools/evidence.rs +++ b/crates/ledger-mcp/src/tools/evidence.rs @@ -330,7 +330,7 @@ impl BooksServer { links: g.link.iter().map(|s| subject_out(&store, *s)).collect(), }) .collect(); - let withdrawn = out_groups.iter().map(|g| g.withdraw.len()).sum(); + let withdrawn = out_groups.iter().flat_map(|g| g.withdraw.iter()).count(); let digest = self.preview_of( &store, "books.consolidate_duplicates", diff --git a/crates/ledger-mcp/src/tools/helpers.rs b/crates/ledger-mcp/src/tools/helpers.rs index 373314a2..f0d1006e 100644 --- a/crates/ledger-mcp/src/tools/helpers.rs +++ b/crates/ledger-mcp/src/tools/helpers.rs @@ -7,6 +7,7 @@ use super::*; use ledger_core::InstrumentId; +use ledger_core::kernel::Amount; use ledger_store::StoreError; /// The book's id, as the commands given to agents name it: its folder's @@ -462,7 +463,7 @@ pub(crate) fn checked_sum( ) -> Result { values.into_iter().try_fold(Decimal::ZERO, |sum, v| { let v = v.map_err(|e| e.to_string())?; - sum.checked_add(v).ok_or_else(|| { + Amount::checked_add(sum, v).ok_or_else(|| { ledger_core::LedgerError::TooLargeToCompute(what.to_string()).to_string() }) }) @@ -548,7 +549,9 @@ pub(crate) fn lines_settled(entry: &JournalEntry) -> bool { .lines() .iter() .filter(|l| l.side == s) - .try_fold(Decimal::ZERO, |sum, l| sum.checked_add(l.amount.amount)) + .try_fold(Decimal::ZERO, |sum, l| { + Amount::checked_add(sum, l.amount.amount) + }) }; match (side(Side::Debit), side(Side::Credit)) { (Some(debits), Some(credits)) => !entry.lines().is_empty() && debits == credits, diff --git a/crates/ledger-mcp/src/tools/reports.rs b/crates/ledger-mcp/src/tools/reports.rs index 59d0569d..8e411d63 100644 --- a/crates/ledger-mcp/src/tools/reports.rs +++ b/crates/ledger-mcp/src/tools/reports.rs @@ -4,6 +4,7 @@ //! Split whole out of `server.rs` (plan/served.md 8.2 U0a). use super::*; +use ledger_core::money::{add_in_range, sub_in_range}; /// What the digest lists from the control check: each line on a control /// account that is no document's, and each document needing attention. @@ -37,18 +38,15 @@ fn movement_over( .iter() .flat_map(|e| e.lines()) .filter(|l| l.account == account), - |l| match l.side { - Side::Debit => l.amount.amount, - Side::Credit => -l.amount.amount, - }, + |l| ledger_core::money::signed_amount(l.side, l.amount.amount), "an account's movement", ) .map_err(|e| e.to_string())?; let account = ledger.chart().get(account).expect("account exists"); - Ok(match account.account_type.normal_side() { - Side::Debit => movement, - Side::Credit => -movement, - }) + Ok(ledger_core::money::signed_amount( + account.account_type.normal_side(), + movement, + )) } fn lines_out(lines: &[ledger_core::StatementLine]) -> Vec { @@ -1057,19 +1055,16 @@ impl BooksServer { Some(a) => a, _ => continue, }; - let signed = match line.side { - Side::Debit => line.amount.amount, - Side::Credit => -line.amount.amount, - }; // Normal-side positive. - let normal = match account.account_type.normal_side() { - Side::Debit => signed, - Side::Credit => -signed, - }; + let normal = ledger_core::money::on_side( + account.account_type.normal_side(), + line.side, + line.amount.amount, + ); let acc = by_class.entry(line.class_id).or_default(); match account.account_type { - AccountType::Revenue => acc.revenue += normal, - AccountType::Expense => acc.expenses += normal, + AccountType::Revenue => acc.revenue = add_in_range(acc.revenue, normal), + AccountType::Expense => acc.expenses = add_in_range(acc.expenses, normal), _ => {} } } @@ -1099,7 +1094,7 @@ impl BooksServer { class, revenue: money(acc.revenue), expenses: money(acc.expenses), - net_income: money(acc.revenue - acc.expenses), + net_income: money(sub_in_range(acc.revenue, acc.expenses)), }) .collect(); Ok(Json(ProfitAndLossByClassOut { diff --git a/crates/ledger-mcp/src/tools/settlements.rs b/crates/ledger-mcp/src/tools/settlements.rs index 0efc010c..b6322280 100644 --- a/crates/ledger-mcp/src/tools/settlements.rs +++ b/crates/ledger-mcp/src/tools/settlements.rs @@ -6,6 +6,7 @@ //! there and this slice's do not collide (plan/served.md 8.2 P4b S6). use super::*; +use ledger_core::money::{add_in_range, sub_in_range}; /// A document as the payment tools and the agings name it ("invoice:7", /// "bill:12"). @@ -257,7 +258,7 @@ fn payment_out( let mut documents = Vec::with_capacity(params.applications.len()); let mut deposited = Decimal::ZERO; for app in ¶ms.applications { - deposited += app.cash; + deposited = add_in_range(deposited, app.cash); let st = ledger .doc_state(app.doc, chrono::NaiveDate::MAX) .map_err(|e| e.to_string())? @@ -270,7 +271,7 @@ fn payment_out( }); } let fee = params.fee.as_ref().map_or(Decimal::ZERO, |f| f.amount); - deposited -= fee; + deposited = sub_in_range(deposited, fee); let (remaining, status) = match documents.as_slice() { [one] => (Some(one.outstanding.clone()), Some(one.status.clone())), _ => (None, None), @@ -413,7 +414,7 @@ impl BooksServer { Some((by, max)) if by >= as_of => ( Some(by.to_string()), Some(money(max)), - Some(money(st.outstanding - max)), + Some(money(sub_in_range(st.outstanding, max))), ), _ => (None, None, None), }; @@ -438,7 +439,7 @@ impl BooksServer { let mut by_date = Vec::new(); let mut running = Decimal::ZERO; for (bill, owed) in &bills { - running += owed; + running = add_in_range(running, *owed); match by_date.last_mut() { Some(DueDateTotalOut { date, amount }) if *date == bill.due_date => { *amount = money(running); diff --git a/crates/ledger-package/src/attention.rs b/crates/ledger-package/src/attention.rs index 055b4670..97c1b72e 100644 --- a/crates/ledger-package/src/attention.rs +++ b/crates/ledger-package/src/attention.rs @@ -100,6 +100,7 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use chrono::{Datelike, NaiveDate}; +use ledger_core::kernel::Amount; use ledger_core::parties::MoneyAccounts; use ledger_core::{ AccountId, AccountType, AssetId, DocRef, DocStatus, EntryId, EntryStatus, Ledger, LedgerError, @@ -344,7 +345,7 @@ pub fn find_with( if missing.len() > 3 { let total = missing .iter() - .try_fold(Decimal::ZERO, |t, e| t.checked_add(e.amount?)); + .try_fold(Decimal::ZERO, |t, e| Amount::checked_add(t, e.amount?)); let list: Vec = missing .iter() .map(|e| format!("{} ({}, {})", e.id, e.description, e.date)) @@ -428,7 +429,7 @@ pub fn find_with( if !due.is_empty() { let Some(total) = due .iter() - .try_fold(Decimal::ZERO, |t, (_, a)| t.checked_add(*a)) + .try_fold(Decimal::ZERO, |t, (_, a)| Amount::checked_add(t, *a)) else { out.push(cant_compute( format!("Amortization schedule \"{}\"", s.description), @@ -704,7 +705,10 @@ pub fn find_with( .map(|r| { [r.days_60, r.days_90, r.days_90_plus] .into_iter() - .try_fold(r.days_30, Decimal::checked_add) + .try_fold( + r.days_30, + ::checked_add, + ) .ok_or_else(too_large) }) .collect::, _>>()? @@ -713,7 +717,7 @@ pub fn find_with( .collect(); let total = late .iter() - .try_fold(Decimal::ZERO, |t, d| t.checked_add(*d)) + .try_fold(Decimal::ZERO, |t, d| Amount::checked_add(t, *d)) .ok_or_else(too_large)?; Ok::<_, LedgerError>((late.len(), total)) }; @@ -870,7 +874,7 @@ pub fn find_with( }; match lines .iter() - .try_fold(Decimal::ZERO, |t, l| t.checked_sub(l.amount)) + .try_fold(Decimal::ZERO, |t, l| Amount::checked_sub(t, l.amount)) { Some(amount) => written_off.push((inv.id, inv.number.clone(), last.date, amount)), None => out.push(cant_compute( @@ -1133,7 +1137,7 @@ pub fn find_with( ( format!( "{} of registered assets not in the books", - dollars(-unregistered) + dollars(ledger_core::money::neg(unregistered)) ), "Registered assets cost more than their cost accounts hold: a purchase entry may be missing.", ) @@ -1864,7 +1868,7 @@ fn paid_this_year( .max(today); let end = last.min(NaiveDate::from_ymd_opt(today.year(), 12, 31).expect("valid")); let a = ledger_core::parties::activity_with(ledger, party, (start, end), money, members); - a.paid - a.received + ledger_core::money::sub_in_range(a.paid, a.received) } /// A figure the books can't compute (BS-entry-4: books an earlier diff --git a/crates/ledger-package/src/invoice.rs b/crates/ledger-package/src/invoice.rs index 7c616a03..d3ae2960 100644 --- a/crates/ledger-package/src/invoice.rs +++ b/crates/ledger-package/src/invoice.rs @@ -269,7 +269,7 @@ pub fn invoice_document( { label.push_str(&format!(" · ref {r}")); } - settled.push((label, -l.amount)); + settled.push((label, ledger_core::money::neg(l.amount))); last_paid = Some(l.date); } for (label, amount) in [ diff --git a/crates/ledger-package/src/k1_tax.rs b/crates/ledger-package/src/k1_tax.rs index d9776b35..8d82c9ab 100644 --- a/crates/ledger-package/src/k1_tax.rs +++ b/crates/ledger-package/src/k1_tax.rs @@ -135,7 +135,7 @@ pub fn tax_basis_csv(ledger: &Ledger, names: &[String], tc: &TaxCapital) -> Stri Some(t) => [ money(book), money(t), - money(book - t), + money(ledger_core::money::sub_in_range(book, t)), "tax basis".into(), note, ], @@ -244,7 +244,7 @@ pub fn tax_basis_csv(ledger: &Ledger, names: &[String], tc: &TaxCapital) -> Stri name, "Reconciliation: less property distributed, at book", recon( - Some(-r.property_distributed), + Some(ledger_core::money::neg(r.property_distributed)), "the company's adjusted tax basis in it is the CPA's", ), ); diff --git a/crates/ledger-package/src/text.rs b/crates/ledger-package/src/text.rs index 188bb051..abc5d900 100644 --- a/crates/ledger-package/src/text.rs +++ b/crates/ledger-package/src/text.rs @@ -27,7 +27,7 @@ pub fn money(n: Decimal) -> String { // is what drops a negative zero. let mut n = ledger_import::round_display(n, n.scale().max(2)); if n.scale() < 2 { - n.rescale(2); + n = ledger_core::kernel::rescale_exact(n, 2).unwrap_or(n); } n.to_string() } @@ -47,7 +47,7 @@ pub fn share_text(n: Decimal) -> String { let mut n = n.normalize(); n = ledger_import::round_display(n, n.scale().max(2)); if n.scale() < 2 { - n.rescale(2); + n = ledger_core::kernel::rescale_exact(n, 2).unwrap_or(n); } n.to_string() } diff --git a/crates/ledger-package/src/vendor_1099.rs b/crates/ledger-package/src/vendor_1099.rs index d66b0f75..d78fd3fb 100644 --- a/crates/ledger-package/src/vendor_1099.rs +++ b/crates/ledger-package/src/vendor_1099.rs @@ -268,7 +268,7 @@ fn notes_for(ledger: &Ledger, r: &ledger_core::Vendor1099Report) -> Vec for p in &r.other_receipts { // Money in is negative; its reversal gives it back. let what = if p.amount < Decimal::ZERO { - format!("received {} from", money(-p.amount)) + format!("received {} from", money(ledger_core::money::neg(p.amount))) } else { format!("reversed {} received from", money(p.amount)) };