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:
1 parent
0de906e9ed
commit
e4c41ccb3f
16 files changed
+244
-151
No files matched your search
@@ -6,6 +6,8 @@
|
||||
use chrono::{Datelike, NaiveDate};
|
||||
use ledger_config::BooksSettings;
|
||||
use ledger_core::analysis::{balance_history, balance_series};
|
||||
use ledger_core::kernel::{Amount, share_of, total_of};
|
||||
use ledger_core::money::{add_in_range, signed_amount, sub_in_range};
|
||||
use ledger_core::reports::{balance_sheet_as_of, profit_and_loss_for_period};
|
||||
use ledger_core::{
|
||||
AccountId, AccountType, AssetId, AssetRegister, AssetStatus, BillId, EntryId, EntryStatus,
|
||||
@@ -139,7 +141,11 @@ impl AssetTrail {
|
||||
/// effect, and what its disposal trued up (so a disposed asset's is
|
||||
/// what the disposal took, ledger_store's dispose_preview).
|
||||
pub fn posted(&self) -> Decimal {
|
||||
self.depreciation.values().map(|(_, a)| *a).sum::<Decimal>() + self.disposal_true_up
|
||||
add_in_range(
|
||||
total_of(self.depreciation.values(), |(_, a)| *a)
|
||||
.expect("an asset's posted runs are in range, so their sum is"),
|
||||
self.disposal_true_up,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -389,7 +395,7 @@ pub struct PartyFlow {
|
||||
impl PartyFlow {
|
||||
/// Paid out less received in.
|
||||
pub fn net(&self) -> Decimal {
|
||||
self.paid - self.received
|
||||
sub_in_range(self.paid, self.received)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -717,8 +723,8 @@ impl Books {
|
||||
.iter()
|
||||
.filter(|l| cash_accounts.contains(&l.account))
|
||||
.try_fold(Decimal::ZERO, |sum, l| match l.side {
|
||||
Side::Debit => sum.checked_add(l.amount.amount),
|
||||
Side::Credit => sum.checked_sub(l.amount.amount),
|
||||
Side::Debit => Amount::checked_add(sum, l.amount.amount),
|
||||
Side::Credit => Amount::checked_sub(sum, l.amount.amount),
|
||||
});
|
||||
// Core tags every entry with its counterparty (hand tags,
|
||||
// vendor tags, bills, invoices, their payments, reversals).
|
||||
@@ -953,14 +959,16 @@ impl Books {
|
||||
&[today - chrono::Days::new(30), today],
|
||||
);
|
||||
let bs = balance_sheet_as_of(l, today).ok();
|
||||
let receivables: Decimal = l
|
||||
.chart()
|
||||
.all()
|
||||
.filter(|a| {
|
||||
a.account_type == AccountType::Asset && a.name.to_lowercase().contains("receivable")
|
||||
})
|
||||
.map(|a| self.balance_on(a.id, today))
|
||||
.sum();
|
||||
let receivables: Decimal = ledger_core::kernel::total(
|
||||
l.chart()
|
||||
.all()
|
||||
.filter(|a| {
|
||||
a.account_type == AccountType::Asset
|
||||
&& a.name.to_lowercase().contains("receivable")
|
||||
})
|
||||
.map(|a| self.balance_on(a.id, today)),
|
||||
)
|
||||
.expect("figures drawn from the books are in range, so their sum is");
|
||||
let ms = self.month_start();
|
||||
let prev_start = ms - chrono::Months::new(1);
|
||||
let prev_end = ms - chrono::Days::new(1);
|
||||
@@ -981,7 +989,7 @@ impl Books {
|
||||
let first_entry = posted().min();
|
||||
let last_entry = posted().max();
|
||||
let monthly_burn = three.and_then(|p| {
|
||||
let loss = p.total_expenses - p.total_revenue;
|
||||
let loss = sub_in_range(p.total_expenses, p.total_revenue);
|
||||
// Only months the books cover count toward the average.
|
||||
let months = match first_entry {
|
||||
Some(f) if f > ms - chrono::Months::new(3) => {
|
||||
@@ -994,7 +1002,9 @@ impl Books {
|
||||
None => 0,
|
||||
};
|
||||
(loss > Decimal::ZERO && months > 0)
|
||||
.then(|| crate::fmt::round_display(loss / Decimal::from(months), 2))
|
||||
.then(|| Amount::checked_div(loss, Decimal::from(months)))
|
||||
.flatten()
|
||||
.map(|avg| crate::fmt::round_display(avg, 2))
|
||||
});
|
||||
Kpis {
|
||||
cash: cash[1],
|
||||
@@ -1006,7 +1016,7 @@ impl Books {
|
||||
revenue_prev_month: prev.as_ref().map(|p| p.total_revenue).unwrap_or_default(),
|
||||
expenses_prev_month: prev.as_ref().map(|p| p.total_expenses).unwrap_or_default(),
|
||||
net_ytd: ytd
|
||||
.map(|p| p.total_revenue - p.total_expenses)
|
||||
.map(|p| sub_in_range(p.total_revenue, p.total_expenses))
|
||||
.unwrap_or_default(),
|
||||
monthly_burn,
|
||||
first_entry,
|
||||
@@ -1105,7 +1115,7 @@ impl Books {
|
||||
let in_year = |d: NaiveDate| d.year() == year;
|
||||
// A sum that can't be computed exactly stays None (INVARIANT 4a).
|
||||
let add = |sum: &mut Option<Decimal>, v: Result<Decimal, LedgerError>| {
|
||||
*sum = sum.and_then(|s| s.checked_add(v.ok()?));
|
||||
*sum = sum.and_then(|s| Amount::checked_add(s, v.ok()?));
|
||||
};
|
||||
let mut out: BTreeMap<PartyId, PartyInfo> = l
|
||||
.parties()
|
||||
@@ -1131,7 +1141,7 @@ impl Books {
|
||||
.filter(|e| a.entries.contains(&e.id))
|
||||
.map(|e| e.id)
|
||||
.collect();
|
||||
info.paid_ytd = a.paid - a.received;
|
||||
info.paid_ytd = sub_in_range(a.paid, a.received);
|
||||
}
|
||||
for inv in l.invoices() {
|
||||
let id = inv.id;
|
||||
@@ -1661,7 +1671,8 @@ impl Books {
|
||||
continue;
|
||||
}
|
||||
for (account, amount) in self.party_what_for(e, party) {
|
||||
*by.entry(account).or_default() += amount;
|
||||
let slot = by.entry(account).or_default();
|
||||
*slot = add_in_range(*slot, amount);
|
||||
}
|
||||
}
|
||||
what_for = by.into_iter().filter(|(_, v)| !v.is_zero()).collect();
|
||||
@@ -1805,14 +1816,14 @@ impl Books {
|
||||
let Some(target) = info
|
||||
.parties
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |t, p| t.checked_add(p.resolved?))
|
||||
.try_fold(Decimal::ZERO, |t, p| Amount::checked_add(t, p.resolved?))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let fraction = if info.parties.len() <= 1 {
|
||||
Decimal::ONE
|
||||
} else {
|
||||
match resolved.checked_div(target) {
|
||||
match Amount::checked_div(resolved, target) {
|
||||
Some(f) => f,
|
||||
None => return Vec::new(),
|
||||
}
|
||||
@@ -1837,7 +1848,8 @@ impl Books {
|
||||
if me.is_some_and(|m| m.capital == a || m.distributions == Some(a)) {
|
||||
own.push((a, v));
|
||||
} else if !several || !member_line(a) {
|
||||
let Some(part) = v.checked_mul(fraction) else {
|
||||
// `fraction` is a quotient, so this product is a rounded figure by construction.
|
||||
let Some(part) = Amount::checked_mul_rounded(v, fraction) else {
|
||||
return Vec::new();
|
||||
};
|
||||
scaled.push((a, truncate_cents(part)));
|
||||
@@ -1846,14 +1858,14 @@ impl Books {
|
||||
let Some(left) = own
|
||||
.iter()
|
||||
.chain(&scaled)
|
||||
.try_fold(Decimal::ZERO, |t, (_, v)| t.checked_add(*v))
|
||||
.and_then(|have| cash.checked_sub(have))
|
||||
.try_fold(Decimal::ZERO, |t, (_, v)| Amount::checked_add(t, *v))
|
||||
.and_then(|have| Amount::checked_sub(cash, have))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !left.is_zero() {
|
||||
match scaled.first_mut().or(own.first_mut()) {
|
||||
Some(first) => first.1 += left,
|
||||
Some(first) => first.1 = add_in_range(first.1, left),
|
||||
None => own.push((e.lines()[0].account, left)),
|
||||
}
|
||||
}
|
||||
@@ -1923,10 +1935,9 @@ impl Books {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let due_to_members: Decimal = due_accounts
|
||||
.iter()
|
||||
.map(|&a| self.balance_on(a, span.1))
|
||||
.sum();
|
||||
let due_to_members: Decimal =
|
||||
total_of(due_accounts.iter(), |&a| self.balance_on(a, span.1))
|
||||
.expect("figures drawn from the books are in range, so their sum is");
|
||||
let shares: Vec<Decimal> = members.iter().map(|x| x.share).collect();
|
||||
let owed_to_member = ledger_core::periods::allocate_cumulative(
|
||||
due_to_members,
|
||||
@@ -2084,15 +2095,15 @@ pub fn share_of_what_for(
|
||||
.what_for
|
||||
.iter()
|
||||
.map(|(a, v)| {
|
||||
let part = v.checked_mul(share)?.checked_div(flow.net)?;
|
||||
let part = share_of(*v, share, flow.net)?;
|
||||
Some((*a, truncate_cents(part)))
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
let have = parts
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |t, (_, v)| t.checked_add(*v))?;
|
||||
let left = share.checked_sub(have)?;
|
||||
parts[0].1 = parts[0].1.checked_add(left)?;
|
||||
.try_fold(Decimal::ZERO, |t, (_, v)| Amount::checked_add(t, *v))?;
|
||||
let left = Amount::checked_sub(share, have)?;
|
||||
parts[0].1 = Amount::checked_add(parts[0].1, left)?;
|
||||
Some(parts)
|
||||
}
|
||||
|
||||
@@ -2156,7 +2167,8 @@ fn asset_trails(ledger: &Ledger, journal: &[JournalLine]) -> HashMap<AssetId, As
|
||||
ledger.get_asset(*id),
|
||||
t.disposal_entry.and_then(|e| ledger.get_entry(e)),
|
||||
) {
|
||||
let runs: Decimal = t.depreciation.values().map(|(_, a)| *a).sum();
|
||||
let runs: Decimal = total_of(t.depreciation.values(), |(_, a)| *a)
|
||||
.expect("an asset's posted runs are in range, so their sum is");
|
||||
let gain_loss = gain_loss_accounts.get(id).copied().flatten();
|
||||
t.disposal_true_up = disposal_true_up(a, e, gain_loss, runs);
|
||||
}
|
||||
@@ -2225,18 +2237,17 @@ fn disposal_true_up(
|
||||
runs: Decimal,
|
||||
) -> Decimal {
|
||||
if gain_loss_account.is_some_and(|g| g != asset.expense_account) {
|
||||
return entry
|
||||
.lines()
|
||||
.iter()
|
||||
.filter(|l| l.account == asset.expense_account)
|
||||
.map(|l| match l.side {
|
||||
Side::Debit => l.amount.amount,
|
||||
Side::Credit => -l.amount.amount,
|
||||
})
|
||||
.sum();
|
||||
return total_of(
|
||||
entry
|
||||
.lines()
|
||||
.iter()
|
||||
.filter(|l| l.account == asset.expense_account),
|
||||
|l| signed_amount(l.side, l.amount.amount),
|
||||
)
|
||||
.expect("a posted entry's lines are in range, so their sum is");
|
||||
}
|
||||
ledger_core::accumulated_scheduled_through(asset, NaiveDate::MAX)
|
||||
.map_or(Decimal::ZERO, |t| t - runs)
|
||||
.map_or(Decimal::ZERO, |t| sub_in_range(t, runs))
|
||||
}
|
||||
|
||||
/// What a document's state ([`Books::doc_today`]) says it owes, read once
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
//! attention" list. Deterministic for a given `today`.
|
||||
|
||||
use chrono::{Datelike, Days, Months, NaiveDate};
|
||||
use ledger_core::kernel::Amount;
|
||||
use ledger_core::money::{add_in_range, sub_in_range};
|
||||
use ledger_core::{
|
||||
AccountType, CloseTo, Currency, Dated1099, Decision1099, Form1099, Frequency, InstrumentKind,
|
||||
Money, NewAsset, NewRecurring, NewSchedule, ScheduleKind, Side, arap::DocumentLine,
|
||||
@@ -61,6 +63,15 @@ fn usd(d: Decimal) -> Money {
|
||||
Money::new(d, Currency::USD)
|
||||
}
|
||||
|
||||
/// `amount` to the nearest whole `step`, a half to the even multiple.
|
||||
fn to_step(amount: Decimal, step: Decimal) -> Decimal {
|
||||
use ledger_core::kernel::{Rounding, round_places};
|
||||
let steps = Amount::checked_div(amount, step)
|
||||
.and_then(|q| round_places(q, 0, Rounding::HalfToEven))
|
||||
.expect("a demo amount over a whole step rounds");
|
||||
Amount::checked_mul(steps, step).expect("a whole number of steps fits")
|
||||
}
|
||||
|
||||
fn dec(n: i64) -> Decimal {
|
||||
Decimal::from(n)
|
||||
}
|
||||
@@ -608,7 +619,7 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> {
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
card_balance += amt;
|
||||
card_balance = add_in_range(card_balance, amt);
|
||||
}
|
||||
// Advertising some months.
|
||||
if month_index % 3 == 1 {
|
||||
@@ -629,7 +640,7 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> {
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
card_balance += amt;
|
||||
card_balance = add_in_range(card_balance, amt);
|
||||
}
|
||||
}
|
||||
// Meals and supplies.
|
||||
@@ -659,7 +670,7 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> {
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
card_balance += amt;
|
||||
card_balance = add_in_range(card_balance, amt);
|
||||
}
|
||||
if month_index % 4 == 2 {
|
||||
let date = day(m, 21);
|
||||
@@ -685,13 +696,13 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> {
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
card_balance += amt;
|
||||
card_balance = add_in_range(card_balance, amt);
|
||||
}
|
||||
}
|
||||
if month_index == 7 {
|
||||
let date = day(m, 9);
|
||||
if in_range(date) {
|
||||
let amt = dec(1186) + rng.amount(0, 90);
|
||||
let amt = add_in_range(dec(1186), rng.amount(0, 90));
|
||||
post(
|
||||
&mut s,
|
||||
date,
|
||||
@@ -712,7 +723,7 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> {
|
||||
None,
|
||||
None,
|
||||
)?;
|
||||
card_balance += amt;
|
||||
card_balance = add_in_range(card_balance, amt);
|
||||
}
|
||||
}
|
||||
// Pay the card in full on the 25th.
|
||||
@@ -748,7 +759,7 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> {
|
||||
continue;
|
||||
}
|
||||
let cust = customers[rng.pick(customers.len() as u64) as usize];
|
||||
let amt = (rng.amount(1800, 7800) / dec(50)).round() * dec(50);
|
||||
let amt = to_step(rng.amount(1800, 7800), dec(50));
|
||||
let inv = s.create_invoice(
|
||||
cust,
|
||||
date,
|
||||
@@ -791,14 +802,17 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> {
|
||||
// A booked figure, so the kernel's rounding and not the
|
||||
// display's: ten percent to the cent, a half to the even
|
||||
// cent, as these books have always been drawn.
|
||||
let fee = ledger_core::kernel::round_places(
|
||||
gross * Decimal::new(10, 2),
|
||||
2,
|
||||
ledger_core::kernel::Rounding::HalfToEven,
|
||||
)
|
||||
.expect("a tenth of a four-digit sale rounds to the cent")
|
||||
+ Decimal::new(30, 2);
|
||||
let net = gross - fee;
|
||||
let fee = add_in_range(
|
||||
ledger_core::kernel::round_places(
|
||||
Amount::checked_mul(gross, Decimal::new(10, 2))
|
||||
.expect("a tenth of a four-digit sale fits"),
|
||||
2,
|
||||
ledger_core::kernel::Rounding::HalfToEven,
|
||||
)
|
||||
.expect("a tenth of a four-digit sale rounds to the cent"),
|
||||
Decimal::new(30, 2),
|
||||
);
|
||||
let net = sub_in_range(gross, fee);
|
||||
let e = s.create_entry(date, "Gumroad payout — template sales")?;
|
||||
s.add_line(e, checking, Side::Debit, usd(net))?;
|
||||
s.add_line(e, fees, Side::Debit, usd(fee))?;
|
||||
@@ -830,7 +844,7 @@ pub fn build(dir: &Path, today: NaiveDate) -> Result<(), StoreError> {
|
||||
if month_index % 2 == 0 && month_index > 0 {
|
||||
let date = day(m, 28);
|
||||
if in_range(date) {
|
||||
let amt = (rng.amount(900, 2200) / dec(25)).round() * dec(25);
|
||||
let amt = to_step(rng.amount(900, 2200), dec(25));
|
||||
post(
|
||||
&mut s,
|
||||
date,
|
||||
|
||||
@@ -71,7 +71,7 @@ pub use ledger_import::format::round_display;
|
||||
pub fn compact(d: Decimal) -> String {
|
||||
let a = d.abs();
|
||||
let scaled = |divisor: Decimal, places: u32| {
|
||||
a.checked_div(divisor)
|
||||
ledger_core::kernel::Amount::checked_div(a, divisor)
|
||||
.map(|v| round_display(v, places))
|
||||
.unwrap_or(a)
|
||||
};
|
||||
@@ -142,7 +142,7 @@ pub fn plain(display: &str) -> Option<String> {
|
||||
/// honest percent (the one rule every percent in the viewer follows;
|
||||
/// the caller shows nothing, or "—", for `None`).
|
||||
pub fn pct_change(prev: Decimal, now: Decimal) -> Option<Decimal> {
|
||||
let part = now.checked_sub(prev)?;
|
||||
let part = ledger_core::kernel::Amount::checked_sub(now, prev)?;
|
||||
let mut x = ledger_core::kernel::percent_of(
|
||||
part,
|
||||
prev,
|
||||
@@ -150,7 +150,7 @@ pub fn pct_change(prev: Decimal, now: Decimal) -> Option<Decimal> {
|
||||
ledger_core::kernel::Rounding::HalfAwayFromZero,
|
||||
)?;
|
||||
// One place always, so no change prints "0.0", never "0" or "-0.0".
|
||||
x.rescale(1);
|
||||
x = ledger_core::kernel::rescale_exact(x, 1).unwrap_or(x);
|
||||
Some(x)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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()?,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -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())));
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)),
|
||||
),
|
||||
|
||||
@@ -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,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))
|
||||
})
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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],
|
||||
|
||||
Reference in new issue
Block a user