refactor(import): Decimal arithmetic goes through the kernel (K-U12)

The raw-decimal-arith detector counted 18 places in ledger-import before
and counts 0 after. No figure changes.

Signs (bank_csv, iif, invoice_pdf, report) go through money::neg and
money::signed_amount; sums and differences of figures from the books
(report, xlsx) through total_of, add_in_range and sub_in_range, which
are exact and panic only where the raw operator panicked.

Not a plain sum or sign: equal_shares (templates) now divides through
Amount::checked_div, rounds half-to-even to two places through
round_places, and gives the last owner a hundred minus the shares
given. Same numbers as before for every n >= 1; for n = 0 it returns no
shares where the raw division panicked (its one caller passes the
owners of a partnership, at least two).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude committed 2026-11-09 23:55:32 -07:00
1 parent 0de906e9ed
commit 0fb19b4b25
6 files changed
+43 -20

No files matched your search

+2 -2
View File
@@ -118,7 +118,7 @@ pub fn parse_bank_csv_with(
4 => { 4 => {
// Money out in the third column, money in in the fourth. // Money out in the third column, money in in the fourth.
match (!fields[2].is_empty(), !fields[3].is_empty()) { 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, true) => parse_amount(fields[3])?,
(false, false) => Decimal::ZERO, (false, false) => Decimal::ZERO,
(true, true) => { (true, true) => {
@@ -227,7 +227,7 @@ fn parse_amount(s: &str) -> Result<Decimal, BankCsvError> {
return Err(bad()); return Err(bad());
} }
if neg { if neg {
amount = -amount; amount = ledger_core::money::neg(amount);
} }
Ok(amount) Ok(amount)
} }
+1 -4
View File
@@ -994,10 +994,7 @@ pub fn journal_to_iif(
/// Debit positive, credit negative (Intuit: "Debit amounts are always /// Debit positive, credit negative (Intuit: "Debit amounts are always
/// positive, credit amounts are always negative"). /// positive, credit amounts are always negative").
fn signed(side: Side, amount: Decimal) -> Decimal { fn signed(side: Side, amount: Decimal) -> Decimal {
match side { ledger_core::money::signed_amount(side, amount)
Side::Debit => amount,
Side::Credit => -amount,
}
} }
/// Two decimal places, no thousands separators. /// Two decimal places, no thousands separators.
+1 -1
View File
@@ -266,7 +266,7 @@ pub fn template_data(doc: &InvoiceDoc) -> Result<serde_json::Value, PdfError> {
"total": dollars(doc.total), "total": dollars(doc.total),
"settled": doc.settled.iter().map(|(label, a)| serde_json::json!({ "settled": doc.settled.iter().map(|(label, a)| serde_json::json!({
"label": label, "label": label,
"amount": dollars(-*a), "amount": dollars(ledger_core::money::neg(*a)),
})).collect::<Vec<_>>(), })).collect::<Vec<_>>(),
"balance_label": "Balance due", "balance_label": "Balance due",
"balance": dollars(doc.balance), "balance": dollars(doc.balance),
+28 -9
View File
@@ -13,6 +13,8 @@
use chrono::{Datelike, NaiveDate}; use chrono::{Datelike, NaiveDate};
use ledger_core::RETAINED_EARNINGS_CODE; 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::{ use ledger_core::reports::{
BalanceSheetStatement, CashFlowSection, CashFlowStatement, MembersEquityStatement, BalanceSheetStatement, CashFlowSection, CashFlowStatement, MembersEquityStatement,
ProfitAndLossStatement, StatementLine, TrialBalance, ProfitAndLossStatement, StatementLine, TrialBalance,
@@ -275,9 +277,14 @@ pub fn balance_sheet(
.iter() .iter()
.map(|l| one(RowKind::Line, format!("{} {}", l.code, l.name), l.amount)), .map(|l| one(RowKind::Line, format!("{} {}", l.code, l.name), l.amount)),
); );
let retained: Decimal = retained.iter().map(|l| l.amount).sum::<Decimal>() let retained: Decimal = sub_in_range(
+ bs.current_earnings add_in_range(
- earnings.net_income_ytd; 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() { if !retained.is_zero() {
rows.push(one(RowKind::Line, "Retained earnings", retained)); rows.push(one(RowKind::Line, "Retained earnings", retained));
} }
@@ -288,7 +295,7 @@ pub fn balance_sheet(
)); ));
} else { } else {
rows.extend(account_lines(&bs.equity)); 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() { if !prior.is_zero() {
rows.push(one( rows.push(one(
RowKind::Line, RowKind::Line,
@@ -307,7 +314,7 @@ pub fn balance_sheet(
rows.push(one( rows.push(one(
RowKind::Total, RowKind::Total,
format!("Total liabilities and {}", equity_name.to_lowercase()), format!("Total liabilities and {}", equity_name.to_lowercase()),
bs.total_liabilities + bs.total_equity, add_in_range(bs.total_liabilities, bs.total_equity),
)); ));
statement( statement(
"Balance Sheet", "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, "Beginning balance", pick(&|c| c.beginning)),
row(RowKind::Line, "Contributions", pick(&|c| c.contributions)), row(RowKind::Line, "Contributions", pick(&|c| c.contributions)),
row(RowKind::Line, "Net income (loss)", pick(&|c| c.net_income)), 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() { if !me.total.other.is_zero() {
rows.push(row(RowKind::Line, "Other changes", pick(&|c| c.other))); 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 /// difference where they disagree (meals at 50%, penalties at 0%), and any
/// account still needing a category. /// account still needing a category.
pub fn tax_summary(ts: &ledger_core::TaxSummary) -> Statement { 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<Row> { let lines = |ls: &[ledger_core::TaxSummaryLine]| -> Vec<Row> {
ls.iter() ls.iter()
.map(|l| { .map(|l| {
@@ -519,8 +536,10 @@ pub fn tax_summary(ts: &ledger_core::TaxSummary) -> Statement {
.collect() .collect()
}; };
let total = |kind, label: &str, ls: &[ledger_core::TaxSummaryLine]| { let total = |kind, label: &str, ls: &[ledger_core::TaxSummaryLine]| {
let b: Decimal = ls.iter().map(|l| l.book).sum(); let b: Decimal = total_of(ls.iter(), |l| l.book)
let t: Decimal = ls.iter().map(|l| l.tax).sum(); .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)]) row(kind, label, vec![Some(b), Some(t), diff(b, t)])
}; };
let mut rows = vec![section("Income")]; let mut rows = vec![section("Income")];
+9 -2
View File
@@ -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 /// Equal shares for `n` owners as percents to two places, the last
/// absorbing the remainder so they sum to exactly 100. /// absorbing the remainder so they sum to exactly 100.
fn equal_shares(n: usize) -> Vec<Decimal> { fn equal_shares(n: usize) -> Vec<Decimal> {
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]; let mut v = vec![each; n];
if let Some((last, rest)) = v.split_last_mut() { if let Some((last, rest)) = v.split_last_mut() {
*last = Decimal::from(100) - rest.iter().sum::<Decimal>(); 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 v
} }
+2 -2
View File
@@ -387,11 +387,11 @@ fn general_journal(
match line.side { match line.side {
ledger_core::Side::Debit => { ledger_core::Side::Debit => {
number(sheet, row, 5, line.amount.amount, &f.plain)?; 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 => { ledger_core::Side::Credit => {
number(sheet, row, 6, line.amount.amount, &f.plain)?; 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; row += 1;