refactor(mcp): Decimal arithmetic goes through the kernel (K-U12)
The raw-decimal-arith detector counted 19 places in ledger-mcp before and counts 0 after. No figure changes. Sides become signs through money::on_side and money::signed_amount (server delta, report movement, the P&L-by-class normal-side figure, which collapses two matches into one call); sums and differences of books figures through add_in_range and sub_in_range; the checked sums in helpers and documents through Amount::checked_add with their error handling untouched. The count of withdrawn attachments (a usize, not a Decimal) is the length of the flattened withdraw lists instead of an Iterator::sum of their lengths: the same number. Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
5ef5f47ebf
commit
1d612d25b8
7 files changed
+34
-36
No files matched your search
@@ -1343,11 +1343,7 @@ fn preview_lines_for(
|
|||||||
.account_balance(*account_id)
|
.account_balance(*account_id)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
let normal = account.account_type.normal_side();
|
let normal = account.account_type.normal_side();
|
||||||
let delta = if *side == normal {
|
let delta = ledger_core::money::on_side(normal, *side, amount.amount);
|
||||||
amount.amount
|
|
||||||
} else {
|
|
||||||
-amount.amount
|
|
||||||
};
|
|
||||||
let after =
|
let after =
|
||||||
ledger_core::money::add_exact(before, delta, "the account's balance after the line")
|
ledger_core::money::add_exact(before, delta, "the account's balance after the line")
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|||||||
@@ -150,7 +150,7 @@ fn basis_out(a: &ledger_core::Asset) -> Result<Option<AssetBasisOut>, String> {
|
|||||||
sec704c_1c_note: loss.map(|l| {
|
sec704c_1c_note: loss.map(|l| {
|
||||||
format!(
|
format!(
|
||||||
"a built-in loss of {}: it counts only for the contributing member(s); for the others the basis is treated as the value at contribution (IRC §704(c)(1)(C))",
|
"a built-in loss of {}: it counts only for the contributing member(s); for the others the basis is treated as the value at contribution (IRC §704(c)(1)(C))",
|
||||||
money(-l)
|
money(ledger_core::money::neg(l))
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
sec704c_method: b.sec704c_method.map(|m| m.key().to_string()),
|
sec704c_method: b.sec704c_method.map(|m| m.key().to_string()),
|
||||||
@@ -748,7 +748,10 @@ impl BooksServer {
|
|||||||
accumulated_posted: figure(|r| r.accumulated_posted),
|
accumulated_posted: figure(|r| r.accumulated_posted),
|
||||||
accumulated_scheduled_through: figure(|r| r.accumulated_scheduled),
|
accumulated_scheduled_through: figure(|r| r.accumulated_scheduled),
|
||||||
unposted_depreciation: figure(|r| {
|
unposted_depreciation: figure(|r| {
|
||||||
r.accumulated_scheduled - r.accumulated_posted
|
ledger_core::money::sub_in_range(
|
||||||
|
r.accumulated_scheduled,
|
||||||
|
r.accumulated_posted,
|
||||||
|
)
|
||||||
}),
|
}),
|
||||||
book_value: figure(|r| r.book_value),
|
book_value: figure(|r| r.book_value),
|
||||||
schedule_error,
|
schedule_error,
|
||||||
@@ -930,7 +933,7 @@ impl BooksServer {
|
|||||||
proceeds.amount,
|
proceeds.amount,
|
||||||
preview.catch_up_depreciation,
|
preview.catch_up_depreciation,
|
||||||
if preview.gain_loss < Decimal::ZERO {
|
if preview.gain_loss < Decimal::ZERO {
|
||||||
-preview.gain_loss
|
ledger_core::money::neg(preview.gain_loss)
|
||||||
} else {
|
} else {
|
||||||
Decimal::ZERO
|
Decimal::ZERO
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use ledger_core::Terms;
|
use ledger_core::Terms;
|
||||||
use ledger_core::arap::{self, PartySnapshot};
|
use ledger_core::arap::{self, PartySnapshot};
|
||||||
|
use ledger_core::kernel::Amount;
|
||||||
|
|
||||||
/// A document's id.
|
/// A document's id.
|
||||||
fn doc_id(doc: ledger_core::DocRef) -> u64 {
|
fn doc_id(doc: ledger_core::DocRef) -> u64 {
|
||||||
@@ -934,8 +935,7 @@ impl BooksServer {
|
|||||||
if !keep {
|
if !keep {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
owed = owed
|
owed = Amount::checked_add(owed, st.outstanding)
|
||||||
.checked_add(st.outstanding)
|
|
||||||
.ok_or("the total is too large to compute")?;
|
.ok_or("the total is too large to compute")?;
|
||||||
rows.push((
|
rows.push((
|
||||||
due,
|
due,
|
||||||
|
|||||||
@@ -330,7 +330,7 @@ impl BooksServer {
|
|||||||
links: g.link.iter().map(|s| subject_out(&store, *s)).collect(),
|
links: g.link.iter().map(|s| subject_out(&store, *s)).collect(),
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let withdrawn = out_groups.iter().map(|g| g.withdraw.len()).sum();
|
let withdrawn = out_groups.iter().flat_map(|g| g.withdraw.iter()).count();
|
||||||
let digest = self.preview_of(
|
let digest = self.preview_of(
|
||||||
&store,
|
&store,
|
||||||
"books.consolidate_duplicates",
|
"books.consolidate_duplicates",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use ledger_core::InstrumentId;
|
use ledger_core::InstrumentId;
|
||||||
|
use ledger_core::kernel::Amount;
|
||||||
use ledger_store::StoreError;
|
use ledger_store::StoreError;
|
||||||
|
|
||||||
/// The book's id, as the commands given to agents name it: its folder's
|
/// The book's id, as the commands given to agents name it: its folder's
|
||||||
@@ -462,7 +463,7 @@ pub(crate) fn checked_sum(
|
|||||||
) -> Result<Decimal, String> {
|
) -> Result<Decimal, String> {
|
||||||
values.into_iter().try_fold(Decimal::ZERO, |sum, v| {
|
values.into_iter().try_fold(Decimal::ZERO, |sum, v| {
|
||||||
let v = v.map_err(|e| e.to_string())?;
|
let v = v.map_err(|e| e.to_string())?;
|
||||||
sum.checked_add(v).ok_or_else(|| {
|
Amount::checked_add(sum, v).ok_or_else(|| {
|
||||||
ledger_core::LedgerError::TooLargeToCompute(what.to_string()).to_string()
|
ledger_core::LedgerError::TooLargeToCompute(what.to_string()).to_string()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -548,7 +549,9 @@ pub(crate) fn lines_settled(entry: &JournalEntry) -> bool {
|
|||||||
.lines()
|
.lines()
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|l| l.side == s)
|
.filter(|l| l.side == s)
|
||||||
.try_fold(Decimal::ZERO, |sum, l| sum.checked_add(l.amount.amount))
|
.try_fold(Decimal::ZERO, |sum, l| {
|
||||||
|
Amount::checked_add(sum, l.amount.amount)
|
||||||
|
})
|
||||||
};
|
};
|
||||||
match (side(Side::Debit), side(Side::Credit)) {
|
match (side(Side::Debit), side(Side::Credit)) {
|
||||||
(Some(debits), Some(credits)) => !entry.lines().is_empty() && debits == credits,
|
(Some(debits), Some(credits)) => !entry.lines().is_empty() && debits == credits,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
//! Split whole out of `server.rs` (plan/served.md 8.2 U0a).
|
//! Split whole out of `server.rs` (plan/served.md 8.2 U0a).
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use ledger_core::money::{add_in_range, sub_in_range};
|
||||||
|
|
||||||
/// What the digest lists from the control check: each line on a control
|
/// What the digest lists from the control check: each line on a control
|
||||||
/// account that is no document's, and each document needing attention.
|
/// account that is no document's, and each document needing attention.
|
||||||
@@ -37,18 +38,15 @@ fn movement_over(
|
|||||||
.iter()
|
.iter()
|
||||||
.flat_map(|e| e.lines())
|
.flat_map(|e| e.lines())
|
||||||
.filter(|l| l.account == account),
|
.filter(|l| l.account == account),
|
||||||
|l| match l.side {
|
|l| ledger_core::money::signed_amount(l.side, l.amount.amount),
|
||||||
Side::Debit => l.amount.amount,
|
|
||||||
Side::Credit => -l.amount.amount,
|
|
||||||
},
|
|
||||||
"an account's movement",
|
"an account's movement",
|
||||||
)
|
)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
let account = ledger.chart().get(account).expect("account exists");
|
let account = ledger.chart().get(account).expect("account exists");
|
||||||
Ok(match account.account_type.normal_side() {
|
Ok(ledger_core::money::signed_amount(
|
||||||
Side::Debit => movement,
|
account.account_type.normal_side(),
|
||||||
Side::Credit => -movement,
|
movement,
|
||||||
})
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lines_out(lines: &[ledger_core::StatementLine]) -> Vec<StatementLineOut> {
|
fn lines_out(lines: &[ledger_core::StatementLine]) -> Vec<StatementLineOut> {
|
||||||
@@ -1057,19 +1055,16 @@ impl BooksServer {
|
|||||||
Some(a) => a,
|
Some(a) => a,
|
||||||
_ => continue,
|
_ => continue,
|
||||||
};
|
};
|
||||||
let signed = match line.side {
|
|
||||||
Side::Debit => line.amount.amount,
|
|
||||||
Side::Credit => -line.amount.amount,
|
|
||||||
};
|
|
||||||
// Normal-side positive.
|
// Normal-side positive.
|
||||||
let normal = match account.account_type.normal_side() {
|
let normal = ledger_core::money::on_side(
|
||||||
Side::Debit => signed,
|
account.account_type.normal_side(),
|
||||||
Side::Credit => -signed,
|
line.side,
|
||||||
};
|
line.amount.amount,
|
||||||
|
);
|
||||||
let acc = by_class.entry(line.class_id).or_default();
|
let acc = by_class.entry(line.class_id).or_default();
|
||||||
match account.account_type {
|
match account.account_type {
|
||||||
AccountType::Revenue => acc.revenue += normal,
|
AccountType::Revenue => acc.revenue = add_in_range(acc.revenue, normal),
|
||||||
AccountType::Expense => acc.expenses += normal,
|
AccountType::Expense => acc.expenses = add_in_range(acc.expenses, normal),
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1099,7 +1094,7 @@ impl BooksServer {
|
|||||||
class,
|
class,
|
||||||
revenue: money(acc.revenue),
|
revenue: money(acc.revenue),
|
||||||
expenses: money(acc.expenses),
|
expenses: money(acc.expenses),
|
||||||
net_income: money(acc.revenue - acc.expenses),
|
net_income: money(sub_in_range(acc.revenue, acc.expenses)),
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
Ok(Json(ProfitAndLossByClassOut {
|
Ok(Json(ProfitAndLossByClassOut {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
//! there and this slice's do not collide (plan/served.md 8.2 P4b S6).
|
//! there and this slice's do not collide (plan/served.md 8.2 P4b S6).
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use ledger_core::money::{add_in_range, sub_in_range};
|
||||||
|
|
||||||
/// A document as the payment tools and the agings name it ("invoice:7",
|
/// A document as the payment tools and the agings name it ("invoice:7",
|
||||||
/// "bill:12").
|
/// "bill:12").
|
||||||
@@ -257,7 +258,7 @@ fn payment_out(
|
|||||||
let mut documents = Vec::with_capacity(params.applications.len());
|
let mut documents = Vec::with_capacity(params.applications.len());
|
||||||
let mut deposited = Decimal::ZERO;
|
let mut deposited = Decimal::ZERO;
|
||||||
for app in ¶ms.applications {
|
for app in ¶ms.applications {
|
||||||
deposited += app.cash;
|
deposited = add_in_range(deposited, app.cash);
|
||||||
let st = ledger
|
let st = ledger
|
||||||
.doc_state(app.doc, chrono::NaiveDate::MAX)
|
.doc_state(app.doc, chrono::NaiveDate::MAX)
|
||||||
.map_err(|e| e.to_string())?
|
.map_err(|e| e.to_string())?
|
||||||
@@ -270,7 +271,7 @@ fn payment_out(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
let fee = params.fee.as_ref().map_or(Decimal::ZERO, |f| f.amount);
|
let fee = params.fee.as_ref().map_or(Decimal::ZERO, |f| f.amount);
|
||||||
deposited -= fee;
|
deposited = sub_in_range(deposited, fee);
|
||||||
let (remaining, status) = match documents.as_slice() {
|
let (remaining, status) = match documents.as_slice() {
|
||||||
[one] => (Some(one.outstanding.clone()), Some(one.status.clone())),
|
[one] => (Some(one.outstanding.clone()), Some(one.status.clone())),
|
||||||
_ => (None, None),
|
_ => (None, None),
|
||||||
@@ -413,7 +414,7 @@ impl BooksServer {
|
|||||||
Some((by, max)) if by >= as_of => (
|
Some((by, max)) if by >= as_of => (
|
||||||
Some(by.to_string()),
|
Some(by.to_string()),
|
||||||
Some(money(max)),
|
Some(money(max)),
|
||||||
Some(money(st.outstanding - max)),
|
Some(money(sub_in_range(st.outstanding, max))),
|
||||||
),
|
),
|
||||||
_ => (None, None, None),
|
_ => (None, None, None),
|
||||||
};
|
};
|
||||||
@@ -438,7 +439,7 @@ impl BooksServer {
|
|||||||
let mut by_date = Vec::new();
|
let mut by_date = Vec::new();
|
||||||
let mut running = Decimal::ZERO;
|
let mut running = Decimal::ZERO;
|
||||||
for (bill, owed) in &bills {
|
for (bill, owed) in &bills {
|
||||||
running += owed;
|
running = add_in_range(running, *owed);
|
||||||
match by_date.last_mut() {
|
match by_date.last_mut() {
|
||||||
Some(DueDateTotalOut { date, amount }) if *date == bill.due_date => {
|
Some(DueDateTotalOut { date, amount }) if *date == bill.due_date => {
|
||||||
*amount = money(running);
|
*amount = money(running);
|
||||||
|
|||||||
Reference in new issue
Block a user