fix(core): Decimal arithmetic in ledger-core goes through the kernel (K-U11a)
Bar item 1: money arithmetic lives in kernel/ and nowhere else. scripts/raw-decimal-arith.sh listed 210 places in ledger-core that did not: raw +, -, * and unary minus (which panic past Decimal's range), and checked_add / checked_sub / checked_mul / checked_div calls that resolved to rust_decimal's inherent methods (which round silently past 28 digits) and not to the kernel's Amount. 199 of them now call the kernel: Amount's methods by their full path, total / total_of for the hand-rolled sums, normal_balance, and money.rs's sign and in-range helpers. The rewrite was done by a script from the compiler's own line and column for each site, so no site was copied by hand; the few that needed a decision are explicit: - a balance sheet that cannot add liabilities and equity is not balanced (it panicked); - a template's shares, a party's percents, a reconciliation's book and cleared balances and a reversal's document movements refuse with TooLargeToCompute or their own message where they panicked; - tax_capital's split refuses where a product by the sign could not be taken, and collects its remainders as Options. No figure moves: every site computes what it computed, by the same operations in the same order. Left, each for a named reason (the detector prints these 11): money.rs 139 and 150 and periods.rs 149 and 202 (K-U10a rewrites them), audit.rs 355 and 511 (V-D3 is in them), ledger.rs 4048 (a share times the closed total: checked_mul_rounded, with K-U10a), and four rescale calls (money.rs 302, reports.rs 637, schedules.rs 370 and 377) that need a kernel function of their own. Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
e0c78a783b
commit
32725fb669
19 files changed
+401
-394
No files matched your search
@@ -6,6 +6,7 @@
|
||||
//! are built from the same posted entries and statements as everything
|
||||
//! else, so a number on a chart always ties to a number on a statement.
|
||||
|
||||
use crate::money::{add_in_range, on_side, sub_in_range};
|
||||
use crate::reports::profit_and_loss_for_period;
|
||||
use crate::{AccountId, AccountType, Ledger, LedgerError, Side};
|
||||
use chrono::{Datelike, Days, Months, NaiveDate};
|
||||
@@ -84,11 +85,11 @@ pub fn balance_series(
|
||||
let Some(account) = ledger.chart().get(line.account) else {
|
||||
continue;
|
||||
};
|
||||
let signed = if line.side == account.account_type.normal_side() {
|
||||
line.amount.amount
|
||||
} else {
|
||||
-line.amount.amount
|
||||
};
|
||||
let signed = on_side(
|
||||
account.account_type.normal_side(),
|
||||
line.side,
|
||||
line.amount.amount,
|
||||
);
|
||||
postings.push((entry.date(), signed));
|
||||
}
|
||||
}
|
||||
@@ -98,7 +99,7 @@ pub fn balance_series(
|
||||
let mut i = 0;
|
||||
for date in dates {
|
||||
while i < postings.len() && postings[i].0 <= *date {
|
||||
running += postings[i].1;
|
||||
running = add_in_range(running, postings[i].1);
|
||||
i += 1;
|
||||
}
|
||||
out.push(running);
|
||||
@@ -137,7 +138,7 @@ pub struct IntervalPnl {
|
||||
impl IntervalPnl {
|
||||
/// Revenue minus expenses.
|
||||
pub fn net(&self) -> Decimal {
|
||||
self.revenue - self.expenses
|
||||
sub_in_range(self.revenue, self.expenses)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,14 +204,14 @@ pub fn flows_by_interval(
|
||||
let mut net = Decimal::ZERO;
|
||||
for line in entry.lines().iter().filter(|l| set.contains(&l.account)) {
|
||||
match line.side {
|
||||
Side::Debit => net += line.amount.amount,
|
||||
Side::Credit => net -= line.amount.amount,
|
||||
Side::Debit => net = add_in_range(net, line.amount.amount),
|
||||
Side::Credit => net = sub_in_range(net, line.amount.amount),
|
||||
}
|
||||
}
|
||||
if net > Decimal::ZERO {
|
||||
slot.2 += net;
|
||||
slot.2 = add_in_range(slot.2, net);
|
||||
} else {
|
||||
slot.3 -= net;
|
||||
slot.3 = sub_in_range(slot.3, net);
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -145,11 +145,7 @@ impl DocRef {
|
||||
/// A line's amount as this document counts it: plus on
|
||||
/// [`Self::owed_side`], minus on the other.
|
||||
pub fn counted(self, side: crate::Side, amount: Decimal) -> Decimal {
|
||||
if side == self.owed_side() {
|
||||
amount
|
||||
} else {
|
||||
-amount
|
||||
}
|
||||
crate::money::on_side(self.owed_side(), side, amount)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1368,7 +1364,8 @@ impl AgingRow {
|
||||
/// Add `other`'s buckets to this row's; refused past exact arithmetic.
|
||||
pub(crate) fn add(&mut self, other: &AgingRow) -> Result<(), LedgerError> {
|
||||
let too_large = || LedgerError::TooLargeToCompute(format!("{}'s aging", self.name));
|
||||
let sum = |a: Decimal, b: Decimal| a.checked_add(b).ok_or_else(too_large);
|
||||
let sum =
|
||||
|a: Decimal, b: Decimal| crate::kernel::Amount::checked_add(a, b).ok_or_else(too_large);
|
||||
let (current, days_30, days_60, days_90, days_90_plus) = (
|
||||
sum(self.current, other.current)?,
|
||||
sum(self.days_30, other.days_30)?,
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
//! the §704(c) built-in gain or loss at contribution.
|
||||
|
||||
use crate::money::Steps;
|
||||
use crate::money::neg;
|
||||
use crate::{
|
||||
AccountId, AccountType, ChartOfAccounts, EntryId, EntryStatus, Ledger, LedgerError, Money,
|
||||
kernel,
|
||||
@@ -684,11 +685,9 @@ fn schedule_months(asset: &Asset, through: NaiveDate) -> Result<Vec<MonthLine>,
|
||||
}
|
||||
let too_large =
|
||||
|| LedgerError::TooLargeToCompute(format!("asset {}'s depreciation schedule", asset.id));
|
||||
let depreciable = asset
|
||||
.cost
|
||||
.amount
|
||||
.checked_sub(asset.salvage_value.amount)
|
||||
.ok_or_else(too_large)?;
|
||||
let depreciable =
|
||||
crate::kernel::Amount::checked_sub(asset.cost.amount, asset.salvage_value.amount)
|
||||
.ok_or_else(too_large)?;
|
||||
if depreciable <= Decimal::ZERO {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
@@ -721,10 +720,7 @@ fn schedule_months(asset: &Asset, through: NaiveDate) -> Result<Vec<MonthLine>,
|
||||
period: format!("{:04}-{:02}", p.year, p.month),
|
||||
amount: steps.decimal(through_k - charged).ok_or_else(too_large)?,
|
||||
accumulated,
|
||||
book_value: asset
|
||||
.cost
|
||||
.amount
|
||||
.checked_sub(accumulated)
|
||||
book_value: crate::kernel::Amount::checked_sub(asset.cost.amount, accumulated)
|
||||
.ok_or_else(too_large)?,
|
||||
},
|
||||
});
|
||||
@@ -760,11 +756,11 @@ pub fn accumulated_scheduled_through(
|
||||
/// [`crate::Ledger::accumulated_posted`] (the register's and the tools'
|
||||
/// `book_value`, BS-asset-3).
|
||||
pub fn scheduled_book_value(asset: &Asset, as_of: NaiveDate) -> Result<Decimal, LedgerError> {
|
||||
asset
|
||||
.cost
|
||||
.amount
|
||||
.checked_sub(accumulated_scheduled_through(asset, as_of)?)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s book value", asset.id)))
|
||||
crate::kernel::Amount::checked_sub(
|
||||
asset.cost.amount,
|
||||
accumulated_scheduled_through(asset, as_of)?,
|
||||
)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s book value", asset.id)))
|
||||
}
|
||||
|
||||
/// A change to what the books carry for an asset's depreciation, in the
|
||||
@@ -839,7 +835,7 @@ pub(crate) fn run_chain_entries(
|
||||
.get_entry(id)
|
||||
.filter(|x| x.status() == EntryStatus::Posted)
|
||||
{
|
||||
out.push((e.date(), if adds { amount } else { -amount }));
|
||||
out.push((e.date(), if adds { amount } else { neg(amount) }));
|
||||
}
|
||||
link = reversals.get(&id).copied();
|
||||
adds = !adds;
|
||||
@@ -929,8 +925,7 @@ pub fn run_amounts(
|
||||
RunAmount {
|
||||
amount,
|
||||
scheduled: own,
|
||||
over: g
|
||||
.checked_sub(s)
|
||||
over: crate::kernel::Amount::checked_sub(g, s)
|
||||
.map_or(Decimal::ZERO, |o| o.max(Decimal::ZERO)),
|
||||
},
|
||||
)
|
||||
@@ -981,7 +976,7 @@ fn cumulatives(
|
||||
li += 1;
|
||||
}
|
||||
while let Some(r) = runs.get(ri).filter(|r| (r.year, r.month) <= (y, m)) {
|
||||
carry = carry.checked_add(r.amount).ok_or_else(too_large)?;
|
||||
carry = crate::kernel::Amount::checked_add(carry, r.amount).ok_or_else(too_large)?;
|
||||
ri += 1;
|
||||
}
|
||||
months.push((y, m));
|
||||
@@ -1096,8 +1091,7 @@ pub fn catch_up_room(
|
||||
let too_large =
|
||||
|| LedgerError::TooLargeToCompute(format!("asset {}'s depreciation run", asset.id));
|
||||
let c = cumulatives(asset, (year, month), latest, &lines, posted)?;
|
||||
let over = c.carried[0]
|
||||
.checked_sub(c.scheduled[0])
|
||||
let over = crate::kernel::Amount::checked_sub(c.carried[0], c.scheduled[0])
|
||||
.ok_or_else(too_large)?
|
||||
.max(Decimal::ZERO);
|
||||
Ok(RunAmount {
|
||||
@@ -1154,15 +1148,13 @@ pub fn disposal_amounts(
|
||||
check_disposal(asset, proceeds)?;
|
||||
let accumulated = accumulated_scheduled_through(asset, date)?;
|
||||
let too_large = || LedgerError::TooLargeToCompute(format!("asset {}'s disposal", asset.id));
|
||||
let book = asset
|
||||
.cost
|
||||
.amount
|
||||
.checked_sub(accumulated)
|
||||
.ok_or_else(too_large)?;
|
||||
let book =
|
||||
crate::kernel::Amount::checked_sub(asset.cost.amount, accumulated).ok_or_else(too_large)?;
|
||||
Ok(DisposalAmounts {
|
||||
book_value: book,
|
||||
accumulated,
|
||||
gain_loss: proceeds.amount.checked_sub(book).ok_or_else(too_large)?,
|
||||
gain_loss: crate::kernel::Amount::checked_sub(proceeds.amount, book)
|
||||
.ok_or_else(too_large)?,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
//! falls, what a member or lender paid for the company, pairs reversals,
|
||||
//! names the kinds and checks the result foots.
|
||||
|
||||
use crate::money::{add_in_range, neg, signed_amount, sub_in_range};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
|
||||
use chrono::NaiveDate;
|
||||
@@ -405,7 +406,7 @@ impl CashFlowStatement {
|
||||
for l in self.lines(section) {
|
||||
match out.last_mut() {
|
||||
Some(k) if k.kind == l.kind => {
|
||||
k.amount += l.amount;
|
||||
k.amount = add_in_range(k.amount, l.amount);
|
||||
k.entries.push(l.entry);
|
||||
}
|
||||
_ => out.push(CashFlowKind {
|
||||
@@ -643,8 +644,7 @@ pub fn role_problems(
|
||||
/// cannot fail on posted entries): the sections sum to the change in
|
||||
/// cash, or nothing is produced.
|
||||
pub fn foot(sections_sum: Decimal, net_change: Decimal) -> Result<CashFlowFooting, LedgerError> {
|
||||
let difference = sections_sum
|
||||
.checked_sub(net_change)
|
||||
let difference = crate::kernel::Amount::checked_sub(sections_sum, net_change)
|
||||
.ok_or_else(|| too_large("the cash flow statement's footing"))?;
|
||||
if !difference.is_zero() {
|
||||
return Err(LedgerError::CashFlowDoesNotFoot {
|
||||
@@ -665,14 +665,11 @@ fn too_large(what: &str) -> LedgerError {
|
||||
}
|
||||
|
||||
fn add(a: Decimal, b: Decimal, what: &str) -> Result<Decimal, LedgerError> {
|
||||
a.checked_add(b).ok_or_else(|| too_large(what))
|
||||
crate::kernel::Amount::checked_add(a, b).ok_or_else(|| too_large(what))
|
||||
}
|
||||
|
||||
fn signed(side: Side, amount: Decimal) -> Decimal {
|
||||
match side {
|
||||
Side::Debit => amount,
|
||||
Side::Credit => -amount,
|
||||
}
|
||||
signed_amount(side, amount)
|
||||
}
|
||||
|
||||
/// What a line part belongs to within its section: the kind its cash is
|
||||
@@ -1075,7 +1072,7 @@ fn bill_splits(roles: &Roles<'_>, chains: &Chains) -> Result<BillSplits, LedgerE
|
||||
if l.side == Side::Credit && left > Decimal::ZERO && operating_liability(l.account)? {
|
||||
let part = left.min(l.amount.amount);
|
||||
out.parts.insert((b.id(), i), (part, bucket.clone()));
|
||||
left -= part;
|
||||
left = sub_in_range(left, part);
|
||||
}
|
||||
}
|
||||
// Each payment pays the equipment part first, in the order paid:
|
||||
@@ -1085,13 +1082,13 @@ fn bill_splits(roles: &Roles<'_>, chains: &Chains) -> Result<BillSplits, LedgerE
|
||||
// paid nothing for good: its reversal unpays it on the reversal's
|
||||
// date, and it leaves the equipment part for the payment that
|
||||
// stands (P4b.2 gap 6: it used to keep it, as the bill did).
|
||||
let mut owed = equipment - left;
|
||||
let mut owed = sub_in_range(equipment, left);
|
||||
let payments = ledger
|
||||
.doc_lines(crate::DocRef::Bill(bill.id))
|
||||
.into_iter()
|
||||
.filter(|l| l.movement == crate::Movement::Payment && !l.reversal);
|
||||
for pl in payments {
|
||||
let (pay, amount) = (pl.entry, -pl.amount);
|
||||
let (pay, amount) = (pl.entry, neg(pl.amount));
|
||||
let Some(p) = ledger.get_entry(pay) else {
|
||||
continue;
|
||||
};
|
||||
@@ -1107,20 +1104,20 @@ fn bill_splits(roles: &Roles<'_>, chains: &Chains) -> Result<BillSplits, LedgerE
|
||||
let paid = out.paid.entry(b.id()).or_default();
|
||||
paid.push((p.date(), part));
|
||||
// Its reversal unpays it; a reinstatement pays it again.
|
||||
let mut undo = -part;
|
||||
let mut undo = neg(part);
|
||||
let mut cur = p.id();
|
||||
while let Some(&r) = chains.reversed_by.get(&cur) {
|
||||
let Some(re) = ledger.get_entry(r).filter(|_| r > cur) else {
|
||||
break;
|
||||
};
|
||||
paid.push((re.date(), undo));
|
||||
undo = -undo;
|
||||
undo = neg(undo);
|
||||
cur = r;
|
||||
}
|
||||
if ledger.in_effect(p.id()) {
|
||||
owed -= part;
|
||||
owed = sub_in_range(owed, part);
|
||||
}
|
||||
this -= part;
|
||||
this = sub_in_range(this, part);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1301,7 +1298,7 @@ fn analyse<'a>(
|
||||
..part.clone()
|
||||
});
|
||||
}
|
||||
part.amount = amount - inv;
|
||||
part.amount = sub_in_range(amount, inv);
|
||||
if part.amount.is_zero() {
|
||||
continue;
|
||||
}
|
||||
@@ -1401,7 +1398,7 @@ fn analyse<'a>(
|
||||
if total > Decimal::ZERO {
|
||||
inflow = add(inflow, total, "an entry's exchange")?;
|
||||
} else {
|
||||
outflow = add(outflow, -total, "an entry's exchange")?;
|
||||
outflow = add(outflow, neg(total), "an entry's exchange")?;
|
||||
}
|
||||
}
|
||||
if !total.is_zero() {
|
||||
@@ -1427,7 +1424,7 @@ fn analyse<'a>(
|
||||
if m > Decimal::ZERO {
|
||||
debits = add(debits, m, "an entry's exchange")?;
|
||||
} else {
|
||||
credits = add(credits, -m, "an entry's exchange")?;
|
||||
credits = add(credits, neg(m), "an entry's exchange")?;
|
||||
}
|
||||
}
|
||||
let exchanged = kernel::exchanged(debits, credits, inflow, outflow)
|
||||
@@ -1490,9 +1487,9 @@ impl Chains {
|
||||
|
||||
fn negated(f: &EntryFlows<Decimal>) -> EntryFlows<Decimal> {
|
||||
EntryFlows {
|
||||
cash: -f.cash,
|
||||
flows: f.flows.map(|x| -x),
|
||||
noncash: f.noncash.map(|x| -x),
|
||||
cash: neg(f.cash),
|
||||
flows: f.flows.map(neg),
|
||||
noncash: f.noncash.map(neg),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1526,8 +1523,8 @@ fn pairs(kept: &[Analysed<'_>]) -> HashSet<EntryId> {
|
||||
r.kinds[k].len() == x.kinds[k].len()
|
||||
&& r.kinds[k].iter().zip(&x.kinds[k]).all(|(rk, xk)| {
|
||||
rk.bucket == xk.bucket
|
||||
&& rk.cash == -xk.cash
|
||||
&& rk.on_behalf == -xk.on_behalf
|
||||
&& rk.cash == neg(xk.cash)
|
||||
&& rk.on_behalf == neg(xk.on_behalf)
|
||||
})
|
||||
});
|
||||
if mirror {
|
||||
@@ -1968,7 +1965,7 @@ pub fn cash_flow(
|
||||
{
|
||||
for &(date, part) in paid {
|
||||
if date <= params.end {
|
||||
exchanged -= part;
|
||||
exchanged = sub_in_range(exchanged, part);
|
||||
}
|
||||
}
|
||||
exchanged = exchanged.max(Decimal::ZERO);
|
||||
@@ -2017,8 +2014,7 @@ pub fn cash_flow(
|
||||
}
|
||||
}
|
||||
}
|
||||
let net_change_in_cash = cash_ending
|
||||
.checked_sub(cash_beginning)
|
||||
let net_change_in_cash = crate::kernel::Amount::checked_sub(cash_ending, cash_beginning)
|
||||
.ok_or_else(|| too_large("the change in cash"))?;
|
||||
let sections_sum = add(
|
||||
add(totals[0], totals[1], "the sections' sum")?,
|
||||
@@ -2072,7 +2068,7 @@ fn reconcile(
|
||||
let (mut g, mut dep) = (Decimal::ZERO, Decimal::ZERO);
|
||||
for p in &a.parts {
|
||||
if p.pl {
|
||||
net_income = add(net_income, -p.signed(), WHAT)?;
|
||||
net_income = add(net_income, neg(p.signed()), WHAT)?;
|
||||
if p.flow == Flow::Investing {
|
||||
if roles.depreciation.contains(&p.account) {
|
||||
dep = add(dep, p.signed(), WHAT)?;
|
||||
@@ -2204,7 +2200,7 @@ fn reconcile(
|
||||
if up { "Increase in" } else { "Decrease in" },
|
||||
named(&code)
|
||||
),
|
||||
amount: -movement,
|
||||
amount: neg(movement),
|
||||
account: Some(code),
|
||||
entries: Vec::new(),
|
||||
});
|
||||
|
||||
@@ -779,10 +779,16 @@ fn check_template(t: &Template) -> Result<Template, String> {
|
||||
l.share
|
||||
)
|
||||
})?;
|
||||
match l.side {
|
||||
Side::Debit => debit += share,
|
||||
Side::Credit => credit += share,
|
||||
}
|
||||
let side_total = match l.side {
|
||||
Side::Debit => &mut debit,
|
||||
Side::Credit => &mut credit,
|
||||
};
|
||||
*side_total = crate::kernel::Amount::checked_add(*side_total, share).ok_or_else(|| {
|
||||
format!(
|
||||
"template line {n}: share {:?} has too many digits to add up exactly",
|
||||
l.share
|
||||
)
|
||||
})?;
|
||||
let account = line_text(&format!("template line {n} account"), &l.account, 64)?;
|
||||
if account.starts_with('{') && slot(&account).is_none() {
|
||||
return Err(format!(
|
||||
|
||||
@@ -200,12 +200,11 @@ impl Policy {
|
||||
/// total past exact arithmetic is refused (TooLargeToCompute), never
|
||||
/// a panic.
|
||||
pub fn entry_debits(entry: &JournalEntry) -> Result<Decimal, LedgerError> {
|
||||
entry
|
||||
.lines()
|
||||
.iter()
|
||||
.filter(|l| l.side == Side::Debit)
|
||||
.try_fold(Decimal::ZERO, |sum, l| sum.checked_add(l.amount.amount))
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("entry {}'s debits", entry.id())))
|
||||
crate::kernel::total_of(
|
||||
entry.lines().iter().filter(|l| l.side == Side::Debit),
|
||||
|l| l.amount.amount,
|
||||
)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("entry {}'s debits", entry.id())))
|
||||
}
|
||||
|
||||
fn account_codes(ledger: &Ledger, entry: &JournalEntry) -> Vec<String> {
|
||||
@@ -343,7 +342,7 @@ impl Policy {
|
||||
// A sum past exact arithmetic is past the threshold.
|
||||
total = Self::entry_debits(other)
|
||||
.ok()
|
||||
.and_then(|d| total.checked_add(d))
|
||||
.and_then(|d| crate::kernel::Amount::checked_add(total, d))
|
||||
.unwrap_or(Decimal::MAX);
|
||||
}
|
||||
if !group.is_empty() && total > self.threshold {
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
//! them and the report takes an override. Confirm with the CPA.
|
||||
|
||||
use crate::kernel::{self, Bucket, PayRole, Tag};
|
||||
use crate::money::neg;
|
||||
use crate::settings::Source;
|
||||
use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, VendorId};
|
||||
use chrono::{Datelike, NaiveDate};
|
||||
@@ -769,7 +770,7 @@ fn split_share(b: [Decimal; 3], v: Decimal) -> Result<[Decimal; 3], LedgerError>
|
||||
kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?;
|
||||
if v.is_sign_negative() {
|
||||
for x in parts.iter_mut().filter(|x| !x.is_zero()) {
|
||||
*x = -*x;
|
||||
*x = neg(*x);
|
||||
}
|
||||
}
|
||||
Ok(parts)
|
||||
@@ -831,8 +832,7 @@ struct Tally {
|
||||
}
|
||||
|
||||
fn add(to: &mut Decimal, x: Decimal) -> Result<(), LedgerError> {
|
||||
*to = to
|
||||
.checked_add(x)
|
||||
*to = crate::kernel::Amount::checked_add(*to, x)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute("a vendor's payments for the year".into()))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1236,8 +1236,7 @@ fn untagged_payments(
|
||||
continue;
|
||||
}
|
||||
let [counts, _, unknown] = entry_buckets(ledger, e, roles)?;
|
||||
let out_of_pocket = counts
|
||||
.checked_add(unknown)
|
||||
let out_of_pocket = crate::kernel::Amount::checked_add(counts, unknown)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute("a payment".into()))?;
|
||||
if out_of_pocket <= Decimal::ZERO {
|
||||
continue;
|
||||
|
||||
@@ -69,7 +69,7 @@
|
||||
//! ```
|
||||
|
||||
use crate::kernel::Amount;
|
||||
use crate::money::{add_exact, sub_exact, sum_exact_of, sum_exact_try};
|
||||
use crate::money::{add_exact, neg, sub_exact, sum_exact_of, sum_exact_try};
|
||||
use crate::reports::{MemberCapital, members_equity};
|
||||
use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, PartyId, Side};
|
||||
use chrono::NaiveDate;
|
||||
@@ -315,7 +315,7 @@ pub(crate) fn entry_lines(
|
||||
"a member's distributions",
|
||||
)?;
|
||||
if !taken.is_zero() {
|
||||
lines.push(line(i, K1Kind::Distribution, -taken));
|
||||
lines.push(line(i, K1Kind::Distribution, neg(taken)));
|
||||
}
|
||||
}
|
||||
Ok(lines)
|
||||
@@ -348,10 +348,7 @@ pub(crate) fn share_property(
|
||||
use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with};
|
||||
let too_large =
|
||||
|| LedgerError::TooLargeToCompute("a member's share of contributed property".into());
|
||||
let total = credits
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |t, c| t.checked_add(*c))
|
||||
.ok_or_else(too_large)?;
|
||||
let total = crate::kernel::total_of(credits.iter(), |c| *c).ok_or_else(too_large)?;
|
||||
let whole = pool.min(total);
|
||||
if whole <= Decimal::ZERO || total <= Decimal::ZERO {
|
||||
return Ok(vec![Decimal::ZERO; credits.len()]);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//! is no other way to change the books, which is what makes the ledger an
|
||||
//! audit trail and what will make the future oracle harness trustworthy.
|
||||
|
||||
use crate::money::{add_in_range, neg, on_side};
|
||||
use crate::schedules::{
|
||||
self, AmortizationSchedule, NewRecurring, NewSchedule, RecurringEntry, RecurringId, ScheduleId,
|
||||
};
|
||||
@@ -2368,9 +2369,11 @@ impl Ledger {
|
||||
for (i, l) in original.lines().iter().enumerate() {
|
||||
if let Some(tag) = self.line_docs.get(&(original.id(), i)) {
|
||||
// The mirror moves the document by the opposite.
|
||||
let by = -tag.doc.counted(l.side, l.amount.amount);
|
||||
let by = neg(tag.doc.counted(l.side, l.amount.amount));
|
||||
match moves.iter_mut().find(|(d, _)| *d == tag.doc) {
|
||||
Some((_, m)) => *m += by,
|
||||
Some((_, m)) => {
|
||||
*m = crate::money::add_exact(*m, by, "a document's movement in a reversal")?
|
||||
}
|
||||
None => moves.push((tag.doc, by)),
|
||||
}
|
||||
}
|
||||
@@ -3438,11 +3441,13 @@ impl Ledger {
|
||||
) -> Result<Decimal, LedgerError> {
|
||||
let too_large =
|
||||
|| LedgerError::TooLargeToCompute(format!("asset {id}'s posted depreciation"));
|
||||
assets::run_chain_entries(self, &self.depreciation_run_entries(id), reversals)
|
||||
.into_iter()
|
||||
.filter(|(d, _)| *d >= from && *d <= to)
|
||||
.try_fold(Decimal::ZERO, |t, (_, a)| t.checked_add(a))
|
||||
.ok_or_else(too_large)
|
||||
crate::kernel::total_of(
|
||||
assets::run_chain_entries(self, &self.depreciation_run_entries(id), reversals)
|
||||
.into_iter()
|
||||
.filter(|(d, _)| *d >= from && *d <= to),
|
||||
|(_, a)| a,
|
||||
)
|
||||
.ok_or_else(too_large)
|
||||
}
|
||||
|
||||
/// The run the books carry for an asset's month, if any: the first one
|
||||
@@ -3756,7 +3761,7 @@ impl Ledger {
|
||||
let mut sweep = |from: AccountId, into: AccountId, this: &Self| {
|
||||
// An equity balance (credit-normal) is −movement; zeroing it
|
||||
// moves exactly that much into the target.
|
||||
let balance = -this.movement_through(from, period.end);
|
||||
let balance = neg(this.movement_through(from, period.end));
|
||||
if !balance.is_zero() {
|
||||
sweep_lines.push((from, into, balance));
|
||||
}
|
||||
@@ -3829,7 +3834,7 @@ impl Ledger {
|
||||
// A sweep zeroes the source (opposite its balance) and moves
|
||||
// the balance into the target.
|
||||
for (from, into, balance) in sweep_lines {
|
||||
post(self, from, -balance)?;
|
||||
post(self, from, neg(balance))?;
|
||||
post(self, into, balance)?;
|
||||
}
|
||||
self.post_entry(entry)?;
|
||||
@@ -4004,10 +4009,10 @@ impl Ledger {
|
||||
regime.trued_up |= matches!(m.rule, periods::MemberRule::Cumulative { .. })
|
||||
&& p.closing_entry.is_some();
|
||||
regime.order.clone_from(&m.members);
|
||||
regime.closed += m.net;
|
||||
regime.closed = add_in_range(regime.closed, m.net);
|
||||
for ((capital, _), part) in m.members.iter().zip(&m.parts) {
|
||||
if let Some(i) = members.iter().position(|(c, _)| c == capital) {
|
||||
regime.given[i] += *part;
|
||||
regime.given[i] = add_in_range(regime.given[i], *part);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4078,7 +4083,7 @@ impl Ledger {
|
||||
let mut total = Decimal::ZERO;
|
||||
for p in closed {
|
||||
match &p.member_close {
|
||||
Some(r) if r.members == members => total += r.net,
|
||||
Some(r) if r.members == members => total = add_in_range(total, r.net),
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
@@ -6346,7 +6351,8 @@ impl Ledger {
|
||||
return Ok(None);
|
||||
}
|
||||
let too_large = || LedgerError::TooLargeToCompute(format!("{doc}'s figures"));
|
||||
let add = |a: Decimal, b: Decimal| a.checked_add(b).ok_or_else(too_large);
|
||||
let add =
|
||||
|a: Decimal, b: Decimal| crate::kernel::Amount::checked_add(a, b).ok_or_else(too_large);
|
||||
let (mut outstanding, mut paid, mut discounted, mut written_off) =
|
||||
(Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO);
|
||||
let lines = self.doc_lines(doc);
|
||||
@@ -6356,9 +6362,9 @@ impl Ledger {
|
||||
for l in lines.into_iter().filter(|l| l.date <= as_of) {
|
||||
outstanding = add(outstanding, l.amount)?;
|
||||
match l.movement {
|
||||
arap::Movement::Payment => paid = add(paid, -l.amount)?,
|
||||
arap::Movement::Discount => discounted = add(discounted, -l.amount)?,
|
||||
arap::Movement::WriteOff => written_off = add(written_off, -l.amount)?,
|
||||
arap::Movement::Payment => paid = add(paid, neg(l.amount))?,
|
||||
arap::Movement::Discount => discounted = add(discounted, neg(l.amount))?,
|
||||
arap::Movement::WriteOff => written_off = add(written_off, neg(l.amount))?,
|
||||
arap::Movement::Origin | arap::Movement::Adopted | arap::Movement::RoleMove => {}
|
||||
}
|
||||
}
|
||||
@@ -6410,12 +6416,14 @@ impl Ledger {
|
||||
/// payment needs that feature. Refused (TooLargeToCompute), never a
|
||||
/// panic, past exact arithmetic: replayed amounts are any size (BS-entry-4).
|
||||
pub fn payments_recorded(&self, doc: arap::DocRef) -> Result<Decimal, LedgerError> {
|
||||
self.payment_events
|
||||
.get(&doc)
|
||||
.map_or(&[][..], Vec::as_slice)
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |sum, &a| sum.checked_add(a))
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{doc}'s payments")))
|
||||
crate::kernel::total_of(
|
||||
self.payment_events
|
||||
.get(&doc)
|
||||
.map_or(&[][..], Vec::as_slice)
|
||||
.iter(),
|
||||
|&a| a,
|
||||
)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{doc}'s payments")))
|
||||
}
|
||||
|
||||
/// The payment entries that stand against a document now: each
|
||||
@@ -6456,7 +6464,7 @@ impl Ledger {
|
||||
.chain(extra.iter().copied());
|
||||
for (date, amount) in moves {
|
||||
let day = by_date.entry(date).or_default();
|
||||
*day = day.checked_add(amount).ok_or_else(too_large)?;
|
||||
*day = crate::kernel::Amount::checked_add(*day, amount).ok_or_else(too_large)?;
|
||||
}
|
||||
Ok(by_date.into_values().collect())
|
||||
}
|
||||
@@ -6533,11 +6541,13 @@ impl Ledger {
|
||||
let too_large = || LedgerError::TooLargeToCompute(format!("{doc}'s figures"));
|
||||
let mut running = Decimal::ZERO;
|
||||
for l in lines.iter().filter(|l| l.date <= from) {
|
||||
running = running.checked_add(l.amount).ok_or_else(too_large)?;
|
||||
running =
|
||||
crate::kernel::Amount::checked_add(running, l.amount).ok_or_else(too_large)?;
|
||||
}
|
||||
let mut room = running;
|
||||
for l in lines.iter().filter(|l| l.date > from) {
|
||||
running = running.checked_add(l.amount).ok_or_else(too_large)?;
|
||||
running =
|
||||
crate::kernel::Amount::checked_add(running, l.amount).ok_or_else(too_large)?;
|
||||
room = room.min(running);
|
||||
}
|
||||
Ok(room)
|
||||
@@ -6729,9 +6739,10 @@ impl Ledger {
|
||||
});
|
||||
}
|
||||
let room = self.payment_room(app.doc, params.date)?;
|
||||
let applied = app.cash.checked_add(app.discount).ok_or_else(|| {
|
||||
LedgerError::TooLargeToCompute(format!("{}'s settlement", app.doc))
|
||||
})?;
|
||||
let applied =
|
||||
crate::kernel::Amount::checked_add(app.cash, app.discount).ok_or_else(|| {
|
||||
LedgerError::TooLargeToCompute(format!("{}'s settlement", app.doc))
|
||||
})?;
|
||||
if applied > room {
|
||||
return Err(LedgerError::Overpayment(applied, room));
|
||||
}
|
||||
@@ -6753,9 +6764,7 @@ impl Ledger {
|
||||
// A fee above the cash is its own refusal; the kernel would also
|
||||
// answer `None` for it, with no way to say which of its refusals it
|
||||
// was. A sum that overflows is left to the kernel (too large).
|
||||
if let Some(total_cash) = cash
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |sum, c| sum.checked_add(*c))
|
||||
if let Some(total_cash) = crate::kernel::total_of(cash.iter(), |c| *c)
|
||||
&& fee_amount > total_cash
|
||||
{
|
||||
return Err(LedgerError::FeeAboveCash {
|
||||
@@ -6779,9 +6788,9 @@ impl Ledger {
|
||||
let mut total_discount = Decimal::ZERO;
|
||||
for app in ¶ms.applications {
|
||||
if app.discount > Decimal::ZERO {
|
||||
total_discount = total_discount
|
||||
.checked_add(app.discount)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute("the discounts".into()))?;
|
||||
total_discount =
|
||||
crate::kernel::Amount::checked_add(total_discount, app.discount)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute("the discounts".into()))?;
|
||||
}
|
||||
}
|
||||
let discount_account = if any_discount {
|
||||
@@ -7411,7 +7420,7 @@ impl Ledger {
|
||||
};
|
||||
for l in self.doc_lines(doc).into_iter().filter(|l| l.date <= as_of) {
|
||||
let t = doc_totals.entry(l.account).or_default();
|
||||
*t = t.checked_add(l.amount).ok_or_else(too_large)?;
|
||||
*t = crate::kernel::Amount::checked_add(*t, l.amount).ok_or_else(too_large)?;
|
||||
}
|
||||
if let Some(st) = self.doc_state(doc, as_of)?
|
||||
&& (st.out_of_bounds() || st.status == arap::DocStatus::Unattached)
|
||||
@@ -7443,7 +7452,7 @@ impl Ledger {
|
||||
} else {
|
||||
Side::Credit
|
||||
};
|
||||
if side == plus { amount } else { -amount }
|
||||
on_side(plus, side, amount)
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (account, role) in accounts {
|
||||
@@ -7454,9 +7463,11 @@ impl Ledger {
|
||||
if l.account != account {
|
||||
continue;
|
||||
}
|
||||
balance = balance
|
||||
.checked_add(counted(role, l.side, l.amount.amount))
|
||||
.ok_or_else(too_large)?;
|
||||
balance = crate::kernel::Amount::checked_add(
|
||||
balance,
|
||||
counted(role, l.side, l.amount.amount),
|
||||
)
|
||||
.ok_or_else(too_large)?;
|
||||
if !self.line_docs.contains_key(&(e.id(), i)) {
|
||||
let top = self.reversal_chain(e.id())[0];
|
||||
if !tops.contains(&(top, i)) {
|
||||
@@ -7479,12 +7490,15 @@ impl Ledger {
|
||||
continue;
|
||||
};
|
||||
debug_assert!(n == 0 || e.reversal_of().is_some());
|
||||
net = net
|
||||
.checked_add(counted(role, l.side, l.amount.amount))
|
||||
.ok_or_else(too_large)?;
|
||||
net = crate::kernel::Amount::checked_add(
|
||||
net,
|
||||
counted(role, l.side, l.amount.amount),
|
||||
)
|
||||
.ok_or_else(too_large)?;
|
||||
}
|
||||
if !net.is_zero() {
|
||||
unattached_sum = unattached_sum.checked_add(net).ok_or_else(too_large)?;
|
||||
unattached_sum = crate::kernel::Amount::checked_add(unattached_sum, net)
|
||||
.ok_or_else(too_large)?;
|
||||
unattached.push(arap::UnattachedLine {
|
||||
entry: top,
|
||||
line: i,
|
||||
@@ -7521,10 +7535,8 @@ impl Ledger {
|
||||
let Ok(Some(st)) = self.doc_state(doc, NaiveDate::MAX) else {
|
||||
return;
|
||||
};
|
||||
let Some(settled) = st
|
||||
.paid
|
||||
.checked_add(st.discounted)
|
||||
.and_then(|s| s.checked_add(st.written_off))
|
||||
let Some(settled) = crate::kernel::Amount::checked_add(st.paid, st.discounted)
|
||||
.and_then(|s| crate::kernel::Amount::checked_add(s, st.written_off))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@@ -8189,18 +8201,14 @@ impl Ledger {
|
||||
continue;
|
||||
}
|
||||
// Signed in the account's normal side: positive = normal balance.
|
||||
let signed = match (line.side, normal) {
|
||||
(Side::Debit, Side::Debit) => line.amount.amount,
|
||||
(Side::Credit, Side::Credit) => line.amount.amount,
|
||||
(Side::Debit, Side::Credit) => -line.amount.amount,
|
||||
(Side::Credit, Side::Debit) => -line.amount.amount,
|
||||
};
|
||||
book += signed;
|
||||
let signed = on_side(normal, line.side, line.amount.amount);
|
||||
book = crate::money::add_exact(book, signed, "the account's book balance")?;
|
||||
if entry.date() > statement_date {
|
||||
continue;
|
||||
}
|
||||
if self.is_cleared(entry.id(), idx) {
|
||||
cleared += signed;
|
||||
cleared =
|
||||
crate::money::add_exact(cleared, signed, "the account's cleared balance")?;
|
||||
} else {
|
||||
uncleared_lines.push(UnclearedLine {
|
||||
entry_id: entry.id(),
|
||||
@@ -8224,9 +8232,9 @@ impl Ledger {
|
||||
cleared
|
||||
},
|
||||
statement_balance,
|
||||
difference: cleared.checked_sub(statement_balance).ok_or_else(|| {
|
||||
LedgerError::TooLargeToCompute("the reconciliation's difference".into())
|
||||
})?,
|
||||
difference: crate::kernel::Amount::checked_sub(cleared, statement_balance).ok_or_else(
|
||||
|| LedgerError::TooLargeToCompute("the reconciliation's difference".into()),
|
||||
)?,
|
||||
uncleared_lines,
|
||||
})
|
||||
}
|
||||
@@ -8441,7 +8449,7 @@ impl Ledger {
|
||||
match l.employee {
|
||||
Some(p) => match paid.iter_mut().find(|(x, _)| *x == p) {
|
||||
Some((_, v)) => {
|
||||
*v = v.checked_add(net).ok_or_else(|| {
|
||||
*v = crate::kernel::Amount::checked_add(*v, net).ok_or_else(|| {
|
||||
LedgerError::TooLargeToCompute(format!("party {p}'s net pay"))
|
||||
})?
|
||||
}
|
||||
@@ -9208,11 +9216,10 @@ impl Ledger {
|
||||
.iter()
|
||||
.filter_map(|l| self.chart.get(l.account).map(|a| a.code.as_str()))
|
||||
.collect();
|
||||
let debits = e
|
||||
.lines()
|
||||
.iter()
|
||||
.filter(|l| l.side == Side::Debit)
|
||||
.try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount))
|
||||
let debits =
|
||||
crate::kernel::total_of(e.lines().iter().filter(|l| l.side == Side::Debit), |l| {
|
||||
l.amount.amount
|
||||
})
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("entry {entry}'s debits")))?;
|
||||
let approvals = self.conventions.approvals(entry);
|
||||
let key = crate::parties::name_key;
|
||||
|
||||
@@ -917,11 +917,9 @@ impl Activity {
|
||||
match basis {
|
||||
Basis::Cash => (self.paid, self.received),
|
||||
Basis::All => (
|
||||
self.paid
|
||||
.checked_add(self.paid_in_kind)
|
||||
crate::kernel::Amount::checked_add(self.paid, self.paid_in_kind)
|
||||
.expect("activity_with keeps the all-basis sums exact"),
|
||||
self.received
|
||||
.checked_add(self.received_in_kind)
|
||||
crate::kernel::Amount::checked_add(self.received, self.received_in_kind)
|
||||
.expect("activity_with keeps the all-basis sums exact"),
|
||||
),
|
||||
}
|
||||
@@ -1152,8 +1150,10 @@ pub fn entry_flow(
|
||||
// sum is checked, and one past exact arithmetic is refused.
|
||||
let too_large =
|
||||
|| crate::LedgerError::TooLargeToCompute(format!("entry {}'s money flow", entry.id()));
|
||||
let plus = |a: Decimal, b: Decimal| a.checked_add(b).ok_or_else(too_large);
|
||||
let minus = |a: Decimal, b: Decimal| a.checked_sub(b).ok_or_else(too_large);
|
||||
let plus =
|
||||
|a: Decimal, b: Decimal| crate::kernel::Amount::checked_add(a, b).ok_or_else(too_large);
|
||||
let minus =
|
||||
|a: Decimal, b: Decimal| crate::kernel::Amount::checked_sub(a, b).ok_or_else(too_large);
|
||||
let (mut cash_cr, mut cash_dr, mut liab_cr, mut liab_dr) =
|
||||
(Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO);
|
||||
for l in entry.lines() {
|
||||
@@ -1199,13 +1199,13 @@ pub fn entry_flow(
|
||||
let (part, rest) = match l.side {
|
||||
Side::Debit => {
|
||||
let take = a.min(down_left);
|
||||
down_left -= take;
|
||||
(take, a - take)
|
||||
down_left = minus(down_left, take)?;
|
||||
(take, minus(a, take)?)
|
||||
}
|
||||
Side::Credit => {
|
||||
let take = a.min(up_left);
|
||||
up_left -= take;
|
||||
(-take, -(a - take))
|
||||
up_left = minus(up_left, take)?;
|
||||
(crate::money::neg(take), crate::money::neg(minus(a, take)?))
|
||||
}
|
||||
};
|
||||
match left.iter_mut().find(|(x, _)| *x == l.account) {
|
||||
@@ -1214,10 +1214,7 @@ pub fn entry_flow(
|
||||
}
|
||||
part
|
||||
} else {
|
||||
match l.side {
|
||||
Side::Debit => a,
|
||||
Side::Credit => -a,
|
||||
}
|
||||
crate::money::signed_amount(l.side, a)
|
||||
};
|
||||
add(&mut by, &mut order, l.account, part)?;
|
||||
}
|
||||
@@ -1226,17 +1223,18 @@ pub fn entry_flow(
|
||||
.map(|(_, v)| *v)
|
||||
.filter(|v| *v > Decimal::ZERO)
|
||||
.try_fold(Decimal::ZERO, &plus)?;
|
||||
let owed_up = -left
|
||||
.iter()
|
||||
.map(|(_, v)| *v)
|
||||
.filter(|v| *v < Decimal::ZERO)
|
||||
.try_fold(Decimal::ZERO, &plus)?;
|
||||
let owed_up = crate::money::neg(
|
||||
left.iter()
|
||||
.map(|(_, v)| *v)
|
||||
.filter(|v| *v < Decimal::ZERO)
|
||||
.try_fold(Decimal::ZERO, &plus)?,
|
||||
);
|
||||
let across = owed_down.min(owed_up);
|
||||
let mut across_left = across;
|
||||
for (account, v) in left {
|
||||
if v > Decimal::ZERO && !across_left.is_zero() {
|
||||
let take = v.min(across_left);
|
||||
across_left -= take;
|
||||
across_left = minus(across_left, take)?;
|
||||
add(&mut by, &mut order, account, take)?;
|
||||
}
|
||||
}
|
||||
@@ -1298,7 +1296,7 @@ pub fn flow(
|
||||
if v.is_zero() {
|
||||
rust_decimal::Decimal::ZERO
|
||||
} else {
|
||||
-v
|
||||
crate::money::neg(v)
|
||||
}
|
||||
};
|
||||
Ok(EntryFlow {
|
||||
@@ -1395,19 +1393,22 @@ pub fn activity_with(
|
||||
// the root original's side; every total, the all-basis sums
|
||||
// included, stays exact or the entry counts nothing.
|
||||
let next = match t.counts_as {
|
||||
Direction::Paid => a
|
||||
.paid
|
||||
.checked_add(p.cash)
|
||||
.zip(a.paid_in_kind.checked_add(p.in_kind))
|
||||
Direction::Paid => crate::kernel::Amount::checked_add(a.paid, p.cash)
|
||||
.zip(crate::kernel::Amount::checked_add(
|
||||
a.paid_in_kind,
|
||||
p.in_kind,
|
||||
))
|
||||
.map(|(c, k)| (c, k, a.received, a.received_in_kind)),
|
||||
_ => a
|
||||
.received
|
||||
.checked_sub(p.cash)
|
||||
.zip(a.received_in_kind.checked_sub(p.in_kind))
|
||||
_ => crate::kernel::Amount::checked_sub(a.received, p.cash)
|
||||
.zip(crate::kernel::Amount::checked_sub(
|
||||
a.received_in_kind,
|
||||
p.in_kind,
|
||||
))
|
||||
.map(|(c, k)| (a.paid, a.paid_in_kind, c, k)),
|
||||
};
|
||||
match next.filter(|(pc, pk, rc, rk)| {
|
||||
pc.checked_add(*pk).is_some() && rc.checked_add(*rk).is_some()
|
||||
crate::kernel::Amount::checked_add(*pc, *pk).is_some()
|
||||
&& crate::kernel::Amount::checked_add(*rc, *rk).is_some()
|
||||
}) {
|
||||
Some((pc, pk, rc, rk)) => {
|
||||
a.paid = pc;
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! no platform: callers (or a format-specific parser) supply the numbers
|
||||
//! from the payout statement, which is the entry's receipt.
|
||||
|
||||
use crate::money::{add_exact, sub_exact, sum_exact_of};
|
||||
use crate::money::{add_exact, neg, on_side, sub_exact, sum_exact_of};
|
||||
use crate::{AccountId, AccountType, ChartOfAccounts, ClassId, LedgerError, Side};
|
||||
use rust_decimal::Decimal;
|
||||
|
||||
@@ -170,10 +170,7 @@ pub fn payout_plan(
|
||||
let fees = sum_exact_of(&payout.fees, |l| l.amount, "the payout's fees")?;
|
||||
let adjustments = sum_exact_of(
|
||||
&payout.adjustments,
|
||||
|a| match a.side {
|
||||
Side::Credit => a.amount,
|
||||
Side::Debit => -a.amount,
|
||||
},
|
||||
|a| on_side(Side::Credit, a.side, a.amount),
|
||||
"the payout's adjustments",
|
||||
)?;
|
||||
let expected = add_exact(
|
||||
@@ -193,7 +190,12 @@ pub fn payout_plan(
|
||||
if payout.deposit > Decimal::ZERO {
|
||||
plan.push((payout.deposit_account, Side::Debit, payout.deposit, None));
|
||||
} else if payout.deposit < Decimal::ZERO {
|
||||
plan.push((payout.deposit_account, Side::Credit, -payout.deposit, None));
|
||||
plan.push((
|
||||
payout.deposit_account,
|
||||
Side::Credit,
|
||||
neg(payout.deposit),
|
||||
None,
|
||||
));
|
||||
}
|
||||
plan.extend(
|
||||
payout
|
||||
|
||||
@@ -177,17 +177,19 @@ pub fn payroll_entry_plan(
|
||||
// exact, or refused here as TooLargeToCompute, never a panic.
|
||||
let gross = crate::kernel::total_of(lines.iter(), |l| l.gross_pay).ok_or_else(too_large)?;
|
||||
let employer = crate::kernel::total_try(lines.iter(), |l| {
|
||||
l.ss_employer.checked_add(l.medicare_employer)
|
||||
crate::kernel::Amount::checked_add(l.ss_employer, l.medicare_employer)
|
||||
})
|
||||
.ok_or_else(too_large)?;
|
||||
let federal =
|
||||
crate::kernel::total_of(lines.iter(), |l| l.federal_withholding).ok_or_else(too_large)?;
|
||||
let state =
|
||||
crate::kernel::total_of(lines.iter(), |l| l.state_withholding).ok_or_else(too_large)?;
|
||||
let ss = crate::kernel::total_try(lines.iter(), |l| l.ss_employee.checked_add(l.ss_employer))
|
||||
.ok_or_else(too_large)?;
|
||||
let ss = crate::kernel::total_try(lines.iter(), |l| {
|
||||
crate::kernel::Amount::checked_add(l.ss_employee, l.ss_employer)
|
||||
})
|
||||
.ok_or_else(too_large)?;
|
||||
let medicare = crate::kernel::total_try(lines.iter(), |l| {
|
||||
l.medicare_employee.checked_add(l.medicare_employer)
|
||||
crate::kernel::Amount::checked_add(l.medicare_employee, l.medicare_employer)
|
||||
})
|
||||
.ok_or_else(too_large)?;
|
||||
let other =
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
//! through the *next* open period (or a reversal dated in an open period).
|
||||
|
||||
use crate::LedgerError;
|
||||
use crate::money::neg;
|
||||
use chrono::NaiveDate;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -157,13 +158,13 @@ pub fn try_allocate(
|
||||
let remainders: Vec<Decimal> = exact
|
||||
.iter()
|
||||
.zip(&parts)
|
||||
.map(|(e, p)| e.checked_sub(*p).ok_or_else(too_large))
|
||||
.map(|(e, p)| crate::kernel::Amount::checked_sub(*e, *p).ok_or_else(too_large))
|
||||
.collect::<Result<_, _>>()?;
|
||||
crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2))
|
||||
.ok_or_else(too_large)?;
|
||||
if amount.is_sign_negative() {
|
||||
for p in &mut parts {
|
||||
*p = -*p;
|
||||
*p = neg(*p);
|
||||
}
|
||||
}
|
||||
Ok(parts)
|
||||
@@ -270,7 +271,10 @@ pub fn allocate_cumulative(
|
||||
}
|
||||
let loss = total < Decimal::ZERO;
|
||||
let magnitude = total.abs().normalize();
|
||||
let given: Vec<Decimal> = given.iter().map(|&g| if loss { -g } else { g }).collect();
|
||||
let given: Vec<Decimal> = given
|
||||
.iter()
|
||||
.map(|&g| if loss { neg(g) } else { g })
|
||||
.collect();
|
||||
let mut parts = Vec::with_capacity(shares.len());
|
||||
let mut remainders = Vec::with_capacity(shares.len());
|
||||
for share in shares {
|
||||
@@ -278,8 +282,7 @@ pub fn allocate_cumulative(
|
||||
// Exact exactly when Decimal kept every digit: a product it had to
|
||||
// round comes back with fewer places than its factors carry (a
|
||||
// zero product, which it returns without places, is exact).
|
||||
let exact = magnitude
|
||||
.checked_mul(share)
|
||||
let exact = crate::kernel::Amount::checked_mul(magnitude, share)
|
||||
.filter(|e| e.is_zero() || e.scale() == magnitude.scale() + share.scale())
|
||||
.ok_or_else(|| {
|
||||
LedgerError::TooLargeToCompute(format!(
|
||||
@@ -290,7 +293,11 @@ pub fn allocate_cumulative(
|
||||
LedgerError::TooLargeToCompute(format!("a member's share {share} of {magnitude}"))
|
||||
})?;
|
||||
parts.push(floor);
|
||||
remainders.push(exact - floor);
|
||||
remainders.push(crate::money::sub_exact(
|
||||
exact,
|
||||
floor,
|
||||
"a member's share of the period's income",
|
||||
)?);
|
||||
}
|
||||
crate::kernel::apportion_cumulative(
|
||||
magnitude,
|
||||
@@ -302,7 +309,7 @@ pub fn allocate_cumulative(
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("the members' shares of {total}")))?;
|
||||
if loss {
|
||||
for p in parts.iter_mut().filter(|p| !p.is_zero()) {
|
||||
*p = -*p;
|
||||
*p = neg(*p);
|
||||
}
|
||||
}
|
||||
Ok(parts)
|
||||
|
||||
@@ -4,7 +4,10 @@
|
||||
//! (`docs/oracle.md`) diffs: the same fixture books through two engines must
|
||||
//! produce byte-identical [`snapshot`] output.
|
||||
|
||||
use crate::money::{add_exact, sub_exact, sum_exact, sum_exact_of, sum_exact_try};
|
||||
use crate::money::{
|
||||
add_exact, add_in_range, neg, on_side, signed_amount, sub_exact, sub_in_range, sum_exact,
|
||||
sum_exact_of, sum_exact_try,
|
||||
};
|
||||
use crate::{AccountType, Class, ClassId, JournalEntry, JournalLine, Ledger, LedgerError};
|
||||
use chrono::NaiveDate;
|
||||
use rust_decimal::Decimal;
|
||||
@@ -92,7 +95,8 @@ fn trial_balance_where(ledger: &Ledger, include: &dyn Fn(&JournalEntry) -> bool)
|
||||
for line in entry.lines() {
|
||||
let signed = crate::kernel::signed(line.side, line.amount.amount)
|
||||
.expect("Decimal negation is exact");
|
||||
*movements.entry(line.account).or_default() += signed;
|
||||
let slot = movements.entry(line.account).or_default();
|
||||
*slot = add_in_range(*slot, signed);
|
||||
}
|
||||
}
|
||||
let mut accounts: Vec<_> = ledger.chart().all().collect();
|
||||
@@ -110,8 +114,8 @@ fn trial_balance_where(ledger: &Ledger, include: &dyn Fn(&JournalEntry) -> bool)
|
||||
continue;
|
||||
}
|
||||
let (debit, credit) = crate::kernel::columns(movement).expect("Decimal negation is exact");
|
||||
total_debits += debit;
|
||||
total_credits += credit;
|
||||
total_debits = add_in_range(total_debits, debit);
|
||||
total_credits = add_in_range(total_credits, credit);
|
||||
lines.push(TrialBalanceLine {
|
||||
code: account.code.clone(),
|
||||
name: account.name.clone(),
|
||||
@@ -140,7 +144,7 @@ pub struct ProfitAndLoss {
|
||||
impl ProfitAndLoss {
|
||||
/// Revenue minus expenses. Positive is profit.
|
||||
pub fn net_income(&self) -> Decimal {
|
||||
self.revenue - self.expenses
|
||||
sub_in_range(self.revenue, self.expenses)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,11 +266,11 @@ fn profit_and_loss_where(
|
||||
if account.placeholder {
|
||||
continue;
|
||||
}
|
||||
let signed = if line.side == account.account_type.normal_side() {
|
||||
line.amount.amount
|
||||
} else {
|
||||
-line.amount.amount
|
||||
};
|
||||
let signed = on_side(
|
||||
account.account_type.normal_side(),
|
||||
line.side,
|
||||
line.amount.amount,
|
||||
);
|
||||
match account.account_type {
|
||||
AccountType::Revenue => revenue = add_exact(revenue, signed, "total revenue")?,
|
||||
AccountType::Expense => expenses = add_exact(expenses, signed, "total expenses")?,
|
||||
@@ -297,7 +301,7 @@ pub struct BalanceSheet {
|
||||
impl BalanceSheet {
|
||||
/// The accounting equation: assets == liabilities + equity, exactly.
|
||||
pub fn balanced(&self) -> bool {
|
||||
self.assets == self.liabilities + self.equity
|
||||
crate::kernel::Amount::checked_add(self.liabilities, self.equity) == Some(self.assets)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,7 +366,7 @@ pub struct ProfitAndLossStatement {
|
||||
impl ProfitAndLossStatement {
|
||||
/// Revenue minus expenses. Positive is profit.
|
||||
pub fn net_income(&self) -> Decimal {
|
||||
self.total_revenue - self.total_expenses
|
||||
sub_in_range(self.total_revenue, self.total_expenses)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -391,7 +395,8 @@ pub struct BalanceSheetStatement {
|
||||
impl BalanceSheetStatement {
|
||||
/// The accounting equation: assets == liabilities + equity, exactly.
|
||||
pub fn balanced(&self) -> bool {
|
||||
self.total_assets == self.total_liabilities + self.total_equity
|
||||
crate::kernel::Amount::checked_add(self.total_liabilities, self.total_equity)
|
||||
== Some(self.total_assets)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,10 +413,7 @@ fn statement_lines(
|
||||
if !include(entry, line) {
|
||||
continue;
|
||||
}
|
||||
let signed = match line.side {
|
||||
crate::Side::Debit => line.amount.amount,
|
||||
crate::Side::Credit => -line.amount.amount,
|
||||
};
|
||||
let signed = signed_amount(line.side, line.amount.amount);
|
||||
let slot = movement.entry(line.account).or_default();
|
||||
*slot = add_exact(*slot, signed, "an account's movement")?;
|
||||
}
|
||||
@@ -425,10 +427,8 @@ fn statement_lines(
|
||||
if account.placeholder || m.is_zero() {
|
||||
continue;
|
||||
}
|
||||
let amount = match account.account_type.normal_side() {
|
||||
crate::Side::Debit => m,
|
||||
crate::Side::Credit => -m,
|
||||
};
|
||||
let amount = crate::kernel::normal_balance(account.account_type, m)
|
||||
.expect("Decimal negation is exact");
|
||||
out.insert(
|
||||
account.code.clone(),
|
||||
(
|
||||
@@ -594,7 +594,7 @@ impl ProjectToDate {
|
||||
/// Revenue less expenses: the project's contribution before overhead
|
||||
/// (WB-statement-7), since only its own tagged lines count.
|
||||
pub fn net(&self) -> Decimal {
|
||||
self.revenue - self.expenses
|
||||
sub_in_range(self.revenue, self.expenses)
|
||||
}
|
||||
|
||||
/// Its contribution margin to date: [`contribution_margin_pct`] of
|
||||
@@ -690,12 +690,13 @@ pub fn project_figures(
|
||||
// before them).
|
||||
let mut running = months
|
||||
.iter()
|
||||
.try_fold(to_date.net(), |t, m| t.checked_sub(m.net()))
|
||||
.try_fold(to_date.net(), |t, m| {
|
||||
crate::kernel::Amount::checked_sub(t, m.net())
|
||||
})
|
||||
.ok_or(LedgerError::AmountOutOfRange)?;
|
||||
let mut months_net_to_date = Vec::with_capacity(months.len());
|
||||
for m in &months {
|
||||
running = running
|
||||
.checked_add(m.net())
|
||||
running = crate::kernel::Amount::checked_add(running, m.net())
|
||||
.ok_or(LedgerError::AmountOutOfRange)?;
|
||||
months_net_to_date.push(running);
|
||||
}
|
||||
@@ -758,21 +759,18 @@ pub fn project_entries(ledger: &Ledger, id: ClassId) -> Vec<(crate::EntryId, Dec
|
||||
let Some(account) = ledger.chart().get(line.account) else {
|
||||
continue;
|
||||
};
|
||||
let debit = matches!(line.side, crate::Side::Debit);
|
||||
match account.account_type {
|
||||
AccountType::Revenue => {
|
||||
amount += if debit {
|
||||
-line.amount.amount
|
||||
} else {
|
||||
line.amount.amount
|
||||
}
|
||||
amount = add_in_range(
|
||||
amount,
|
||||
on_side(crate::Side::Credit, line.side, line.amount.amount),
|
||||
);
|
||||
}
|
||||
AccountType::Expense => {
|
||||
amount -= if debit {
|
||||
line.amount.amount
|
||||
} else {
|
||||
-line.amount.amount
|
||||
}
|
||||
amount = sub_in_range(
|
||||
amount,
|
||||
on_side(crate::Side::Debit, line.side, line.amount.amount),
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -952,10 +950,7 @@ pub fn general_ledger(
|
||||
for entry in &entries {
|
||||
let lines = entry.lines();
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
let signed = match line.side {
|
||||
crate::Side::Debit => line.amount.amount,
|
||||
crate::Side::Credit => -line.amount.amount,
|
||||
};
|
||||
let signed = signed_amount(line.side, line.amount.amount);
|
||||
if entry.date() < start {
|
||||
let slot = begin.entry(line.account).or_default();
|
||||
*slot = add_exact(*slot, signed, "an account's beginning balance")?;
|
||||
@@ -1005,15 +1000,15 @@ pub fn general_ledger(
|
||||
continue;
|
||||
}
|
||||
let normal = account.account_type.normal_side();
|
||||
let to_normal = |m: Decimal| if normal == crate::Side::Debit { m } else { -m };
|
||||
let beginning_balance = to_normal(begin_movement) + Decimal::ZERO;
|
||||
let to_normal = |m: Decimal| on_side(normal, crate::Side::Debit, m);
|
||||
let beginning_balance = add_in_range(to_normal(begin_movement), Decimal::ZERO);
|
||||
let mut balance = beginning_balance;
|
||||
let (mut total_debits, mut total_credits) = (Decimal::ZERO, Decimal::ZERO);
|
||||
let mut posted = Vec::with_capacity(lines.len());
|
||||
for (side, amount, mut p) in lines {
|
||||
balance = add_exact(
|
||||
balance,
|
||||
if side == normal { amount } else { -amount },
|
||||
on_side(normal, side, amount),
|
||||
"an account's running balance",
|
||||
)?;
|
||||
total_debits = add_exact(total_debits, p.debit, "an account's total debits")?;
|
||||
@@ -1602,7 +1597,7 @@ impl AssetRegister {
|
||||
/// don't carry yet (run `run_depreciation`); negative if the books
|
||||
/// carry more.
|
||||
pub fn unposted_depreciation(&self) -> Decimal {
|
||||
self.total_accumulated_scheduled - self.ledger_accumulated
|
||||
sub_in_range(self.total_accumulated_scheduled, self.ledger_accumulated)
|
||||
}
|
||||
|
||||
/// Accumulated depreciation in the accounts that no held asset's runs
|
||||
@@ -1610,14 +1605,14 @@ impl AssetRegister {
|
||||
/// from a run; otherwise an entry made by hand (or a run reversed
|
||||
/// after its asset left the books) is in them.
|
||||
pub fn unattributed_accumulated(&self) -> Decimal {
|
||||
self.ledger_accumulated - self.total_accumulated_posted
|
||||
sub_in_range(self.ledger_accumulated, self.total_accumulated_posted)
|
||||
}
|
||||
|
||||
/// Cost in the ledger's cost accounts that no held asset accounts for
|
||||
/// (equipment bought but not registered), or negative if registered
|
||||
/// cost isn't in the books.
|
||||
pub fn unregistered_cost(&self) -> Decimal {
|
||||
self.ledger_cost - self.total_cost
|
||||
sub_in_range(self.ledger_cost, self.total_cost)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1656,9 +1651,7 @@ pub fn register_row(
|
||||
let book_value = if disposed.is_some() {
|
||||
Decimal::ZERO
|
||||
} else {
|
||||
a.cost
|
||||
.amount
|
||||
.checked_sub(post)
|
||||
crate::kernel::Amount::checked_sub(a.cost.amount, post)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s book value", a.id)))?
|
||||
};
|
||||
Ok(Some(AssetRegisterRow {
|
||||
@@ -1745,23 +1738,18 @@ pub fn fixed_asset_register(
|
||||
cost_accounts.insert(a.cost_account);
|
||||
accum_accounts.insert(a.accum_depr_account);
|
||||
if row.disposed.is_none() {
|
||||
cost = cost
|
||||
.checked_add(row.cost)
|
||||
cost = crate::kernel::Amount::checked_add(cost, row.cost)
|
||||
.ok_or_else(|| too_large("cost"))?;
|
||||
scheduled = scheduled
|
||||
.checked_add(row.accumulated_scheduled)
|
||||
scheduled = crate::kernel::Amount::checked_add(scheduled, row.accumulated_scheduled)
|
||||
.ok_or_else(|| too_large("accumulated depreciation"))?;
|
||||
posted_total = posted_total
|
||||
.checked_add(row.accumulated_posted)
|
||||
posted_total = crate::kernel::Amount::checked_add(posted_total, row.accumulated_posted)
|
||||
.ok_or_else(|| too_large("posted depreciation"))?;
|
||||
match row.depreciable_basis {
|
||||
Some(b) => {
|
||||
depreciable_total = depreciable_total
|
||||
.checked_add(b)
|
||||
depreciable_total = crate::kernel::Amount::checked_add(depreciable_total, b)
|
||||
.ok_or_else(|| too_large("depreciable basis"))?;
|
||||
if let Some(b) = row.tax_basis_723 {
|
||||
total_723 = total_723
|
||||
.checked_add(b)
|
||||
total_723 = crate::kernel::Amount::checked_add(total_723, b)
|
||||
.ok_or_else(|| too_large("§723 basis"))?;
|
||||
}
|
||||
}
|
||||
@@ -1779,7 +1767,7 @@ pub fn fixed_asset_register(
|
||||
tb.lines
|
||||
.iter()
|
||||
.find(|l| &l.code == code)
|
||||
.map(|l| l.debit - l.credit)
|
||||
.map(|l| sub_in_range(l.debit, l.credit))
|
||||
.unwrap_or(Decimal::ZERO)
|
||||
};
|
||||
Ok(AssetRegister {
|
||||
@@ -1788,17 +1776,16 @@ pub fn fixed_asset_register(
|
||||
total_cost: cost,
|
||||
total_accumulated_scheduled: scheduled,
|
||||
total_accumulated_posted: posted_total,
|
||||
total_book_value: cost
|
||||
.checked_sub(posted_total)
|
||||
total_book_value: crate::kernel::Amount::checked_sub(cost, posted_total)
|
||||
.ok_or_else(|| too_large("book value"))?,
|
||||
total_depreciable_basis: depreciable_total,
|
||||
total_tax_basis_723: total_723,
|
||||
missing_basis: missing,
|
||||
ledger_cost: sum_exact_of(&cost_accounts, |&id| net(id), "the ledger's asset cost")?,
|
||||
ledger_accumulated: -sum_exact_of(
|
||||
ledger_accumulated: neg(sum_exact_of(
|
||||
&accum_accounts,
|
||||
|&id| net(id),
|
||||
"the ledger's accumulated depreciation",
|
||||
)?,
|
||||
)?),
|
||||
})
|
||||
}
|
||||
@@ -668,13 +668,15 @@ impl AmortizationSchedule {
|
||||
/// The amount not yet recognized: the sum of the plan's unposted
|
||||
/// months.
|
||||
pub fn remaining(&self) -> Result<Decimal, LedgerError> {
|
||||
self.plan()?
|
||||
.into_iter()
|
||||
.filter(|(d, _)| !self.posted.contains(d))
|
||||
.try_fold(Decimal::ZERO, |sum, (_, a)| sum.checked_add(a))
|
||||
.ok_or_else(|| {
|
||||
LedgerError::TooLargeToCompute(format!("schedule {}'s remaining amount", self.id))
|
||||
})
|
||||
crate::kernel::total_of(
|
||||
self.plan()?
|
||||
.into_iter()
|
||||
.filter(|(d, _)| !self.posted.contains(d)),
|
||||
|(_, a)| a,
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
LedgerError::TooLargeToCompute(format!("schedule {}'s remaining amount", self.id))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -808,8 +810,7 @@ pub fn validate_recurring_journaled(
|
||||
Side::Debit => &mut debits,
|
||||
Side::Credit => &mut credits,
|
||||
};
|
||||
*total = total
|
||||
.checked_add(money.amount)
|
||||
*total = crate::kernel::Amount::checked_add(*total, money.amount)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute("the recurring entry's total".into()))?;
|
||||
}
|
||||
if debits != credits {
|
||||
|
||||
@@ -850,10 +850,11 @@ pub fn parse_share(name: &str, s: &str) -> Result<Decimal, String> {
|
||||
let s = s.trim();
|
||||
let bad = || format!("member {name}: share {s:?} must be like \"50%\" or \"0.5\"");
|
||||
let share = match s.strip_suffix('%') {
|
||||
Some(pct) => decimal(pct.trim())
|
||||
.ok_or_else(bad)?
|
||||
.checked_div(Decimal::from(100))
|
||||
.ok_or_else(bad)?,
|
||||
Some(pct) => crate::kernel::Amount::checked_div(
|
||||
decimal(pct.trim()).ok_or_else(bad)?,
|
||||
Decimal::from(100),
|
||||
)
|
||||
.ok_or_else(bad)?,
|
||||
None => decimal(s).ok_or_else(bad)?,
|
||||
};
|
||||
if share <= Decimal::ZERO || share > Decimal::ONE {
|
||||
@@ -1404,9 +1405,7 @@ fn check_members(list: &[Value]) -> Result<Vec<Member>, String> {
|
||||
}
|
||||
}
|
||||
if !members.is_empty() {
|
||||
let total = members
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |t, m| t.checked_add(m.share))
|
||||
let total = crate::kernel::total_of(members.iter(), |m| m.share)
|
||||
.ok_or("member shares are too large to add")?;
|
||||
if total != Decimal::ONE {
|
||||
return Err(format!("member shares sum to {total}, not 100%"));
|
||||
|
||||
@@ -128,6 +128,7 @@
|
||||
|
||||
pub use crate::kernel::Direction;
|
||||
use crate::kernel::{self, PartyTarget};
|
||||
use crate::money::{neg, on_side};
|
||||
use crate::{AccountId, AccountType, EntryId, JournalEntry, Ledger, LedgerError, PartyId, Side};
|
||||
use rust_decimal::Decimal;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -257,7 +258,12 @@ pub fn check_shares_journaled(
|
||||
));
|
||||
}
|
||||
any_percent = true;
|
||||
percent += p;
|
||||
percent = crate::kernel::Amount::checked_add(percent, p).ok_or_else(|| {
|
||||
format!(
|
||||
"party {}'s percent has too many digits to add up exactly",
|
||||
s.party
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Share::Derived => {}
|
||||
}
|
||||
@@ -275,9 +281,7 @@ fn too_large(what: String) -> crate::LedgerError {
|
||||
|
||||
/// The sum of `values`, or None past exact arithmetic.
|
||||
fn checked_sum(values: impl IntoIterator<Item = Decimal>) -> Option<Decimal> {
|
||||
values
|
||||
.into_iter()
|
||||
.try_fold(Decimal::ZERO, |s, v| s.checked_add(v))
|
||||
crate::kernel::total(values)
|
||||
}
|
||||
|
||||
/// Split `magnitude` (non-negative) by `weights` (positive, any sum): each
|
||||
@@ -407,7 +411,7 @@ fn original_target(
|
||||
kind(a) == Some(AccountType::Asset) && !money.cash.contains(&a) && Some(a) != receivables
|
||||
};
|
||||
let add = |t: &mut Decimal, v: Decimal| -> Result<(), LedgerError> {
|
||||
*t = t.checked_add(v).ok_or_else(past_exact)?;
|
||||
*t = crate::kernel::Amount::checked_add(*t, v).ok_or_else(past_exact)?;
|
||||
Ok(())
|
||||
};
|
||||
let zero = Decimal::ZERO;
|
||||
@@ -528,12 +532,13 @@ pub fn split(
|
||||
let parts: Vec<Decimal> = named
|
||||
.iter()
|
||||
.map(|m| {
|
||||
checked_sum(entry.lines().iter().filter(|l| on(m, l.account)).map(|l| {
|
||||
match l.side {
|
||||
Side::Credit => l.amount.amount,
|
||||
Side::Debit => -l.amount.amount,
|
||||
}
|
||||
}))
|
||||
checked_sum(
|
||||
entry
|
||||
.lines()
|
||||
.iter()
|
||||
.filter(|l| on(m, l.account))
|
||||
.map(|l| on_side(Side::Credit, l.side, l.amount.amount)),
|
||||
)
|
||||
.map(|s| s.abs())
|
||||
})
|
||||
.collect::<Option<_>>()
|
||||
@@ -576,7 +581,7 @@ pub fn split(
|
||||
let left: Vec<Decimal> = sizes
|
||||
.iter()
|
||||
.zip(&in_kind_sizes)
|
||||
.map(|(s, k)| s.checked_sub(*k))
|
||||
.map(|(s, k)| crate::kernel::Amount::checked_sub(*s, *k))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(past_exact)?;
|
||||
let cash_sizes = if cash == checked_sum(left.iter().copied()).ok_or_else(past_exact)? {
|
||||
@@ -587,7 +592,7 @@ pub fn split(
|
||||
share_by(cash, &left, &order).ok_or_else(past_exact)?
|
||||
};
|
||||
let negative = target.amount < Decimal::ZERO;
|
||||
let signed = |v: Decimal| if negative && !v.is_zero() { -v } else { v };
|
||||
let signed = |v: Decimal| if negative && !v.is_zero() { neg(v) } else { v };
|
||||
Ok(shares
|
||||
.iter()
|
||||
.enumerate()
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
//! Scope is deliberate, like fixed assets: no tax depreciation (MACRS,
|
||||
//! Section 179, bonus), no basis computations, no filing. Not tax advice.
|
||||
|
||||
use crate::money::{neg, sub_in_range};
|
||||
use crate::{AccountType, Ledger, LedgerError};
|
||||
use chrono::NaiveDate;
|
||||
use rust_decimal::Decimal;
|
||||
@@ -513,21 +514,29 @@ pub struct TaxSummary {
|
||||
impl TaxSummary {
|
||||
/// Book net income of the categorized accounts.
|
||||
pub fn book_net(&self) -> Decimal {
|
||||
sum(&self.income, |l| l.book)
|
||||
- sum(&self.cost_of_goods, |l| l.book)
|
||||
- sum(&self.deductions, |l| l.book)
|
||||
sub_in_range(
|
||||
sub_in_range(
|
||||
sum(&self.income, |l| l.book),
|
||||
sum(&self.cost_of_goods, |l| l.book),
|
||||
),
|
||||
sum(&self.deductions, |l| l.book),
|
||||
)
|
||||
}
|
||||
|
||||
/// Income less deductible amounts, before the CPA's other adjustments.
|
||||
pub fn tax_net(&self) -> Decimal {
|
||||
sum(&self.income, |l| l.tax)
|
||||
- sum(&self.cost_of_goods, |l| l.tax)
|
||||
- sum(&self.deductions, |l| l.tax)
|
||||
sub_in_range(
|
||||
sub_in_range(
|
||||
sum(&self.income, |l| l.tax),
|
||||
sum(&self.cost_of_goods, |l| l.tax),
|
||||
),
|
||||
sum(&self.deductions, |l| l.tax),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn sum(lines: &[TaxSummaryLine], f: fn(&TaxSummaryLine) -> Decimal) -> Decimal {
|
||||
lines.iter().map(f).sum()
|
||||
crate::kernel::total_of(lines, f).expect("posted lines are in range, so their sums are")
|
||||
}
|
||||
|
||||
/// A category's line while it is being built, with the exact `(book,
|
||||
@@ -570,7 +579,7 @@ pub fn tax_summary(
|
||||
// Income from an expense-type account (e.g. a contra) counts with
|
||||
// its sign flipped, so returns reduce receipts.
|
||||
let book = if c.kind == TaxKind::Income && account.account_type == AccountType::Expense {
|
||||
-line.amount
|
||||
neg(line.amount)
|
||||
} else {
|
||||
line.amount
|
||||
};
|
||||
@@ -593,9 +602,7 @@ pub fn tax_summary(
|
||||
(&mut build.line, &mut build.shares)
|
||||
};
|
||||
entry.accounts.push(name);
|
||||
entry.book = entry
|
||||
.book
|
||||
.checked_add(book)
|
||||
entry.book = crate::kernel::Amount::checked_add(entry.book, book)
|
||||
.ok_or_else(|| too_large("book amount"))?;
|
||||
shares.push((book, pct));
|
||||
}
|
||||
|
||||
@@ -80,6 +80,7 @@
|
||||
|
||||
use crate::k1::{K1Kind, K1Row, k1_detail};
|
||||
use crate::money::sum_exact_of;
|
||||
use crate::money::{neg, signed_amount};
|
||||
use crate::reports::MemberCapital;
|
||||
use crate::{AccountId, AssetId, AssetStatus, EntryId, Ledger, LedgerError, Side};
|
||||
use chrono::NaiveDate;
|
||||
@@ -120,16 +121,11 @@ fn disposal_depreciation(
|
||||
}) else {
|
||||
return Ok(Decimal::ZERO);
|
||||
};
|
||||
e.lines()
|
||||
.iter()
|
||||
.filter(|l| l.account == a.expense_account)
|
||||
.try_fold(Decimal::ZERO, |t, l| {
|
||||
t.checked_add(match l.side {
|
||||
Side::Debit => l.amount.amount,
|
||||
Side::Credit => -l.amount.amount,
|
||||
})
|
||||
})
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s depreciation", a.id)))
|
||||
crate::kernel::total_of(
|
||||
e.lines().iter().filter(|l| l.account == a.expense_account),
|
||||
|l| signed_amount(l.side, l.amount.amount),
|
||||
)
|
||||
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s depreciation", a.id)))
|
||||
}
|
||||
|
||||
/// A figure the books can't know, with what they do have.
|
||||
@@ -437,10 +433,7 @@ impl RunningSplit {
|
||||
weights.len()
|
||||
)));
|
||||
}
|
||||
let sum = weights
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |t, w| t.checked_add(*w))
|
||||
.ok_or_else(too_large)?;
|
||||
let sum = crate::kernel::total_of(weights.iter(), |w| *w).ok_or_else(too_large)?;
|
||||
Ok((sum > Decimal::ZERO).then_some(sum))
|
||||
}
|
||||
|
||||
@@ -469,11 +462,10 @@ impl RunningSplit {
|
||||
}
|
||||
let mut exact = self.exact.clone();
|
||||
for (x, w) in exact.iter_mut().zip(weights) {
|
||||
*x = x
|
||||
.checked_add(Self::share(whole, *w, sum)?)
|
||||
*x = crate::kernel::Amount::checked_add(*x, Self::share(whole, *w, sum)?)
|
||||
.ok_or_else(too_large)?;
|
||||
}
|
||||
let total = self.total.checked_add(whole).ok_or_else(too_large)?;
|
||||
let total = crate::kernel::Amount::checked_add(self.total, whole).ok_or_else(too_large)?;
|
||||
// A loss is rounded as its magnitude, then negated; at a running
|
||||
// whole of zero, by the sign of this whole (INVARIANT 2).
|
||||
let sign = if total < Decimal::ZERO || (total.is_zero() && whole < Decimal::ZERO) {
|
||||
@@ -485,7 +477,13 @@ impl RunningSplit {
|
||||
// rounded down to the cent, what rounding took its remainder.
|
||||
let snapped: Vec<Decimal> = exact
|
||||
.iter()
|
||||
.map(|x| round_places(x * sign, EXACT_PLACES, Rounding::HalfToEven))
|
||||
.map(|x| {
|
||||
round_places(
|
||||
crate::kernel::Amount::checked_mul(*x, sign)?,
|
||||
EXACT_PLACES,
|
||||
Rounding::HalfToEven,
|
||||
)
|
||||
})
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(too_large)?;
|
||||
let mut parts: Vec<Decimal> = snapped
|
||||
@@ -493,10 +491,20 @@ impl RunningSplit {
|
||||
.map(|x| round_places(*x, 2, Rounding::TowardNegativeInfinity))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(too_large)?;
|
||||
let remainders: Vec<Decimal> = snapped.iter().zip(&parts).map(|(x, p)| x - p).collect();
|
||||
let given: Vec<Decimal> = self.given.iter().map(|g| g * sign).collect();
|
||||
let remainders: Vec<Decimal> = snapped
|
||||
.iter()
|
||||
.zip(&parts)
|
||||
.map(|(x, p)| crate::kernel::Amount::checked_sub(*x, *p))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(too_large)?;
|
||||
let given: Vec<Decimal> = self
|
||||
.given
|
||||
.iter()
|
||||
.map(|g| crate::kernel::Amount::checked_mul(*g, sign))
|
||||
.collect::<Option<_>>()
|
||||
.ok_or_else(too_large)?;
|
||||
crate::kernel::apportion_cumulative(
|
||||
total * sign,
|
||||
crate::kernel::Amount::checked_mul(total, sign).ok_or_else(too_large)?,
|
||||
&mut parts,
|
||||
&remainders,
|
||||
Decimal::new(1, 2),
|
||||
@@ -504,8 +512,8 @@ impl RunningSplit {
|
||||
)
|
||||
.ok_or_else(too_large)?;
|
||||
for (p, g) in parts.iter_mut().zip(self.given.iter_mut()) {
|
||||
*p *= sign;
|
||||
*g = g.checked_add(*p).ok_or_else(too_large)?;
|
||||
*p = crate::kernel::Amount::checked_mul(*p, sign).ok_or_else(too_large)?;
|
||||
*g = crate::kernel::Amount::checked_add(*g, *p).ok_or_else(too_large)?;
|
||||
}
|
||||
self.exact = exact;
|
||||
self.total = total;
|
||||
@@ -538,12 +546,13 @@ impl RunningSplit {
|
||||
let mut exact = self.exact.clone();
|
||||
let mut given = self.given.clone();
|
||||
for i in 0..n {
|
||||
exact[i] = exact[i]
|
||||
.checked_sub(Self::share(whole, weights[i], sum)?)
|
||||
.ok_or_else(too_large)?;
|
||||
given[i] = given[i].checked_sub(parts[i]).ok_or_else(too_large)?;
|
||||
exact[i] =
|
||||
crate::kernel::Amount::checked_sub(exact[i], Self::share(whole, weights[i], sum)?)
|
||||
.ok_or_else(too_large)?;
|
||||
given[i] =
|
||||
crate::kernel::Amount::checked_sub(given[i], parts[i]).ok_or_else(too_large)?;
|
||||
}
|
||||
self.total = self.total.checked_sub(whole).ok_or_else(too_large)?;
|
||||
self.total = crate::kernel::Amount::checked_sub(self.total, whole).ok_or_else(too_large)?;
|
||||
self.exact = exact;
|
||||
self.given = given;
|
||||
Ok(())
|
||||
@@ -611,21 +620,17 @@ fn entry_wholes(
|
||||
// Distributions are negative lines; weights are what each took.
|
||||
let taken: Vec<Decimal> = by_member(K1Kind::Distribution)?
|
||||
.into_iter()
|
||||
.map(|d| -d)
|
||||
.map(neg)
|
||||
.collect();
|
||||
if taken.iter().any(|t| *t > Decimal::ZERO) {
|
||||
let property = e
|
||||
.lines()
|
||||
.iter()
|
||||
.filter(|l| {
|
||||
let property = crate::kernel::total_of(
|
||||
e.lines().iter().filter(|l| {
|
||||
l.side == Side::Credit && crate::k1::is_property_account(ledger, cash, l.account)
|
||||
})
|
||||
.try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount))
|
||||
.ok_or_else(too_large)?;
|
||||
let total_taken = taken
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |t, x| t.checked_add(*x))
|
||||
.ok_or_else(too_large)?;
|
||||
}),
|
||||
|l| l.amount.amount,
|
||||
)
|
||||
.ok_or_else(too_large)?;
|
||||
let total_taken = crate::kernel::total_of(taken.iter(), |x| *x).ok_or_else(too_large)?;
|
||||
let property = property.min(total_taken);
|
||||
if property > Decimal::ZERO {
|
||||
out.push((DISTRIBUTED, property, taken));
|
||||
@@ -736,14 +741,13 @@ fn entry_property(
|
||||
entry: &crate::JournalEntry,
|
||||
cash: &[AccountId],
|
||||
) -> Result<EntryProperty, LedgerError> {
|
||||
let pool = entry
|
||||
.lines()
|
||||
.iter()
|
||||
.filter(|l| {
|
||||
let pool = crate::kernel::total_of(
|
||||
entry.lines().iter().filter(|l| {
|
||||
l.side == Side::Debit && crate::k1::is_property_account(ledger, cash, l.account)
|
||||
})
|
||||
.try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount))
|
||||
.ok_or_else(too_large)?;
|
||||
}),
|
||||
|l| l.amount.amount,
|
||||
)
|
||||
.ok_or_else(too_large)?;
|
||||
// Prepaid accounts: those a prepaid-expense schedule amortizes, and no
|
||||
// registered asset carries its cost in (INVARIANT 6).
|
||||
let prepaid_account = |id: AccountId| {
|
||||
@@ -751,17 +755,16 @@ fn entry_property(
|
||||
s.kind == crate::schedules::ScheduleKind::PrepaidExpense && s.balance_account == id
|
||||
}) && !ledger.registered_assets().any(|a| a.cost_account == id)
|
||||
};
|
||||
let prepaid = entry
|
||||
.lines()
|
||||
.iter()
|
||||
.filter(|l| {
|
||||
let prepaid = crate::kernel::total_of(
|
||||
entry.lines().iter().filter(|l| {
|
||||
l.side == Side::Debit
|
||||
&& crate::k1::is_property_account(ledger, cash, l.account)
|
||||
&& prepaid_account(l.account)
|
||||
})
|
||||
.try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount))
|
||||
.ok_or_else(too_large)?;
|
||||
let pool = pool.checked_sub(prepaid).ok_or_else(too_large)?;
|
||||
}),
|
||||
|l| l.amount.amount,
|
||||
)
|
||||
.ok_or_else(too_large)?;
|
||||
let pool = crate::kernel::Amount::checked_sub(pool, prepaid).ok_or_else(too_large)?;
|
||||
let (mut linked, mut big, mut unknown) = (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO);
|
||||
for a in ledger
|
||||
.registered_assets()
|
||||
@@ -772,11 +775,14 @@ fn entry_property(
|
||||
// Its book amount in the entry: the value at contribution, which
|
||||
// the books recorded (D-41), or the book cost.
|
||||
let value = a.fmv_at_contribution().unwrap_or(a.cost.amount);
|
||||
linked = linked.checked_add(value).ok_or_else(too_large)?;
|
||||
linked = crate::kernel::Amount::checked_add(linked, value).ok_or_else(too_large)?;
|
||||
match contributed {
|
||||
Some(g) => big = big.checked_add(g).ok_or_else(too_large)?,
|
||||
Some(g) => big = crate::kernel::Amount::checked_add(big, g).ok_or_else(too_large)?,
|
||||
// No basis, or a purchase's basis on a contribution: unknown.
|
||||
None => unknown = unknown.checked_add(value).ok_or_else(too_large)?,
|
||||
None => {
|
||||
unknown =
|
||||
crate::kernel::Amount::checked_add(unknown, value).ok_or_else(too_large)?
|
||||
}
|
||||
}
|
||||
}
|
||||
if linked > pool {
|
||||
@@ -787,11 +793,11 @@ fn entry_property(
|
||||
mismatch: Some((linked, pool)),
|
||||
});
|
||||
}
|
||||
let rest = pool.checked_sub(linked).ok_or_else(too_large)?;
|
||||
let rest = crate::kernel::Amount::checked_sub(pool, linked).ok_or_else(too_large)?;
|
||||
Ok(EntryProperty {
|
||||
built_in_gain: big,
|
||||
prepaid,
|
||||
without_basis: unknown.checked_add(rest).ok_or_else(too_large)?,
|
||||
without_basis: crate::kernel::Amount::checked_add(unknown, rest).ok_or_else(too_large)?,
|
||||
mismatch: None,
|
||||
})
|
||||
}
|
||||
@@ -855,8 +861,9 @@ fn span(
|
||||
book: pp,
|
||||
});
|
||||
}
|
||||
big[i] = big[i].checked_add(g).ok_or_else(too_large)?;
|
||||
without[i] = without[i].checked_add(w).ok_or_else(too_large)?;
|
||||
big[i] = crate::kernel::Amount::checked_add(big[i], g).ok_or_else(too_large)?;
|
||||
without[i] =
|
||||
crate::kernel::Amount::checked_add(without[i], w).ok_or_else(too_large)?;
|
||||
if let Some((linked, property)) = p.mismatch {
|
||||
prop_open[i].push(Open::LinkedValueExceedsEntry {
|
||||
entry: id,
|
||||
@@ -873,7 +880,8 @@ fn span(
|
||||
for i in 0..n {
|
||||
let book = part.get(DISTRIBUTED, i);
|
||||
if !book.is_zero() {
|
||||
distributed[i] = distributed[i].checked_add(book).ok_or_else(too_large)?;
|
||||
distributed[i] = crate::kernel::Amount::checked_add(distributed[i], book)
|
||||
.ok_or_else(too_large)?;
|
||||
dist_open[i].push(Open::PropertyDistribution { entry: id, book });
|
||||
}
|
||||
}
|
||||
@@ -888,13 +896,15 @@ fn span(
|
||||
if a.in_service_date <= end && !gone_before {
|
||||
in_service = true;
|
||||
}
|
||||
let d = ledger
|
||||
.depreciation_posted_between(a.id, start, end)?
|
||||
.checked_add(disposal_depreciation(ledger, a, start, end)?)
|
||||
.ok_or_else(too_large)?;
|
||||
book_depr = book_depr.checked_add(d).ok_or_else(too_large)?;
|
||||
let d = crate::kernel::Amount::checked_add(
|
||||
ledger.depreciation_posted_between(a.id, start, end)?,
|
||||
disposal_depreciation(ledger, a, start, end)?,
|
||||
)
|
||||
.ok_or_else(too_large)?;
|
||||
book_depr = crate::kernel::Amount::checked_add(book_depr, d).ok_or_else(too_large)?;
|
||||
if a.basis.as_ref().is_some_and(|b| b.rule.is_contribution()) {
|
||||
contributed_depr = contributed_depr.checked_add(d).ok_or_else(too_large)?;
|
||||
contributed_depr =
|
||||
crate::kernel::Amount::checked_add(contributed_depr, d).ok_or_else(too_large)?;
|
||||
}
|
||||
}
|
||||
if in_service || !book_depr.is_zero() {
|
||||
@@ -930,10 +940,8 @@ fn span(
|
||||
None => TaxLine::complete(book.beginning),
|
||||
};
|
||||
let contributions_property = TaxLine {
|
||||
known: book
|
||||
.contributions_property
|
||||
.checked_sub(big[i])
|
||||
.and_then(|x| x.checked_sub(without[i]))
|
||||
known: crate::kernel::Amount::checked_sub(book.contributions_property, big[i])
|
||||
.and_then(|x| crate::kernel::Amount::checked_sub(x, without[i]))
|
||||
.ok_or_else(too_large)?,
|
||||
open: std::mem::take(&mut prop_open[i]),
|
||||
notes: std::mem::take(&mut prop_notes[i]),
|
||||
@@ -957,20 +965,16 @@ fn span(
|
||||
notes: Vec::new(),
|
||||
};
|
||||
let distributions = TaxLine {
|
||||
known: book
|
||||
.distributions
|
||||
.checked_sub(distributed[i])
|
||||
known: crate::kernel::Amount::checked_sub(book.distributions, distributed[i])
|
||||
.ok_or_else(too_large)?,
|
||||
open: std::mem::take(&mut dist_open[i]),
|
||||
notes: Vec::new(),
|
||||
};
|
||||
let known = beginning
|
||||
.known
|
||||
.checked_add(book.contributions_cash)
|
||||
.and_then(|x| x.checked_add(contributions_property.known))
|
||||
.and_then(|x| x.checked_add(net_income.known))
|
||||
.and_then(|x| x.checked_add(other.known))
|
||||
.and_then(|x| x.checked_sub(distributions.known))
|
||||
let known = crate::kernel::Amount::checked_add(beginning.known, book.contributions_cash)
|
||||
.and_then(|x| crate::kernel::Amount::checked_add(x, contributions_property.known))
|
||||
.and_then(|x| crate::kernel::Amount::checked_add(x, net_income.known))
|
||||
.and_then(|x| crate::kernel::Amount::checked_add(x, other.known))
|
||||
.and_then(|x| crate::kernel::Amount::checked_sub(x, distributions.known))
|
||||
.ok_or_else(too_large)?;
|
||||
let ending = TaxLine {
|
||||
known,
|
||||
@@ -987,9 +991,7 @@ fn span(
|
||||
notes: Vec::new(),
|
||||
};
|
||||
let reconciliation = Reconciliation {
|
||||
beginning: book
|
||||
.beginning
|
||||
.checked_sub(beginning.known)
|
||||
beginning: crate::kernel::Amount::checked_sub(book.beginning, beginning.known)
|
||||
.ok_or_else(too_large)?,
|
||||
built_in_gain_704c: big[i],
|
||||
property_without_basis: without[i],
|
||||
|
||||
Reference in new issue
Block a user