refactor(gui): the viewer's Decimal arithmetic goes through the kernel (K-U12)

The detector (scripts/raw-decimal-arith.sh ledger-gui) counted 123 places
in the viewer that did Decimal arithmetic outside the kernel; it counts 0
now. No figure the viewer shows changes: a raw operator panicked when the
exact answer did not fit, and add_in_range / sub_in_range / neg panic in
exactly that case; rust_decimal's checked_* methods, which round past 96
bits, became the kernel's Amount::checked_* (exact or None), with the
existing None handling untouched.

Places that are not plain sums or differences, and what each became:
- Sums of balances and posted lines (receivables, due to members, a
  disposal's true-up, a statement row across columns, cleared total):
  kernel::total / total_of; a refused sum is an expect where the figure
  is drawn from the books, and a blank cell in the cash-flow keyed rows
  (which already blank a refused statement).
- The share split (books.rs): share_of(v, share, net), the same multiply
  then divide; the scaled parts use checked_mul_rounded because the
  fraction is a quotient, truncated to cents on the next line.
- Percents of a share (capital, company, reports): checked_mul_rounded
  by 100, exactly what * did.
- Averages and runway (monthly burn, cash runway, net per month, a
  third of an amount, build-in pct): Amount::checked_div, a None joins
  the None or "can't compute" the code already has.
- The 125% watch threshold: checked_mul_rounded and is_some_and.
- Rescale to one place (pct): rescale_exact, keeping the value when it
  would round.
- The demo's rounding to a step ((x / 50).round() * 50): to_step, the
  same half-to-even rounding through round_places.
- f32 widths and usize counts: plain folds, no allow.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude committed 2026-11-10 01:07:35 -07:00
1 parent 0de906e9ed
commit e4c41ccb3f
16 files changed
+244 -151

No files matched your search

+6 -5
View File
@@ -21,6 +21,7 @@ use crate::widgets;
use chrono::{Datelike, NaiveDate};
use egui::{Color32, CornerRadius, Margin, RichText, Sense, Ui, vec2};
use egui_phosphor::regular as icon;
use ledger_core::money::{neg, sub_in_range};
use ledger_core::{
Asset, AssetId, AssetRegister, AssetRegisterRow, AssetStatus, BasisRule, Sec704cMethod,
};
@@ -91,7 +92,7 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec<Notice> {
),
});
}
let accruing = unposted - due_amount;
let accruing = sub_in_range(unposted, due_amount);
if accruing > Decimal::ZERO {
out.push(Notice {
problem: false,
@@ -108,7 +109,7 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec<Notice> {
problem: true,
text: format!(
"The books carry {} more accumulated depreciation than the schedules through {} — ask the bookkeeper to check the depreciation entries.",
fmt::dollars(-unposted),
fmt::dollars(neg(unposted)),
fmt::date(r.as_of)
),
});
@@ -127,7 +128,7 @@ pub fn notices(b: &Books, r: &AssetRegister) -> Vec<Notice> {
problem: true,
text: format!(
"{} of registered cost isn't in the books' asset cost accounts — ask the bookkeeper to check the purchase entries.",
fmt::dollars(-unregistered)
fmt::dollars(neg(unregistered))
),
});
}
@@ -324,7 +325,7 @@ impl TaxFacts {
/// figure, for a built-in gain (+) or loss (−).
pub fn gain_or_loss(g: Decimal) -> (&'static str, Decimal) {
if g < Decimal::ZERO {
("Built-in loss", -g)
("Built-in loss", neg(g))
} else {
("Built-in gain", g)
}
@@ -399,7 +400,7 @@ pub(crate) fn row(
ui.painter().rect_filled(r, CornerRadius::same(4), p.hover);
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
let fixed: f32 = cells.iter().map(|c| c.1).sum();
let fixed: f32 = cells.iter().map(|c| c.1).fold(0.0_f32, |a, b| a + b);
let flex = (w - fixed).max(40.0);
let painter = ui.painter_at(r);
let font = if strong {
+15 -5
View File
@@ -12,6 +12,8 @@ use crate::nav::Route;
use crate::theme::{self, pal};
use crate::widgets;
use egui::{Align, Layout, RichText, Sense, Ui, vec2};
use ledger_core::kernel::Amount;
use ledger_core::money::{add_in_range, neg, sub_in_range};
use rust_decimal::Decimal;
/// What a capital line is, in words.
@@ -29,7 +31,8 @@ pub fn kind_label(k: CapitalKind) -> &'static str {
/// decimal multiplication (never a float, never rounded); only a
/// negative zero is dropped.
pub fn percent(share: Decimal) -> String {
let p = share * Decimal::ONE_HUNDRED;
let p = Amount::checked_mul_rounded(share, Decimal::ONE_HUNDRED)
.expect("a member's share is at most one, so a hundred times it fits");
let p = if p.is_zero() { Decimal::ZERO } else { p };
format!("{}%", p.normalize())
}
@@ -181,7 +184,7 @@ pub fn capital_card(
ui,
"Distributions",
16.0,
Some(fmt::accounting(-st.distributions_taken)),
Some(fmt::accounting(neg(st.distributions_taken))),
None,
false,
);
@@ -189,9 +192,16 @@ pub fn capital_card(
line(ui, "Other changes", 16.0, amt(st.other), None, false);
}
underline(ui, false, false);
let change = st.contributions_cash + st.contributions_property + st.income_share
- st.distributions_taken
+ st.other;
let change = add_in_range(
sub_in_range(
add_in_range(
add_in_range(st.contributions_cash, st.contributions_property),
st.income_share,
),
st.distributions_taken,
),
st.other,
);
line(
ui,
"Net change in capital",
+12 -13
View File
@@ -13,6 +13,8 @@ use chrono::{Datelike, Days, NaiveDate};
use egui::{CornerRadius, RichText, Sense, Ui, vec2};
use egui_phosphor::regular as icon;
use ledger_core::analysis::{Interval, balance_history, flows_by_interval, interval_start};
use ledger_core::kernel::Amount;
use ledger_core::money::{add_in_range, neg, sub_in_range};
use rust_decimal::Decimal;
pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
@@ -29,7 +31,7 @@ pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
);
let (cin, cout): (Decimal, Decimal) =
flows.iter().fold((Decimal::ZERO, Decimal::ZERO), |a, f| {
(a.0 + f.2, a.1 + f.3)
(add_in_range(a.0, f.2), add_in_range(a.1, f.3))
});
widgets::page_header(
ui,
@@ -74,7 +76,7 @@ pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
.collect();
let bal = b.balance_on(*id, b.today);
let ago = b.balance_on(*id, since);
let delta = bal - ago;
let delta = sub_in_range(bal, ago);
let r = widgets::kpi(
ui,
widgets::Kpi {
@@ -186,7 +188,7 @@ fn runway(ui: &mut Ui, b: &Books) {
let Some(net) = ledger_core::kernel::total_try(&months, |&(_, _, i, o)| {
ledger_core::kernel::Amount::checked_sub(i, o)
})
.and_then(|sum| sum.checked_div(Decimal::from(months.len() as u64))) else {
.and_then(|sum| Amount::checked_div(sum, Decimal::from(months.len() as u64))) else {
ui.label(RichText::new("The figures are too large to compute.").color(p.muted));
return;
};
@@ -224,13 +226,10 @@ fn runway(ui: &mut Ui, b: &Books) {
if net < Decimal::ZERO {
// Checked: a sub-cent average (lines an earlier version
// booked) makes a runway past any calendar.
let months_left = b
.kpis
.cash
.checked_div(-net)
let months_left = Amount::checked_div(b.kpis.cash, neg(net))
.map(|m| fmt::round_display(m, 1));
let out = months_left
.and_then(|m| m.checked_mul(Decimal::from(30)))
.and_then(|m| Amount::checked_mul(m, Decimal::from(30)))
.and_then(|d| u64::try_from(d).ok())
.and_then(|d| b.today.checked_add_days(Days::new(d)));
big(
@@ -319,9 +318,9 @@ fn coming_up(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
.filter(|(a, _, _)| b.cash_accounts.contains(a))
.try_fold(Decimal::ZERO, |sum, (_, s, m)| {
if *s == ledger_core::Side::Debit {
sum.checked_add(m.amount)
Amount::checked_add(sum, m.amount)
} else {
sum.checked_sub(m.amount)
Amount::checked_sub(sum, m.amount)
}
});
for d in occurrences_from(r, b.today, horizon) {
@@ -378,7 +377,7 @@ fn coming_up(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
items.push(Upcoming {
date: bill.due_date,
label: format!("Bill {id} to {who}"),
amount: balance.map(|x| -x),
amount: balance.map(neg),
route: Some(Route::Entry(bill.entry_id)),
});
}
@@ -409,9 +408,9 @@ fn coming_up(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
(Some(Decimal::ZERO), Some(Decimal::ZERO)),
|(inflow, outflow), i| match i.amount {
Some(a) if a > Decimal::ZERO => {
(inflow.and_then(|x| x.checked_add(a)), outflow)
(inflow.and_then(|x| Amount::checked_add(x, a)), outflow)
}
Some(a) => (inflow, outflow.and_then(|x| x.checked_sub(a))),
Some(a) => (inflow, outflow.and_then(|x| Amount::checked_sub(x, a))),
None => (None, None),
},
);
+26 -10
View File
@@ -12,6 +12,8 @@ use crate::widgets;
use egui::{CornerRadius, RichText, Sense, Ui, vec2};
use egui_phosphor::regular as icon;
use ledger_core::assets::accumulated_scheduled_through;
use ledger_core::kernel::Amount;
use ledger_core::money::sub_in_range;
use ledger_core::{AssetStatus, PeriodStatus};
use rust_decimal::Decimal;
@@ -247,7 +249,14 @@ pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
ui.label(RichText::new(&m.name).font(theme::semibold(13.5)));
widgets::pill(
ui,
&format!("{}%", (m.share * Decimal::from(100)).normalize()),
&format!(
"{}%",
Amount::checked_mul_rounded(m.share, Decimal::from(100))
.expect(
"a member's share is at most one, so a hundred times it fits"
)
.normalize()
),
p.accent,
p.accent_soft,
);
@@ -384,7 +393,7 @@ fn assets(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
let later = b.ledger.asset_acquired_date(a.id).filter(|d| *d > b.today);
let acc = b.ledger.accumulated_posted(a.id, b.today);
let scheduled = accumulated_scheduled_through(a, b.today);
let dep = a.cost.amount - a.salvage_value.amount;
let dep = sub_in_range(a.cost.amount, a.salvage_value.amount);
ui.horizontal_wrapped(|ui| {
if widgets::link(
ui,
@@ -416,7 +425,10 @@ fn assets(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
),
(_, Some(_)) => format!("book value {}", fmt::dollars(Decimal::ZERO)),
(Ok(acc), None) => {
format!("book value {}", fmt::dollars(a.cost.amount - *acc))
format!(
"book value {}",
fmt::dollars(sub_in_range(a.cost.amount, *acc))
)
}
(Err(e), None) => format!("book value can't be computed: {e}"),
};
@@ -433,13 +445,15 @@ fn assets(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
let frac: f32 = if dep.is_zero() {
1.0
} else {
(*acc / dep).try_into().unwrap_or(0.0)
Amount::checked_div(*acc, dep)
.and_then(|x| x.try_into().ok())
.unwrap_or(0.0)
};
let note = match scheduled {
Ok(s) if s > *acc => {
format!(
" · {} more scheduled through today",
fmt::dollars(s - *acc)
fmt::dollars(sub_in_range(s, *acc))
)
}
Ok(_) => String::new(),
@@ -514,11 +528,10 @@ fn schedules(ui: &mut Ui, b: &Books) {
continue;
}
};
let recognized = total.checked_sub(remaining);
let recognized = Amount::checked_sub(total, remaining);
let frac: f32 = match recognized {
_ if total.is_zero() => 1.0,
Some(r) => r
.checked_div(total)
Some(r) => Amount::checked_div(r, total)
.and_then(|x| x.try_into().ok())
.unwrap_or(0.0),
None => 0.0,
@@ -580,7 +593,9 @@ fn recurring(ui: &mut Ui, b: &Books) {
.lines
.iter()
.filter(|(_, s, _)| *s == ledger_core::Side::Debit)
.try_fold(Decimal::ZERO, |t, (_, _, m)| t.checked_add(m.amount));
.try_fold(Decimal::ZERO, |t, (_, _, m)| {
Amount::checked_add(t, m.amount)
});
let next = (0..)
.map_while(|k| {
r.frequency
@@ -715,7 +730,8 @@ fn parties(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
.filter_map(|i| b.ledger.get_invoice(i))
.filter(|i| i.customer_id == c.id)
.try_fold(Decimal::ZERO, |t, i| {
t.checked_add(
Amount::checked_add(
t,
b.owed_today(ledger_core::DocRef::Invoice(i.id)).ok()?,
)
});
+7 -3
View File
@@ -11,6 +11,8 @@ use crate::widgets;
use egui::{CornerRadius, Margin, RichText, Stroke, Ui, vec2};
use egui_phosphor::regular as icon;
use ledger_core::arap::DocumentLine;
use ledger_core::kernel::Amount;
use ledger_core::money::sub_in_range;
use ledger_core::{EntryStatus, Side};
use ledger_store::Attachment;
use rust_decimal::Decimal;
@@ -264,11 +266,13 @@ pub fn detail(ui: &mut Ui, b: &Books, e: &EntryInfo, shell: &mut Shell<'_>) {
let a = fmt::money(line.amount.amount);
let (d, c) = match line.side {
Side::Debit => {
dr = dr.and_then(|t| t.checked_add(line.amount.amount));
dr =
dr.and_then(|t| Amount::checked_add(t, line.amount.amount));
(a, String::new())
}
Side::Credit => {
cr = cr.and_then(|t| t.checked_add(line.amount.amount));
cr =
cr.and_then(|t| Amount::checked_add(t, line.amount.amount));
(String::new(), a)
}
};
@@ -720,7 +724,7 @@ pub fn share_text(
t.push_str(&format!(", {} in kind", fmt::dollars(in_kind.abs())));
}
}
let owed = v - cash - in_kind;
let owed = sub_in_range(sub_in_range(v, cash), in_kind);
if d != Direction::Neither && !owed.is_zero() {
t.push_str(&format!(", {} still owed", fmt::dollars(owed.abs())));
}
+6 -5
View File
@@ -16,6 +16,7 @@ use crate::widgets;
use chrono::NaiveDate;
use egui::Ui;
use egui_phosphor::regular as icon;
use ledger_core::money::add_in_range;
use ledger_core::{DocRef, DocState, DocStatus, DocumentLine};
use rust_decimal::Decimal;
@@ -200,7 +201,7 @@ pub fn summary(b: &Books, bills: bool) -> Option<(Decimal, usize, usize)> {
if let Ok(Some(st)) = &it.state
&& Filter::Open.keeps(st)
{
owed += st.outstanding;
owed = add_in_range(owed, st.outstanding);
if st.overdue_days > 0 {
late += 1;
} else if it.due <= week {
@@ -265,10 +266,10 @@ pub fn show_list(ui: &mut Ui, b: &Books, bills: bool, shell: &mut Shell<'_>) {
for it in &all {
match &it.state {
Ok(Some(st)) if Filter::Open.keeps(st) => {
owed += st.outstanding;
owed = add_in_range(owed, st.outstanding);
open_n += 1;
if st.overdue_days > 0 {
late += st.outstanding;
late = add_in_range(late, st.outstanding);
late_n += 1;
}
}
@@ -473,8 +474,8 @@ fn tie_out(b: &Books, bills: bool) -> (String, String, bool) {
return ("Agrees".into(), "No account holds them yet".into(), true);
}
let names: Vec<String> = mine.iter().map(|c| b.account_label(c.account)).collect();
let loose: usize = mine.iter().map(|c| c.unattached.len()).sum();
let odd: usize = mine.iter().map(|c| c.attention.len()).sum();
let loose: usize = mine.iter().fold(0_usize, |n, c| n + c.unattached.len());
let odd: usize = mine.iter().fold(0_usize, |n, c| n + c.attention.len());
let off = mine.iter().any(|c| !c.difference.is_zero());
if off {
("Differs".into(), "An engine error: report it".into(), false)
+1 -1
View File
@@ -88,7 +88,7 @@ pub fn columns(ui: &mut Ui, min_width: f32, weights: &[f32], mut add: impl FnMut
}
return;
}
let total: f32 = weights.iter().sum();
let total: f32 = weights.iter().fold(0.0_f32, |a, b| a + *b);
let avail = ui.available_width() - gap * (weights.len() as f32 - 1.0);
let top = ui.cursor().min;
let mut x = top.x;
+6 -3
View File
@@ -12,6 +12,8 @@ use crate::widgets::{self, Kpi};
use egui::{RichText, Ui};
use egui_phosphor::regular as icon;
use ledger_core::analysis::{Interval, pnl_by_interval};
use ledger_core::kernel::Amount;
use ledger_core::money::neg;
use ledger_core::reports::profit_and_loss_for_period;
use rust_decimal::Decimal;
@@ -66,7 +68,8 @@ fn headline(b: &Books) -> String {
if let Some(burn) = k.monthly_burn {
if burn > Decimal::ZERO
&& k.cash > Decimal::ZERO
&& let Some(months) = k.cash.checked_div(burn).map(|m| fmt::round_display(m, 1))
&& let Some(months) =
Amount::checked_div(k.cash, burn).map(|m| fmt::round_display(m, 1))
{
s.push_str(&format!(
" Lately you spend {} a month more than you earn: about {} months of runway.",
@@ -82,7 +85,7 @@ fn headline(b: &Books) -> String {
} else if k.net_ytd < Decimal::ZERO {
s.push_str(&format!(
" You've spent {} more than you've earned this year.",
fmt::dollars(-k.net_ytd)
fmt::dollars(neg(k.net_ytd))
));
}
if (b.today - first).num_days() < 60 {
@@ -136,7 +139,7 @@ fn kpis(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
.collect();
let runway = match k.monthly_burn {
Some(burn) if burn > Decimal::ZERO && k.cash > Decimal::ZERO => (
k.cash.checked_div(burn).map_or_else(
Amount::checked_div(k.cash, burn).map_or_else(
|| "—".to_string(),
|m| format!("{} mo", fmt::round_display(m, 1)),
),
+6 -5
View File
@@ -17,6 +17,7 @@ use crate::widgets;
use chrono::{Datelike, NaiveDate};
use egui::{CornerRadius, RichText, Stroke, Ui, vec2};
use egui_phosphor::regular as icon;
use ledger_core::money::{add_in_range, neg};
use ledger_core::{Party, PartyId, Role};
use rust_decimal::Decimal;
@@ -296,7 +297,7 @@ pub fn role_counts(b: &Books, show_archived: bool) -> Vec<(Role, usize)> {
/// with a plus (in green), as the transactions list shows cash.
fn paid_cell(paid: Decimal, p: &theme::Palette) -> (String, egui::Color32) {
if paid < Decimal::ZERO {
(format!("+{}", fmt::money(-paid)), p.positive)
(format!("+{}", fmt::money(neg(paid))), p.positive)
} else if paid.is_zero() {
("—".into(), p.faint)
} else {
@@ -570,8 +571,8 @@ pub fn in_kind_text(flow: &crate::books::PartyFlow) -> Option<String> {
}
Some(format!(
"With property contributed or distributed: paid {}, received {}",
fmt::dollars(flow.paid + flow.paid_in_kind),
fmt::dollars(flow.received + flow.received_in_kind)
fmt::dollars(add_in_range(flow.paid, flow.paid_in_kind)),
fmt::dollars(add_in_range(flow.received, flow.received_in_kind))
))
}
@@ -1552,7 +1553,7 @@ fn what_for_card(ui: &mut Ui, b: &Books, flow: &PartyFlow, label: &str, go: &mut
.find(|(r, _)| b.ledger.role_account(r) == Some(*account))
.map(|(_, n)| *n);
let (text, color) = if *amount < Decimal::ZERO {
(format!("+{}", fmt::money(-*amount)), p.positive)
(format!("+{}", fmt::money(neg(*amount))), p.positive)
} else {
(fmt::money(*amount), p.text)
};
@@ -1580,7 +1581,7 @@ fn what_for_card(ui: &mut Ui, b: &Books, flow: &PartyFlow, label: &str, go: &mut
("Net".into(), 0.0, false, p.text),
(
if net < Decimal::ZERO {
format!("+{}", fmt::money(-net))
format!("+{}", fmt::money(neg(net)))
} else {
fmt::money(net)
},
+14 -7
View File
@@ -14,6 +14,8 @@ use chrono::{Days, Months};
use egui::{CornerRadius, RichText, Sense, Ui, vec2};
use egui_phosphor::regular as icon;
use ledger_core::analysis::{Interval, interval_start, pnl_by_interval};
use ledger_core::kernel::Amount;
use ledger_core::money::sub_in_range;
use ledger_core::reports::profit_and_loss_for_period;
use rust_decimal::Decimal;
use std::collections::BTreeMap;
@@ -30,7 +32,7 @@ pub(crate) fn pct(part: Decimal, whole: Decimal) -> Option<Decimal> {
ledger_core::kernel::Rounding::HalfToEven,
)?;
// One place always, so 100% prints as "100.0", as 64.0 does.
x.rescale(1);
x = ledger_core::kernel::rescale_exact(x, 1).unwrap_or(x);
Some(x)
}
@@ -43,7 +45,7 @@ pub fn show(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
.as_ref()
.map(|p| (p.total_revenue, p.total_expenses))
.unwrap_or_default();
let net = rev - exp;
let net = sub_in_range(rev, exp);
let margin = pct(net, rev);
let sentence = match margin {
Some(m) => format!(
@@ -204,7 +206,10 @@ fn spending_changes(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
match slot {
0 => e.1 = l.amount,
1 => e.2 = l.amount,
_ => e.3 = l.amount / Decimal::from(3),
_ => {
e.3 = Amount::checked_div(l.amount, Decimal::from(3))
.expect("a third of a posted amount fits")
}
}
}
};
@@ -267,7 +272,9 @@ fn spending_changes(ui: &mut Ui, b: &Books, shell: &mut Shell<'_>) {
w - cw * 3.0 - 8.0,
);
// Flag a category already running well above its average.
let hot = *avg > Decimal::ZERO && *now > *avg * Decimal::new(125, 2);
let hot = *avg > Decimal::ZERO
&& Amount::checked_mul_rounded(*avg, Decimal::new(125, 2))
.is_some_and(|limit| *now > limit);
let vals = [(*now, hot), (*last, false), (*avg, false)];
for (i, (v, flag)) in vals.iter().enumerate() {
let x = r.right() - cw * (2 - i) as f32 - 4.0;
@@ -321,7 +328,7 @@ fn by_customer(ui: &mut Ui, b: &Books) {
.map(|c| c.name.clone())
.unwrap_or_default();
let sum = by.entry(who).or_default();
match inv.total().ok().and_then(|t| sum.checked_add(t)) {
match inv.total().ok().and_then(|t| Amount::checked_add(*sum, t)) {
Some(t) => *sum = t,
None => cant = Some(format!("invoice {id}'s total can't be computed exactly")),
}
@@ -371,7 +378,7 @@ fn by_customer(ui: &mut Ui, b: &Books) {
/// The sum of the customers' totals, None past exact arithmetic.
fn rows_total(by: &BTreeMap<String, Decimal>) -> Option<Decimal> {
by.values()
.try_fold(Decimal::ZERO, |t, v| t.checked_add(*v))
.try_fold(Decimal::ZERO, |t, v| Amount::checked_add(t, *v))
}
/// Each project's net income this year, a bar each; a bar opens its
@@ -398,7 +405,7 @@ fn by_class(ui: &mut Ui, b: &Books, go: &mut Option<Route>) {
.iter()
.filter_map(|c| {
let pl = profit_and_loss_for_period(&b.ledger, ys, ye, Some(c.id)).ok()?;
let net = pl.total_revenue - pl.total_expenses;
let net = sub_in_range(pl.total_revenue, pl.total_expenses);
(!pl.total_revenue.is_zero() || !pl.total_expenses.is_zero())
.then(|| (c.id, c.name.clone(), net))
})
+4 -2
View File
@@ -21,6 +21,8 @@ use crate::widgets;
use chrono::{Datelike, NaiveDate};
use egui::{RichText, Ui, vec2};
use egui_phosphor::regular as icon;
use ledger_core::kernel::Amount;
use ledger_core::money::neg;
use ledger_core::{ClassId, ProjectFacts, ProjectKind, ProjectStatus};
use rust_decimal::Decimal;
@@ -93,7 +95,7 @@ fn summary(rows: &[Listed]) -> String {
let net: Option<Decimal> = rows
.iter()
.map(|r| r.to_date.as_ref().map(|t| t.net()))
.try_fold(Decimal::ZERO, |t, n| t.checked_add(n?));
.try_fold(Decimal::ZERO, |t, n| Amount::checked_add(t, n?));
let counts = if parts.len() == 1 && rows.len() > 1 {
format!(
"{}, all {}",
@@ -953,7 +955,7 @@ fn accounts_card(
let amt = widgets::amount_col_w(ui.available_width(), 1, 160.0, 140.0);
let w = ui.available_width();
let mut line = |ui: &mut Ui, l: &ledger_core::StatementLine, expense: bool| {
let shown = if expense { -l.amount } else { l.amount };
let shown = if expense { neg(l.amount) } else { l.amount };
let resp = row(
ui,
w,
@@ -68,7 +68,7 @@ fn signed(b: &Books, account: AccountId, side: Side, amount: Decimal) -> Decimal
.chart()
.get(account)
.map_or(Side::Debit, |a| a.account_type.normal_side());
if side == normal { amount } else { -amount }
ledger_core::money::on_side(normal, side, amount)
}
/// Every posted line on the reconciliation's account dated on or before
@@ -168,7 +168,8 @@ pub fn show(ui: &mut Ui, b: &Books, id: u64, shell: &mut Shell<'_>) {
let all = lines(b, r);
let cleared: Vec<_> = all.iter().filter(|l| l.5).collect();
let outstanding: Vec<_> = all.iter().filter(|l| !l.5).collect();
let cleared_total: Decimal = cleared.iter().map(|l| l.4).sum();
let cleared_total: Decimal = ledger_core::kernel::total_of(cleared.iter(), |l| l.4)
.expect("figures drawn from the books are in range, so their sum is");
let st = b.statement(r.attachment_id);
super::columns(ui, 860.0, &[1.0, 1.0], |col, ui| {
if col == 0 {
+51 -28
View File
@@ -14,6 +14,8 @@ use chrono::{Datelike, Days, Months, NaiveDate};
use egui::{CornerRadius, RichText, Sense, Stroke, Ui, vec2};
use egui_phosphor::regular as icon;
use ledger_core::analysis::{Interval, intervals};
use ledger_core::kernel::Amount;
use ledger_core::money::{add_in_range, neg, sub_in_range};
use ledger_core::reports::{
balance_sheet_as_of, general_ledger, members_equity, profit_and_loss_for_period,
trial_balance_as_of,
@@ -237,9 +239,9 @@ impl Table {
}
let (a, b) = (r.cells[0].value, r.cells[1].value);
let diff = match (a, b) {
(Some(a), Some(b)) => Some(a - b),
(Some(a), Some(b)) => Some(sub_in_range(a, b)),
(Some(a), None) => Some(a),
(None, Some(b)) => Some(-b),
(None, Some(b)) => Some(neg(b)),
_ => None,
};
// No percent of a zero or negative base: it would mislead.
@@ -474,7 +476,7 @@ fn pnl(b: &Books, cols: &Cols, total: bool) -> Table {
.and_then(|st| pick(st).iter().find(|l| &l.code == code))
.map(|l| l.amount)
.unwrap_or_default();
totals[i] += v;
totals[i] = add_in_range(totals[i], v);
Cell {
value: Some(v),
drill: id.map(|account| Drill {
@@ -499,7 +501,10 @@ fn pnl(b: &Books, cols: &Cols, total: bool) -> Table {
t.row(
Kind::Grand,
"Net income",
rev.iter().zip(&exp).map(|(r, e)| Cell::of(r - e)).collect(),
rev.iter()
.zip(&exp)
.map(|(r, e)| Cell::of(sub_in_range(*r, *e)))
.collect(),
);
t
}
@@ -572,12 +577,12 @@ fn balance_sheet(b: &Books, dates: &[(NaiveDate, String)]) -> Table {
t.row(
Kind::Grand,
"Total liabilities and equity",
total(&|s| s.total_liabilities + s.total_equity),
total(&|s| add_in_range(s.total_liabilities, s.total_equity)),
);
if stmts
.iter()
.flatten()
.all(|s| s.total_assets == s.total_liabilities + s.total_equity)
.all(|s| s.total_assets == add_in_range(s.total_liabilities, s.total_equity))
{
t.note(format!(
"{} Assets equal liabilities plus equity in every column.",
@@ -656,12 +661,13 @@ fn cash_flow_table(b: &Books, cols: &Cols, total: bool) -> Table {
.iter()
.zip(&stmts)
.map(|((s, e, _), st)| Cell {
value: st.as_ref().ok().map(|st| {
rows(st)
.into_iter()
.filter(|r| r.0 == key)
.map(|r| r.2)
.sum()
// Blank where the statement was refused, or the sum can't be
// computed exactly.
value: st.as_ref().ok().and_then(|st| {
ledger_core::kernel::total_of(
rows(st).into_iter().filter(|r| r.0 == key),
|r| r.2,
)
}),
drill: id.map(|account| Drill {
account,
@@ -929,7 +935,9 @@ fn owners_equity(b: &Books, s: NaiveDate, e: NaiveDate) -> Table {
);
row(&mut t, Kind::Line, "Contributions", &|m| m.contributions);
row(&mut t, Kind::Line, "Share of net income", &|m| m.net_income);
row(&mut t, Kind::Line, "Distributions", &|m| -m.distributions);
row(&mut t, Kind::Line, "Distributions", &|m| {
neg(m.distributions)
});
row(&mut t, Kind::Line, "Other", &|m| m.other);
row(
&mut t,
@@ -939,7 +947,15 @@ fn owners_equity(b: &Books, s: NaiveDate, e: NaiveDate) -> Table {
);
let shares: Vec<String> = members
.iter()
.map(|m| format!("{} {}%", m.name, (m.share * Decimal::from(100)).normalize()))
.map(|m| {
format!(
"{} {}%",
m.name,
Amount::checked_mul_rounded(m.share, Decimal::from(100))
.expect("a member's share is at most one, so a hundred times it fits")
.normalize()
)
})
.collect();
t.note(format!("Ownership: {}.", shares.join(", ")));
return t;
@@ -953,8 +969,8 @@ fn owners_equity(b: &Books, s: NaiveDate, e: NaiveDate) -> Table {
// Nothing is dated before chrono's first day: nothing to begin with.
let begin = s.pred_opt().map_or(Decimal::ZERO, |d| b.balance_on(a, d));
let end = b.balance_on(a, e);
tb += begin;
te += end;
tb = add_in_range(tb, begin);
te = add_in_range(te, end);
let d = Some(Drill {
account: a,
start: s,
@@ -966,7 +982,7 @@ fn owners_equity(b: &Books, s: NaiveDate, e: NaiveDate) -> Table {
vec![
Cell::of(begin),
Cell {
value: Some(end - begin),
value: Some(sub_in_range(end, begin)),
drill: d,
},
Cell::of(end),
@@ -986,7 +1002,7 @@ fn owners_equity(b: &Books, s: NaiveDate, e: NaiveDate) -> Table {
"Net income not yet closed",
vec![
Cell::of(ni_begin),
Cell::of(ni_end - ni_begin),
Cell::of(sub_in_range(ni_end, ni_begin)),
Cell::of(ni_end),
],
);
@@ -994,9 +1010,12 @@ fn owners_equity(b: &Books, s: NaiveDate, e: NaiveDate) -> Table {
Kind::Grand,
"Total equity",
vec![
Cell::of(tb + ni_begin),
Cell::of(te + ni_end - tb - ni_begin),
Cell::of(te + ni_end),
Cell::of(add_in_range(tb, ni_begin)),
Cell::of(sub_in_range(
sub_in_range(add_in_range(te, ni_end), tb),
ni_begin,
)),
Cell::of(add_in_range(te, ni_end)),
],
);
t
@@ -1130,7 +1149,7 @@ fn aging(
total,
];
for (i, x) in v.iter().enumerate() {
match tot[i].checked_add(*x) {
match Amount::checked_add(tot[i], *x) {
Some(sum) => tot[i] = sum,
None => return cant_compute(t, &too_large()),
}
@@ -1310,7 +1329,7 @@ fn asset_register(b: &Books, as_of: NaiveDate) -> Table {
value: Some(r.ledger_accumulated),
drill: accum_drill,
},
Cell::of(r.ledger_cost - r.ledger_accumulated),
Cell::of(sub_in_range(r.ledger_cost, r.ledger_accumulated)),
Cell {
value: Some(r.ledger_accumulated),
drill: accum_drill,
@@ -1324,9 +1343,12 @@ fn asset_register(b: &Books, as_of: NaiveDate) -> Table {
Kind::Subtotal,
"Register less books",
vec![
Cell::of(-r.unregistered_cost()),
Cell::of(-r.unattributed_accumulated()),
Cell::of(r.total_book_value - (r.ledger_cost - r.ledger_accumulated)),
Cell::of(neg(r.unregistered_cost())),
Cell::of(neg(r.unattributed_accumulated())),
Cell::of(sub_in_range(
r.total_book_value,
sub_in_range(r.ledger_cost, r.ledger_accumulated),
)),
Cell::of(r.unposted_depreciation()),
Cell::none(),
Cell::none(),
@@ -2129,8 +2151,9 @@ fn gl(ui: &mut Ui, b: &Books, s: NaiveDate, e: NaiveDate, shell: &mut Shell<'_>)
// Narrow, the description gives way down to 120 points, then
// the table scrolls sideways.
let fixed = [86.0, 52.0, 0.0, 110.0, 110.0, 120.0];
let w = ui.available_width().max(fixed.iter().sum::<f32>() + 120.0);
let flex = w - fixed.iter().sum::<f32>();
let fixed_total = fixed.iter().fold(0.0_f32, |a, b| a + *b);
let w = ui.available_width().max(fixed_total + 120.0);
let flex = w - fixed_total;
widgets::min_width(ui, &format!("gl_{}", a.code), w, |ui| {
let row = |ui: &mut Ui,
vals: [String; 6],