refactor(core): every report and book total goes through the kernel's checked sum

A raw Decimal + / += / .sum() panics at Decimal::MAX, and a replayed
journal line is accepted of any size (rules.md B-28), so a total of
restored figures must be exact or refused (B-21), never a crash. The
reports (P&L, balance sheet, general ledger, members' equity, asset
register), K-1 lines, tax-basis wholes, payouts, the 1099 split, the
audit's articulation check, the members close split and arap's
document_total now sum with kernel::total / total_of / total_try and
add or subtract with checked arithmetic, refusing with TooLargeToCompute.
money::sum_exact* and add_exact/sub_exact are the engine's thin wrappers
over the kernel (no second copy of the sum). form1099::sum3 was a copy of
the kernel's sum and is now kernel::total.

periods::allocate and allocate_last_absorbs (frozen replay rules) keep
their signatures and results to the cent; each gains a try_ twin that
returns TooLargeToCompute where the raw amount * share used to panic, and
the ledger's close split calls the twins.

Behaviour for every ordinary input is unchanged: no figure moves, no test
or golden edited. Infallible public signatures (trial_balance,
ProfitAndLossStatement::net_income, tax book_net, project_entries,
cash-flow kinds, the Regime) keep their raw sums; making them fallible
would change ~100 callers and is a decision, not a refactor.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-08 12:17:58 -07:00
1 parent b3d504067f
commit 3376c3d549
10 files changed
+368 -162

No files matched your search

+1 -3
View File
@@ -1064,9 +1064,7 @@ pub struct Invoice {
/// line as written (rules.md B-28), so its lines are bounded only by what /// line as written (rules.md B-28), so its lines are bounded only by what
/// the version that wrote it checked. /// the version that wrote it checked.
pub fn document_total(lines: &[DocumentLine], what: &str) -> Result<Decimal, LedgerError> { pub fn document_total(lines: &[DocumentLine], what: &str) -> Result<Decimal, LedgerError> {
lines crate::kernel::total_of(lines, |l| l.amount)
.iter()
.try_fold(Decimal::ZERO, |sum, l| sum.checked_add(l.amount))
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{what}'s total"))) .ok_or_else(|| LedgerError::TooLargeToCompute(format!("{what}'s total")))
} }
+10 -6
View File
@@ -333,7 +333,9 @@ pub fn check_equation(bs: &crate::reports::BalanceSheetStatement) -> Option<Find
/// Net income moved to equity by the closes dated through `through`: /// Net income moved to equity by the closes dated through `through`:
/// revenue closed less expenses closed, read off the closing entries' /// revenue closed less expenses closed, read off the closing entries'
/// lines. /// lines.
fn closed_net(ledger: &Ledger, through: NaiveDate) -> Decimal { /// `None` when the sum is past exact arithmetic (the check is skipped, as
/// `articulation` skips a statement it cannot make).
fn closed_net(ledger: &Ledger, through: NaiveDate) -> Option<Decimal> {
let mut net = Decimal::ZERO; let mut net = Decimal::ZERO;
for id in ledger.closing_entry_ids() { for id in ledger.closing_entry_ids() {
let Some(e) = ledger.get_entry(id) else { let Some(e) = ledger.get_entry(id) else {
@@ -351,11 +353,11 @@ fn closed_net(ledger: &Ledger, through: NaiveDate) -> Decimal {
Side::Credit => -l.amount.amount, Side::Credit => -l.amount.amount,
}; };
if matches!(a.account_type, AccountType::Revenue | AccountType::Expense) { if matches!(a.account_type, AccountType::Revenue | AccountType::Expense) {
net += signed; net = crate::kernel::Amount::checked_add(net, signed)?;
} }
} }
} }
net Some(net)
} }
fn articulation(ledger: &Ledger, through: NaiveDate) -> Option<Finding> { fn articulation(ledger: &Ledger, through: NaiveDate) -> Option<Finding> {
@@ -369,7 +371,7 @@ fn articulation(ledger: &Ledger, through: NaiveDate) -> Option<Finding> {
check_articulation( check_articulation(
pnl.net_income(), pnl.net_income(),
bs.current_earnings, bs.current_earnings,
closed_net(ledger, through), closed_net(ledger, through)?,
) )
} }
@@ -380,7 +382,8 @@ pub fn check_articulation(
current_earnings: Decimal, current_earnings: Decimal,
closed: Decimal, closed: Decimal,
) -> Option<Finding> { ) -> Option<Finding> {
(net_income != current_earnings + closed).then(|| { let explained = crate::kernel::Amount::checked_add(current_earnings, closed)?;
(net_income != explained).then(|| {
Finding::new( Finding::new(
"pnl_not_articulated", "pnl_not_articulated",
Subject::Books, Subject::Books,
@@ -522,7 +525,8 @@ fn schedules(ledger: &Ledger, through: NaiveDate) -> Vec<Finding> {
} }
}; };
if let Some((first, _)) = months.first() { if let Some((first, _)) = months.first() {
let total: Decimal = months.iter().map(|(_, a)| *a).sum(); let total = crate::kernel::total_of(&months, |&(_, a)| a)
.map_or_else(|| "a sum too large to compute".to_string(), |t| t.to_string());
out.push(Finding::new( out.push(Finding::new(
"schedule_behind", "schedule_behind",
Subject::Schedule(s.id), Subject::Schedule(s.id),
+5 -7
View File
@@ -704,9 +704,7 @@ fn entry_buckets(
} }
fn sum3(b: [Decimal; 3]) -> Result<Decimal, LedgerError> { fn sum3(b: [Decimal; 3]) -> Result<Decimal, LedgerError> {
b[0].checked_add(b[1]) kernel::total(b).ok_or_else(|| LedgerError::TooLargeToCompute("a payment's buckets".into()))
.and_then(|s| s.checked_add(b[2]))
.ok_or_else(|| LedgerError::TooLargeToCompute("a payment's buckets".into()))
} }
/// The vendor's part of `payment` when the entry names several parties: /// The vendor's part of `payment` when the entry names several parties:
@@ -763,13 +761,13 @@ fn split_share(b: [Decimal; 3], v: Decimal) -> Result<[Decimal; 3], LedgerError>
let q = num.checked_div(ap).ok_or_else(too_large)?; let q = num.checked_div(ap).ok_or_else(too_large)?;
let mut part = q.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::ToZero); let mut part = q.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::ToZero);
while times(part)? > num { while times(part)? > num {
part -= cent; part = part.checked_sub(cent).ok_or_else(too_large)?;
} }
while times(part + cent)? <= num { while times(part.checked_add(cent).ok_or_else(too_large)?)? <= num {
part += cent; part = part.checked_add(cent).ok_or_else(too_large)?;
} }
// The remainder, over the common denominator ap. // The remainder, over the common denominator ap.
rems[i] = num - times(part)?; rems[i] = num.checked_sub(times(part)?).ok_or_else(too_large)?;
parts[i] = part; parts[i] = part;
} }
kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?; kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?;
+63 -34
View File
@@ -66,6 +66,8 @@
//! 3001 1,500): 1,500.00 property each, no cash. //! 3001 1,500): 1,500.00 property each, no cash.
//! ``` //! ```
use crate::kernel::Amount;
use crate::money::{add_exact, sub_exact, sum_exact_of, sum_exact_try};
use crate::reports::{MemberCapital, members_equity}; use crate::reports::{MemberCapital, members_equity};
use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, PartyId, Side}; use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, PartyId, Side};
use chrono::NaiveDate; use chrono::NaiveDate;
@@ -178,10 +180,16 @@ pub fn k1_detail(
{ {
if closings.contains(&e.id()) { if closings.contains(&e.id()) {
for (i, m) in members.iter().enumerate() { for (i, m) in members.iter().enumerate() {
let effect: Decimal = std::iter::once(m.capital_account) let effect = sum_exact_try(
.chain(m.distribution_account) std::iter::once(m.capital_account).chain(m.distribution_account),
.map(|a| side_sum(e, Side::Credit, a) - side_sum(e, Side::Debit, a)) |a| {
.sum(); Amount::checked_sub(
side_sum(e, Side::Credit, a).ok()?,
side_sum(e, Side::Debit, a).ok()?,
)
},
"a member's closing effect",
)?;
if !effect.is_zero() { if !effect.is_zero() {
lines.push(K1Line { lines.push(K1Line {
member: i, member: i,
@@ -195,12 +203,12 @@ pub fn k1_detail(
} }
lines.extend(entry_lines(ledger, e, members, cash, places)?); lines.extend(entry_lines(ledger, e, members, cash, places)?);
} }
let total = |i: usize, k: K1Kind| -> Decimal { let total = |i: usize, k: K1Kind| -> Result<Decimal, LedgerError> {
lines sum_exact_of(
.iter() lines.iter().filter(|l| l.member == i && l.kind == k),
.filter(|l| l.member == i && l.kind == k) |l| l.amount,
.map(|l| l.amount) "a member's K-1 contributions",
.sum() )
}; };
let rows = me let rows = me
.members .members
@@ -211,30 +219,40 @@ pub fn k1_detail(
// Each entry's property is at most that member's credit in it, // Each entry's property is at most that member's credit in it,
// and contributions are those credits' sum: property never // and contributions are those credits' sum: property never
// exceeds contributions, and is never negative. // exceeds contributions, and is never negative.
let prop = total(i, K1Kind::PropertyContribution); let prop = total(i, K1Kind::PropertyContribution)?;
K1Row { Ok(K1Row {
name: col.name, name: col.name,
share: m.share, share: m.share,
beginning: col.beginning, beginning: col.beginning,
contributions_cash: col.contributions - prop, contributions_cash: sub_exact(
col.contributions,
prop,
"a member's cash contributions",
)?,
contributions_property: prop, contributions_property: prop,
net_income: col.net_income, net_income: col.net_income,
distributions: col.distributions, distributions: col.distributions,
other: col.other, other: col.other,
ending: col.ending, ending: col.ending,
} })
}) })
.collect(); .collect::<Result<_, LedgerError>>()?;
Ok(K1Detail { rows, lines }) Ok(K1Detail { rows, lines })
} }
/// Σ of an entry's lines on `account`, on `side`. /// Σ of an entry's lines on `account`, on `side`.
fn side_sum(e: &crate::JournalEntry, side: Side, account: AccountId) -> Decimal { fn side_sum(
e.lines() e: &crate::JournalEntry,
.iter() side: Side,
.filter(|l| l.side == side && l.account == account) account: AccountId,
.map(|l| l.amount.amount) ) -> Result<Decimal, LedgerError> {
.sum() sum_exact_of(
e.lines()
.iter()
.filter(|l| l.side == side && l.account == account),
|l| l.amount.amount,
"an entry's lines on an account",
)
} }
/// One entry's contribution and distribution lines, as [`k1_detail`] /// One entry's contribution and distribution lines, as [`k1_detail`]
@@ -256,33 +274,44 @@ pub(crate) fn entry_lines(
kind, kind,
amount, amount,
}; };
let pool: Decimal = e let pool = sum_exact_of(
.lines() e.lines()
.iter() .iter()
.filter(|l| l.side == Side::Debit && is_property_account(ledger, cash, l.account)) .filter(|l| l.side == Side::Debit && is_property_account(ledger, cash, l.account)),
.map(|l| l.amount.amount) |l| l.amount.amount,
.sum(); "an entry's property debits",
)?;
// Contributions are credits to capital (members_equity's). // Contributions are credits to capital (members_equity's).
let credits: Vec<Decimal> = members let credits: Vec<Decimal> = members
.iter() .iter()
.map(|m| side_sum(e, Side::Credit, m.capital_account)) .map(|m| side_sum(e, Side::Credit, m.capital_account))
.collect(); .collect::<Result<_, _>>()?;
let takes = share_property(pool, &credits, places)?; let takes = share_property(pool, &credits, places)?;
let mut lines = Vec::new(); let mut lines = Vec::new();
for (i, m) in members.iter().enumerate() { for (i, m) in members.iter().enumerate() {
let (credit, take) = (credits[i], takes[i]); let (credit, take) = (credits[i], takes[i]);
if !(credit - take).is_zero() { let cash_part = sub_exact(credit, take, "a member's cash contribution")?;
lines.push(line(i, K1Kind::CashContribution, credit - take)); if !cash_part.is_zero() {
lines.push(line(i, K1Kind::CashContribution, cash_part));
} }
if !take.is_zero() { if !take.is_zero() {
lines.push(line(i, K1Kind::PropertyContribution, take)); lines.push(line(i, K1Kind::PropertyContribution, take));
} }
// Distributions: debits to capital, net debits to the // Distributions: debits to capital, net debits to the
// distributions account (members_equity's). // distributions account (members_equity's).
let taken = side_sum(e, Side::Debit, m.capital_account) let from_distributions = match m.distribution_account {
+ m.distribution_account.map_or(Decimal::ZERO, |d| { None => Decimal::ZERO,
side_sum(e, Side::Debit, d) - side_sum(e, Side::Credit, d) Some(d) => sub_exact(
}); side_sum(e, Side::Debit, d)?,
side_sum(e, Side::Credit, d)?,
"a member's distributions",
)?,
};
let taken = add_exact(
side_sum(e, Side::Debit, m.capital_account)?,
from_distributions,
"a member's distributions",
)?;
if !taken.is_zero() { if !taken.is_zero() {
lines.push(line(i, K1Kind::Distribution, -taken)); lines.push(line(i, K1Kind::Distribution, -taken));
} }
+23 -9
View File
@@ -3821,17 +3821,26 @@ impl Ledger {
let shares: Vec<Decimal> = members.iter().map(|m| m.share).collect(); let shares: Vec<Decimal> = members.iter().map(|m| m.share).collect();
Ok(match to { Ok(match to {
CloseTo::MembersLastAbsorbs(_) => ( CloseTo::MembersLastAbsorbs(_) => (
periods::allocate_last_absorbs(net, &shares), periods::try_allocate_last_absorbs(net, &shares)?,
MemberRule::LastAbsorbs, MemberRule::LastAbsorbs,
), ),
CloseTo::MembersPerClose(_) => (periods::allocate(net, &shares), MemberRule::PerClose), CloseTo::MembersPerClose(_) => {
(periods::try_allocate(net, &shares)?, MemberRule::PerClose)
}
CloseTo::MembersRun(_) => { CloseTo::MembersRun(_) => {
// The run rule: what the run gives each member with this // The run rule: what the run gives each member with this
// close, less what it gave them before. // close, less what it gave them before.
let before = self.member_close_run(&member_key(members)); let before = self.member_close_run(&member_key(members));
let after = periods::allocate(before + net, &shares); let after = periods::try_allocate(
let prior = periods::allocate(before, &shares); crate::money::add_exact(before, net, "the members' close run")?,
let parts = after.iter().zip(&prior).map(|(a, p)| a - p).collect(); &shares,
)?;
let prior = periods::try_allocate(before, &shares)?;
let parts = after
.iter()
.zip(&prior)
.map(|(a, p)| crate::money::sub_exact(*a, *p, "the members' close run"))
.collect::<Result<_, _>>()?;
(parts, MemberRule::Run) (parts, MemberRule::Run)
} }
_ => { _ => {
@@ -3841,7 +3850,7 @@ impl Ledger {
let parts = if posts { let parts = if posts {
regime.allocate( regime.allocate(
&key, &key,
regime.closed + net, crate::money::add_exact(regime.closed, net, "the members' closed earnings")?,
&regime.given, &regime.given,
self.base_currency.allocation_places(), self.base_currency.allocation_places(),
)? )?
@@ -4044,7 +4053,8 @@ impl Ledger {
"a count of members closes starts at close 1 or later, not 0".into(), "a count of members closes starts at close 1 or later, not 0".into(),
)); ));
} }
let total: Decimal = members.iter().map(|m| m.share).sum(); let total =
crate::money::sum_exact_of(members, |m| m.share, "the members' shares")?;
if members.is_empty() if members.is_empty()
|| total != Decimal::ONE || total != Decimal::ONE
|| members.iter().any(|m| m.share <= Decimal::ZERO) || members.iter().any(|m| m.share <= Decimal::ZERO)
@@ -6396,7 +6406,7 @@ impl Ledger {
return Err(LedgerError::TooLargeToCompute(format!("{doc}'s figures"))); return Err(LedgerError::TooLargeToCompute(format!("{doc}'s figures")));
} }
}; };
let owed: Decimal = after[..=i].iter().sum(); let owed = crate::money::sum_exact(after[..=i].iter().copied(), &format!("{doc}'s figures"))?;
let on = grid[i]; let on = grid[i];
let payments: Vec<String> = self let payments: Vec<String> = self
.standing_payments(doc) .standing_payments(doc)
@@ -8415,7 +8425,11 @@ impl Ledger {
.ok_or(LedgerError::UnknownAccount(cash_account))?; .ok_or(LedgerError::UnknownAccount(cash_account))?;
self.check_controls(&PAYROLL)?; self.check_controls(&PAYROLL)?;
let payables = self.payroll_tax_payables(); let payables = self.payroll_tax_payables();
let total: Decimal = payables.iter().map(|(_, b)| *b).sum(); let total = crate::money::sum_exact_of(
&payables,
|(_, b)| *b,
"the payroll taxes payable",
)?;
if total.is_zero() { if total.is_zero() {
return Err(LedgerError::NothingToRemit); return Err(LedgerError::NothingToRemit);
} }
+45
View File
@@ -153,6 +153,51 @@ impl Money {
} }
} }
/// The exact sum of some figures ([`crate::kernel::total`]), or
/// `TooLargeToCompute` naming `what` when a running sum cannot be held:
/// the engine's way to total a column without a raw `.sum()` that would
/// panic at `Decimal::MAX` (rules.md B-21, B-28).
pub fn sum_exact(
values: impl IntoIterator<Item = Decimal>,
what: &str,
) -> Result<Decimal, LedgerError> {
crate::kernel::total(values).ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
}
/// [`sum_exact`] over a figure drawn from each item
/// ([`crate::kernel::total_of`]).
pub fn sum_exact_of<I>(
values: impl IntoIterator<Item = I>,
f: impl FnMut(I) -> Decimal,
what: &str,
) -> Result<Decimal, LedgerError> {
crate::kernel::total_of(values, f)
.ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
}
/// [`sum_exact`] over a derived figure that can itself be unrepresentable
/// ([`crate::kernel::total_try`]).
pub fn sum_exact_try<I>(
values: impl IntoIterator<Item = I>,
f: impl FnMut(I) -> Option<Decimal>,
what: &str,
) -> Result<Decimal, LedgerError> {
crate::kernel::total_try(values, f)
.ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
}
/// `a + b` exactly, or `TooLargeToCompute` naming `what` (a checked `+`).
pub fn add_exact(a: Decimal, b: Decimal, what: &str) -> Result<Decimal, LedgerError> {
crate::kernel::Amount::checked_add(a, b)
.ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
}
/// `a - b` exactly, or `TooLargeToCompute` naming `what` (a checked `-`).
pub fn sub_exact(a: Decimal, b: Decimal, what: &str) -> Result<Decimal, LedgerError> {
crate::kernel::Amount::checked_sub(a, b)
.ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
}
impl fmt::Debug for Money { impl fmt::Debug for Money {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.amount, self.currency) write!(f, "{} {}", self.amount, self.currency)
+15 -10
View File
@@ -17,6 +17,7 @@
//! no platform: callers (or a format-specific parser) supply the numbers //! no platform: callers (or a format-specific parser) supply the numbers
//! from the payout statement, which is the entry's receipt. //! from the payout statement, which is the entry's receipt.
use crate::money::{add_exact, sub_exact, sum_exact_of};
use crate::{AccountId, AccountType, ChartOfAccounts, ClassId, LedgerError, Side}; use crate::{AccountId, AccountType, ChartOfAccounts, ClassId, LedgerError, Side};
use rust_decimal::Decimal; use rust_decimal::Decimal;
@@ -165,23 +166,27 @@ pub fn payout_plan(
for a in &payout.adjustments { for a in &payout.adjustments {
check(a.account, a.amount, "adjustment", &[])?; check(a.account, a.amount, "adjustment", &[])?;
} }
let gross: Decimal = payout.revenue.iter().map(|l| l.amount).sum(); let gross = sum_exact_of(&payout.revenue, |l| l.amount, "the payout's revenue")?;
let fees: Decimal = payout.fees.iter().map(|l| l.amount).sum(); let fees = sum_exact_of(&payout.fees, |l| l.amount, "the payout's fees")?;
let adjustments: Decimal = payout let adjustments = sum_exact_of(
.adjustments &payout.adjustments,
.iter() |a| match a.side {
.map(|a| match a.side {
Side::Credit => a.amount, Side::Credit => a.amount,
Side::Debit => -a.amount, Side::Debit => -a.amount,
}) },
.sum(); "the payout's adjustments",
let expected = gross - fees + adjustments; )?;
let expected = add_exact(
sub_exact(gross, fees, "the payout's total")?,
adjustments,
"the payout's total",
)?;
if expected != payout.deposit { if expected != payout.deposit {
return bad(format!( return bad(format!(
"payout doesn't reconcile: gross {gross} − fees {fees} + adjustments \ "payout doesn't reconcile: gross {gross} − fees {fees} + adjustments \
{adjustments} = {expected}, but the deposit is {} (off by {})", {adjustments} = {expected}, but the deposit is {} (off by {})",
payout.deposit, payout.deposit,
payout.deposit - expected sub_exact(payout.deposit, expected, "the payout's difference")?
)); ));
} }
let mut plan = Vec::new(); let mut plan = Vec::new();
+46 -8
View File
@@ -124,22 +124,42 @@ pub fn allocate(
amount: rust_decimal::Decimal, amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal], shares: &[rust_decimal::Decimal],
) -> Vec<rust_decimal::Decimal> { ) -> Vec<rust_decimal::Decimal> {
try_allocate(amount, shares)
.expect("shares sum to 1, so the shortfall is under one cent per member")
}
/// [`allocate`], refusing with `TooLargeToCompute` instead of panicking
/// when a share of `amount` is beyond exact arithmetic (a replayed close
/// carries a journaled amount of any size, rules.md B-28). The same split,
/// to the cent, for every amount [`allocate`] accepts.
pub fn try_allocate(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
) -> Result<Vec<rust_decimal::Decimal>, LedgerError> {
use rust_decimal::{Decimal, RoundingStrategy::ToZero}; use rust_decimal::{Decimal, RoundingStrategy::ToZero};
let too_large = || LedgerError::TooLargeToCompute(format!("the members' shares of {amount}"));
let magnitude = amount.abs(); let magnitude = amount.abs();
let exact: Vec<Decimal> = shares.iter().map(|s| magnitude * s).collect(); let exact: Vec<Decimal> = shares
.iter()
.map(|s| magnitude.checked_mul(*s).ok_or_else(too_large))
.collect::<Result<_, _>>()?;
let mut parts: Vec<Decimal> = exact let mut parts: Vec<Decimal> = exact
.iter() .iter()
.map(|e| e.round_dp_with_strategy(2, ToZero)) .map(|e| e.round_dp_with_strategy(2, ToZero))
.collect(); .collect();
let remainders: Vec<Decimal> = exact.iter().zip(&parts).map(|(e, p)| e - p).collect(); let remainders: Vec<Decimal> = exact
.iter()
.zip(&parts)
.map(|(e, p)| e.checked_sub(*p).ok_or_else(too_large))
.collect::<Result<_, _>>()?;
crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2)) crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2))
.expect("shares sum to 1, so the shortfall is under one cent per member"); .ok_or_else(too_large)?;
if amount.is_sign_negative() { if amount.is_sign_negative() {
for p in &mut parts { for p in &mut parts {
*p = -*p; *p = -*p;
} }
} }
parts Ok(parts)
} }
/// The rule closes used before 2026-10-13: each share rounded half away /// The rule closes used before 2026-10-13: each share rounded half away
@@ -149,13 +169,31 @@ pub fn allocate_last_absorbs(
amount: rust_decimal::Decimal, amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal], shares: &[rust_decimal::Decimal],
) -> Vec<rust_decimal::Decimal> { ) -> Vec<rust_decimal::Decimal> {
try_allocate_last_absorbs(amount, shares).expect("allocated amounts are in range")
}
/// [`allocate_last_absorbs`], refusing with `TooLargeToCompute` instead of
/// panicking when `amount × share` or the plug is beyond exact arithmetic
/// (replay of a legacy close with a huge journaled amount, rules.md B-28).
/// The same split, to the cent, for every amount [`allocate_last_absorbs`]
/// accepts: this is the frozen rule, only its overflow now an error.
pub fn try_allocate_last_absorbs(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
) -> Result<Vec<rust_decimal::Decimal>, LedgerError> {
use rust_decimal::RoundingStrategy::MidpointAwayFromZero; use rust_decimal::RoundingStrategy::MidpointAwayFromZero;
let too_large = || LedgerError::TooLargeToCompute(format!("the members' shares of {amount}"));
let mut parts: Vec<_> = shares let mut parts: Vec<_> = shares
.iter() .iter()
.map(|s| (amount * s).round_dp_with_strategy(2, MidpointAwayFromZero)) .map(|s| {
.collect(); amount
crate::kernel::plug_last(amount, &mut parts).expect("allocated amounts are in range"); .checked_mul(*s)
parts .map(|p| p.round_dp_with_strategy(2, MidpointAwayFromZero))
.ok_or_else(too_large)
})
.collect::<Result<_, _>>()?;
crate::kernel::plug_last(amount, &mut parts).ok_or_else(too_large)?;
Ok(parts)
} }
/// What one members close gives each member: [`allocate`]'s split of the /// What one members close gives each member: [`allocate`]'s split of the
+139 -67
View File
@@ -4,6 +4,7 @@
//! (`docs/oracle.md`) diffs: the same fixture books through two engines must //! (`docs/oracle.md`) diffs: the same fixture books through two engines must
//! produce byte-identical [`snapshot`] output. //! produce byte-identical [`snapshot`] output.
use crate::money::{add_exact, sub_exact, sum_exact, sum_exact_of, sum_exact_try};
use crate::{AccountType, Class, ClassId, JournalEntry, JournalLine, Ledger, LedgerError}; use crate::{AccountType, Class, ClassId, JournalEntry, JournalLine, Ledger, LedgerError};
use chrono::NaiveDate; use chrono::NaiveDate;
use rust_decimal::Decimal; use rust_decimal::Decimal;
@@ -267,8 +268,8 @@ fn profit_and_loss_where(
-line.amount.amount -line.amount.amount
}; };
match account.account_type { match account.account_type {
AccountType::Revenue => revenue += signed, AccountType::Revenue => revenue = add_exact(revenue, signed, "total revenue")?,
AccountType::Expense => expenses += signed, AccountType::Expense => expenses = add_exact(expenses, signed, "total expenses")?,
_ => {} _ => {}
} }
} }
@@ -311,14 +312,16 @@ pub fn balance_sheet(ledger: &Ledger) -> Result<BalanceSheet, LedgerError> {
} }
let balance = ledger.account_balance(account.id)?; let balance = ledger.account_balance(account.id)?;
match account.account_type { match account.account_type {
AccountType::Asset => assets += balance, AccountType::Asset => assets = add_exact(assets, balance, "total assets")?,
AccountType::Liability => liabilities += balance, AccountType::Liability => {
AccountType::Equity => equity += balance, liabilities = add_exact(liabilities, balance, "total liabilities")?
}
AccountType::Equity => equity = add_exact(equity, balance, "total equity")?,
AccountType::Revenue | AccountType::Expense => {} AccountType::Revenue | AccountType::Expense => {}
} }
} }
let current_earnings = unclosed_earnings(ledger)?.net_income(); let current_earnings = unclosed_earnings(ledger)?.net_income();
equity += current_earnings; equity = add_exact(equity, current_earnings, "total equity")?;
Ok(BalanceSheet { Ok(BalanceSheet {
assets, assets,
liabilities, liabilities,
@@ -409,7 +412,8 @@ fn statement_lines(
crate::Side::Debit => line.amount.amount, crate::Side::Debit => line.amount.amount,
crate::Side::Credit => -line.amount.amount, crate::Side::Credit => -line.amount.amount,
}; };
*movement.entry(line.account).or_default() += signed; let slot = movement.entry(line.account).or_default();
*slot = add_exact(*slot, signed, "an account's movement")?;
} }
} }
let mut out = BTreeMap::new(); let mut out = BTreeMap::new();
@@ -514,8 +518,8 @@ fn profit_and_loss_counted(
_ => {} _ => {}
} }
} }
let total_revenue = revenue.iter().map(|l| l.amount).sum(); let total_revenue = sum_exact_of(&revenue, |l| l.amount, "total revenue")?;
let total_expenses = expenses.iter().map(|l| l.amount).sum(); let total_expenses = sum_exact_of(&expenses, |l| l.amount, "total expenses")?;
Ok(( Ok((
ProfitAndLossStatement { ProfitAndLossStatement {
start, start,
@@ -816,13 +820,21 @@ pub fn balance_sheet_as_of(
AccountType::Asset => assets.push(line), AccountType::Asset => assets.push(line),
AccountType::Liability => liabilities.push(line), AccountType::Liability => liabilities.push(line),
AccountType::Equity => equity.push(line), AccountType::Equity => equity.push(line),
AccountType::Revenue => current_earnings += line.amount, AccountType::Revenue => {
AccountType::Expense => current_earnings -= line.amount, current_earnings = add_exact(current_earnings, line.amount, "current earnings")?
}
AccountType::Expense => {
current_earnings = sub_exact(current_earnings, line.amount, "current earnings")?
}
} }
} }
let total_assets = assets.iter().map(|l| l.amount).sum(); let total_assets = sum_exact_of(&assets, |l| l.amount, "total assets")?;
let total_liabilities = liabilities.iter().map(|l| l.amount).sum(); let total_liabilities = sum_exact_of(&liabilities, |l| l.amount, "total liabilities")?;
let total_equity = equity.iter().map(|l| l.amount).sum::<Decimal>() + current_earnings; let total_equity = add_exact(
sum_exact_of(&equity, |l| l.amount, "total equity")?,
current_earnings,
"total equity",
)?;
Ok(BalanceSheetStatement { Ok(BalanceSheetStatement {
as_of, as_of,
assets, assets,
@@ -945,7 +957,8 @@ pub fn general_ledger(
crate::Side::Credit => -line.amount.amount, crate::Side::Credit => -line.amount.amount,
}; };
if entry.date() < start { if entry.date() < start {
*begin.entry(line.account).or_default() += signed; let slot = begin.entry(line.account).or_default();
*slot = add_exact(*slot, signed, "an account's beginning balance")?;
continue; continue;
} }
if entry.date() > end { if entry.date() > end {
@@ -998,9 +1011,13 @@ pub fn general_ledger(
let (mut total_debits, mut total_credits) = (Decimal::ZERO, Decimal::ZERO); let (mut total_debits, mut total_credits) = (Decimal::ZERO, Decimal::ZERO);
let mut posted = Vec::with_capacity(lines.len()); let mut posted = Vec::with_capacity(lines.len());
for (side, amount, mut p) in lines { for (side, amount, mut p) in lines {
balance += if side == normal { amount } else { -amount }; balance = add_exact(
total_debits += p.debit; balance,
total_credits += p.credit; if side == normal { amount } else { -amount },
"an account's running balance",
)?;
total_debits = add_exact(total_debits, p.debit, "an account's total debits")?;
total_credits = add_exact(total_credits, p.credit, "an account's total credits")?;
p.balance = balance; p.balance = balance;
posted.push(p); posted.push(p);
} }
@@ -1180,7 +1197,7 @@ pub fn members_equity(
return Err(LedgerError::InvalidMembers("no members given".to_string())); return Err(LedgerError::InvalidMembers("no members given".to_string()));
} }
let shares: Vec<Decimal> = members.iter().map(|m| m.share).collect(); let shares: Vec<Decimal> = members.iter().map(|m| m.share).collect();
let total_share: Decimal = shares.iter().sum(); let total_share = sum_exact(shares.iter().copied(), "the members' shares")?;
if total_share != Decimal::ONE || shares.iter().any(|s| *s <= Decimal::ZERO) { if total_share != Decimal::ONE || shares.iter().any(|s| *s <= Decimal::ZERO) {
return Err(LedgerError::InvalidMembers(format!( return Err(LedgerError::InvalidMembers(format!(
"member shares must be positive and sum to 1, got {total_share}" "member shares must be positive and sum to 1, got {total_share}"
@@ -1210,23 +1227,23 @@ pub fn members_equity(
let end_bs = balance_sheet_as_of(ledger, end)?; let end_bs = balance_sheet_as_of(ledger, end)?;
// Capital account balances before the period, and their movement in it. // Capital account balances before the period, and their movement in it.
let capital_before = |id: crate::AccountId| -> Decimal { let capital_before = |id: crate::AccountId| -> Result<Decimal, LedgerError> {
let mut m = Decimal::ZERO; let mut m = Decimal::ZERO;
for e in ledger.posted_entries().filter(|e| e.date() < start) { for e in ledger.posted_entries().filter(|e| e.date() < start) {
for l in e.lines().iter().filter(|l| l.account == id) { for l in e.lines().iter().filter(|l| l.account == id) {
match l.side { m = match l.side {
crate::Side::Credit => m += l.amount.amount, crate::Side::Credit => add_exact(m, l.amount.amount, "a member's capital")?,
crate::Side::Debit => m -= l.amount.amount, crate::Side::Debit => sub_exact(m, l.amount.amount, "a member's capital")?,
} };
} }
} }
m Ok(m)
}; };
// Contributions and distributions move a capital account; a closing // Contributions and distributions move a capital account; a closing
// entry allocating earnings into it is income, already counted below. // entry allocating earnings into it is income, already counted below.
let closings = ledger.closing_entry_ids(); let closings = ledger.closing_entry_ids();
let cancelled = cancelled_in_span(ledger, start, end); let cancelled = cancelled_in_span(ledger, start, end);
let flows = |id: crate::AccountId| -> (Decimal, Decimal) { let flows = |id: crate::AccountId| -> Result<(Decimal, Decimal), LedgerError> {
let (mut credits, mut debits) = (Decimal::ZERO, Decimal::ZERO); let (mut credits, mut debits) = (Decimal::ZERO, Decimal::ZERO);
for e in ledger.posted_entries().filter(|e| { for e in ledger.posted_entries().filter(|e| {
e.date() >= start e.date() >= start
@@ -1236,35 +1253,48 @@ pub fn members_equity(
}) { }) {
for l in e.lines().iter().filter(|l| l.account == id) { for l in e.lines().iter().filter(|l| l.account == id) {
match l.side { match l.side {
crate::Side::Credit => credits += l.amount.amount, crate::Side::Credit => {
crate::Side::Debit => debits += l.amount.amount, credits = add_exact(credits, l.amount.amount, "a member's contributions")?
}
crate::Side::Debit => {
debits = add_exact(debits, l.amount.amount, "a member's distributions")?
}
} }
} }
} }
(credits, debits) Ok((credits, debits))
}; };
// A member's capital is their capital account plus their distributions // A member's capital is their capital account plus their distributions
// account (a debit balance, so it reduces capital). // account (a debit balance, so it reduces capital).
let capital: Vec<Decimal> = members let capital: Vec<Decimal> = members
.iter() .iter()
.map(|m| { .map(|m| {
capital_before(m.capital_account) add_exact(
+ m.distribution_account.map_or(Decimal::ZERO, capital_before) capital_before(m.capital_account)?,
m.distribution_account
.map_or(Ok(Decimal::ZERO), capital_before)?,
"a member's capital",
)
}) })
.collect(); .collect::<Result<_, _>>()?;
// (contributions, distributions): credits to capital are // (contributions, distributions): credits to capital are
// contributions; debits to capital and net debits to the distributions // contributions; debits to capital and net debits to the distributions
// account are distributions. // account are distributions.
let flow: Vec<(Decimal, Decimal)> = members let flow: Vec<(Decimal, Decimal)> = members
.iter() .iter()
.map(|m| { .map(|m| {
let (credits, debits) = flows(m.capital_account); let (credits, debits) = flows(m.capital_account)?;
let (dc, dd) = m let (dc, dd) = m
.distribution_account .distribution_account
.map_or((Decimal::ZERO, Decimal::ZERO), flows); .map_or(Ok((Decimal::ZERO, Decimal::ZERO)), flows)?;
(credits, debits + dd - dc) let distributions = sub_exact(
add_exact(debits, dd, "a member's distributions")?,
dc,
"a member's distributions",
)?;
Ok((credits, distributions))
}) })
.collect(); .collect::<Result<_, LedgerError>>()?;
// Everything in equity that isn't a capital account is partnership // Everything in equity that isn't a capital account is partnership
// earnings not yet distributed. Each member's share of it is allocated // earnings not yet distributed. Each member's share of it is allocated
@@ -1272,26 +1302,32 @@ pub fn members_equity(
// depends on which statement shows it: one statement's ending is the // depends on which statement shows it: one statement's ending is the
// next one's beginning, to the minor unit (a capital account is one // next one's beginning, to the minor unit (a capital account is one
// running balance: Treas. Reg. §1.704-1(b)(2)(iv)(b)). // running balance: Treas. Reg. §1.704-1(b)(2)(iv)(b)).
let capital_through = |id: crate::AccountId, through: NaiveDate| -> Decimal { let capital_through =
let mut m = Decimal::ZERO; |id: crate::AccountId, through: NaiveDate| -> Result<Decimal, LedgerError> {
for e in ledger.posted_entries().filter(|e| e.date() <= through) { let mut m = Decimal::ZERO;
for l in e.lines().iter().filter(|l| l.account == id) { for e in ledger.posted_entries().filter(|e| e.date() <= through) {
match l.side { for l in e.lines().iter().filter(|l| l.account == id) {
crate::Side::Credit => m += l.amount.amount, m = match l.side {
crate::Side::Debit => m -= l.amount.amount, crate::Side::Credit => {
add_exact(m, l.amount.amount, "a member's capital")?
}
crate::Side::Debit => sub_exact(m, l.amount.amount, "a member's capital")?,
};
} }
} }
} Ok(m)
m };
};
let capital_end: Vec<Decimal> = members let capital_end: Vec<Decimal> = members
.iter() .iter()
.map(|m| { .map(|m| {
capital_through(m.capital_account, end) add_exact(
+ m.distribution_account capital_through(m.capital_account, end)?,
.map_or(Decimal::ZERO, |d| capital_through(d, end)) m.distribution_account
.map_or(Ok(Decimal::ZERO), |d| capital_through(d, end))?,
"a member's capital",
)
}) })
.collect(); .collect::<Result<_, _>>()?;
// As of a date, a member's share of the earnings not yet in capital is // As of a date, a member's share of the earnings not yet in capital is
// what the next members close would give them of it: their split of // what the next members close would give them of it: their split of
// everything closed to these members and shares (the regime's closes // everything closed to these members and shares (the regime's closes
@@ -1309,38 +1345,68 @@ pub fn members_equity(
let nothing = vec![Decimal::ZERO; members.len()]; let nothing = vec![Decimal::ZERO; members.len()];
let unclosed_share = |undistributed: Decimal, regime: &crate::ledger::Regime| { let unclosed_share = |undistributed: Decimal, regime: &crate::ledger::Regime| {
let closed = regime.allocate(&key, regime.closed, &nothing, places)?; let closed = regime.allocate(&key, regime.closed, &nothing, places)?;
regime.allocate(&key, regime.closed + undistributed, &closed, places) let whole = add_exact(regime.closed, undistributed, "the members' closed earnings")?;
regime.allocate(&key, whole, &closed, places)
}; };
let end_regime = ledger.members_regime(&key, Some(end)); let end_regime = ledger.members_regime(&key, Some(end));
let begin_alloc = unclosed_share( let begin_alloc = unclosed_share(
begin_bs.total_equity - capital.iter().sum::<Decimal>(), sub_exact(
begin_bs.total_equity,
sum_exact(capital.iter().copied(), "the members' capital")?,
"the members' undistributed earnings",
)?,
&ledger.members_regime(&key, Some(day_before)), &ledger.members_regime(&key, Some(day_before)),
)?; )?;
let end_alloc = unclosed_share( let end_alloc = unclosed_share(
end_bs.total_equity - capital_end.iter().sum::<Decimal>(), sub_exact(
end_bs.total_equity,
sum_exact(capital_end.iter().copied(), "the members' capital")?,
"the members' undistributed earnings",
)?,
&end_regime, &end_regime,
)?; )?;
let explained = flow.iter().map(|(c, d)| c - d).sum::<Decimal>() + pnl.net_income(); let explained = add_exact(
sum_exact_try(
flow.iter(),
|&(c, d)| crate::kernel::Amount::checked_sub(c, d),
"the members' net contributions",
)?,
pnl.net_income(),
"the period's explained equity",
)?;
// "Other" is split anew on each statement, its tied unit to the member // "Other" is split anew on each statement, its tied unit to the member
// the count as of `end` lists first, as the ending's are: a reorder of // the count as of `end` lists first, as the ending's are: a reorder of
// the members in the settings moves no cent between their other (and // the members in the settings moves no cent between their other (and
// so their income) either. // so their income) either.
let other_alloc = end_regime.allocate( let other_alloc = end_regime.allocate(
&key, &key,
end_bs.total_equity - begin_bs.total_equity - explained, sub_exact(
sub_exact(end_bs.total_equity, begin_bs.total_equity, "the change in equity")?,
explained,
"the change in equity",
)?,
&nothing, &nothing,
places, places,
)?; )?;
let mut cols = Vec::with_capacity(members.len()); let mut cols = Vec::with_capacity(members.len());
for (i, m) in members.iter().enumerate() { for (i, m) in members.iter().enumerate() {
let beginning = capital[i] + begin_alloc[i]; let beginning = add_exact(capital[i], begin_alloc[i], "a member's beginning capital")?;
let ending = capital_end[i] + end_alloc[i]; let ending = add_exact(capital_end[i], end_alloc[i], "a member's ending capital")?;
let (contributions, distributions) = flow[i]; let (contributions, distributions) = flow[i];
// The member's income is what the roll-forward leaves: their share // The member's income is what the roll-forward leaves: their share
// of the period's income, give or take the rounding cent that keeps // of the period's income, give or take the rounding cent that keeps
// the running balance exact. The members' incomes sum to net income. // the running balance exact. The members' incomes sum to net income.
let income = ending - beginning - contributions + distributions - other_alloc[i]; let too_large = "a member's income";
let income = sub_exact(
add_exact(
sub_exact(sub_exact(ending, beginning, too_large)?, contributions, too_large)?,
distributions,
too_large,
)?,
other_alloc[i],
too_large,
)?;
cols.push(MemberEquityColumn { cols.push(MemberEquityColumn {
name: m.name.clone(), name: m.name.clone(),
beginning: zero_clean(beginning), beginning: zero_clean(beginning),
@@ -1351,15 +1417,17 @@ pub fn members_equity(
ending: zero_clean(ending), ending: zero_clean(ending),
}); });
} }
let sum = |f: fn(&MemberEquityColumn) -> Decimal| cols.iter().map(f).sum::<Decimal>(); let sum = |f: fn(&MemberEquityColumn) -> Decimal| {
sum_exact_of(&cols, f, "the members' equity totals")
};
let total = MemberEquityColumn { let total = MemberEquityColumn {
name: "Total".to_string(), name: "Total".to_string(),
beginning: sum(|c| c.beginning), beginning: sum(|c| c.beginning)?,
contributions: sum(|c| c.contributions), contributions: sum(|c| c.contributions)?,
net_income: sum(|c| c.net_income), net_income: sum(|c| c.net_income)?,
distributions: sum(|c| c.distributions), distributions: sum(|c| c.distributions)?,
other: sum(|c| c.other), other: sum(|c| c.other)?,
ending: sum(|c| c.ending), ending: sum(|c| c.ending)?,
}; };
debug_assert_eq!(total.ending, end_bs.total_equity); debug_assert_eq!(total.ending, end_bs.total_equity);
Ok(MembersEquityStatement { Ok(MembersEquityStatement {
@@ -1720,7 +1788,11 @@ pub fn fixed_asset_register(
total_depreciable_basis: depreciable_total, total_depreciable_basis: depreciable_total,
total_tax_basis_723: total_723, total_tax_basis_723: total_723,
missing_basis: missing, missing_basis: missing,
ledger_cost: cost_accounts.iter().map(|&id| net(id)).sum(), ledger_cost: sum_exact_of(&cost_accounts, |&id| net(id), "the ledger's asset cost")?,
ledger_accumulated: -accum_accounts.iter().map(|&id| net(id)).sum::<Decimal>(), ledger_accumulated: -sum_exact_of(
&accum_accounts,
|&id| net(id),
"the ledger's accumulated depreciation",
)?,
}) })
} }
+21 -18
View File
@@ -79,6 +79,7 @@
//! ``` //! ```
use crate::k1::{K1Kind, K1Row, k1_detail}; use crate::k1::{K1Kind, K1Row, k1_detail};
use crate::money::sum_exact_of;
use crate::reports::MemberCapital; use crate::reports::MemberCapital;
use crate::{AccountId, AssetId, AssetStatus, EntryId, Ledger, LedgerError, Side}; use crate::{AccountId, AssetId, AssetStatus, EntryId, Ledger, LedgerError, Side};
use chrono::NaiveDate; use chrono::NaiveDate;
@@ -584,19 +585,19 @@ fn entry_wholes(
n: usize, n: usize,
cash: &[AccountId], cash: &[AccountId],
) -> Result<Vec<Whole>, LedgerError> { ) -> Result<Vec<Whole>, LedgerError> {
let by_member = |kind| -> Vec<Decimal> { let by_member = |kind| -> Result<Vec<Decimal>, LedgerError> {
(0..n) (0..n)
.map(|i| { .map(|i| {
lines sum_exact_of(
.iter() lines.iter().filter(|l| l.member == i && l.kind == kind),
.filter(|l| l.member == i && l.kind == kind) |l| l.amount,
.map(|l| l.amount) "a member's K-1 lines",
.sum() )
}) })
.collect() .collect()
}; };
let mut out = Vec::new(); let mut out = Vec::new();
let takes = by_member(K1Kind::PropertyContribution); let takes = by_member(K1Kind::PropertyContribution)?;
if takes.iter().any(|t| !t.is_zero()) { if takes.iter().any(|t| !t.is_zero()) {
let p = entry_property(ledger, e, cash)?; let p = entry_property(ledger, e, cash)?;
out.push((BUILT_IN_GAIN, p.built_in_gain, takes.clone())); out.push((BUILT_IN_GAIN, p.built_in_gain, takes.clone()));
@@ -604,7 +605,7 @@ fn entry_wholes(
out.push((PREPAID, p.prepaid, takes)); out.push((PREPAID, p.prepaid, takes));
} }
// Distributions are negative lines; weights are what each took. // Distributions are negative lines; weights are what each took.
let taken: Vec<Decimal> = by_member(K1Kind::Distribution) let taken: Vec<Decimal> = by_member(K1Kind::Distribution)?
.into_iter() .into_iter()
.map(|d| -d) .map(|d| -d)
.collect(); .collect();
@@ -755,7 +756,7 @@ fn entry_property(
}) })
.try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount)) .try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount))
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
let pool = pool - prepaid; let pool = pool.checked_sub(prepaid).ok_or_else(too_large)?;
let (mut linked, mut big, mut unknown) = (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO); let (mut linked, mut big, mut unknown) = (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO);
for a in ledger for a in ledger
.registered_assets() .registered_assets()
@@ -781,7 +782,7 @@ fn entry_property(
mismatch: Some((linked, pool)), mismatch: Some((linked, pool)),
}); });
} }
let rest = pool - linked; let rest = pool.checked_sub(linked).ok_or_else(too_large)?;
Ok(EntryProperty { Ok(EntryProperty {
built_in_gain: big, built_in_gain: big,
prepaid, prepaid,
@@ -816,21 +817,23 @@ fn span(
} }
for id in entries { for id in entries {
let e = ledger.get_entry(id).ok_or(LedgerError::UnknownEntry(id))?; let e = ledger.get_entry(id).ok_or(LedgerError::UnknownEntry(id))?;
let lines = |kind| -> Vec<Decimal> { let lines = |kind| -> Result<Vec<Decimal>, LedgerError> {
(0..n) (0..n)
.map(|i| { .map(|i| {
detail sum_exact_of(
.lines detail
.iter() .lines
.filter(|l| l.entry == id && l.member == i && l.kind == kind) .iter()
.map(|l| l.amount) .filter(|l| l.entry == id && l.member == i && l.kind == kind),
.sum() |l| l.amount,
"a member's K-1 lines",
)
}) })
.collect() .collect()
}; };
let none = EntryParts::default(); let none = EntryParts::default();
let part = parts.get(&id).unwrap_or(&none); let part = parts.get(&id).unwrap_or(&none);
let takes = lines(K1Kind::PropertyContribution); let takes = lines(K1Kind::PropertyContribution)?;
if takes.iter().any(|t| !t.is_zero()) { if takes.iter().any(|t| !t.is_zero()) {
let p = entry_property(ledger, e, cash)?; let p = entry_property(ledger, e, cash)?;
// Only the members with property in the entry have a part of // Only the members with property in the entry have a part of