refactor(core): the bookspec adapter becomes modules by area
The bookspec adapter was one 4,647-line test file, and every later unit that adds a query or an event touches it. Split it by its own sections, with no behaviour change: `main` keeps the crate doc, the shared imports and the module list; `common` holds the shared vocabulary (dates, refusals, exact decimals, figure formatting); `books` the example's books and setup; `events` the application of each event; `queries/` the answers and checks per query family (statements, parties, tax, assets, formats, commands, dates); `engine` the `Engine` impl; `check` and `run` the drivers; and `examples`, `loader_tests`, `sources` and `rules_md` the tests by area. Every `#[test]` keeps its function name (52 tests, same names), and Cargo still builds one test target named `bookspec`. Co-Authored-By: DeepSeek V4.1 Flash <noreply@opencode.ai>
This commit is contained in:
1 parent
66d9b7ac54
commit
f9cdf4d718
24 files changed
+4764
-4663
No files matched your search
@@ -0,0 +1,481 @@
|
||||
use crate::*;
|
||||
|
||||
impl Books<'_> {
|
||||
pub(crate) fn answer_run(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let n = q.event.ok_or_else(|| self.missing("event"))?;
|
||||
let run = self.runs.get(&n).ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Asset, 1),
|
||||
format!("event {n} is no run_depreciation (or not yet run)"),
|
||||
)
|
||||
})?;
|
||||
let posted = if run.already_posted {
|
||||
Decimal::ZERO
|
||||
} else {
|
||||
run.amount
|
||||
};
|
||||
let caught_up = (posted - run.scheduled).max(Decimal::ZERO);
|
||||
Ok(json_figures([
|
||||
("amount".to_string(), figure(posted)),
|
||||
("caught_up".to_string(), figure(caught_up)),
|
||||
]))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_disposal(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let name = q.asset.as_deref().ok_or_else(|| self.missing("asset"))?;
|
||||
let p = self.disposals.get(name).ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Asset, 1),
|
||||
format!("asset {name:?} wasn't disposed of"),
|
||||
)
|
||||
})?;
|
||||
Ok(json_figures([
|
||||
(
|
||||
"final_depreciation".to_string(),
|
||||
figure(p.final_depreciation),
|
||||
),
|
||||
(
|
||||
"catch_up_depreciation".to_string(),
|
||||
figure(p.catch_up_depreciation),
|
||||
),
|
||||
(
|
||||
"excess_depreciation".to_string(),
|
||||
figure(p.excess_depreciation),
|
||||
),
|
||||
("accumulated".to_string(), figure(p.accumulated)),
|
||||
("book_value".to_string(), figure(p.book_value)),
|
||||
("gain_loss".to_string(), figure(p.gain_loss)),
|
||||
]))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_depreciation_schedule(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let as_of = self.q_day(q)?;
|
||||
let name = q.asset.as_deref().ok_or_else(|| self.missing("asset"))?;
|
||||
let asset = self
|
||||
.l()
|
||||
.get_asset(self.asset(name, name))
|
||||
.expect("a registered asset");
|
||||
let lines = ledger_core::depreciation_schedule(asset, as_of)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Asset, 1), e))?;
|
||||
let mut m = JsonMap::new();
|
||||
for l in &lines {
|
||||
m.insert(l.period.clone(), Value::String(figure(l.amount)));
|
||||
}
|
||||
// A month the schedule doesn't reach is 0.00: from acquisition
|
||||
// (never later than in-service) through the day asked as of.
|
||||
let start = self
|
||||
.l()
|
||||
.asset_acquired_date(asset.id)
|
||||
.unwrap_or(asset.in_service_date);
|
||||
let (mut year, mut month) = (start.year(), start.month());
|
||||
while (year, month) <= (as_of.year(), as_of.month()) {
|
||||
m.entry(format!("{year:04}-{month:02}"))
|
||||
.or_insert_with(|| Value::String("0.00".to_string()));
|
||||
if month == 12 {
|
||||
year += 1;
|
||||
month = 1;
|
||||
} else {
|
||||
month += 1;
|
||||
}
|
||||
}
|
||||
let accumulated = ledger_core::accumulated_scheduled_through(asset, as_of)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Asset, 1), e))?;
|
||||
let book_value = ledger_core::scheduled_book_value(asset, as_of)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Asset, 1), e))?;
|
||||
m.insert(
|
||||
"accumulated".to_string(),
|
||||
Value::String(figure(accumulated)),
|
||||
);
|
||||
m.insert("book_value".to_string(), Value::String(figure(book_value)));
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_schedule_plan(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let name = q
|
||||
.schedule
|
||||
.as_deref()
|
||||
.ok_or_else(|| self.missing("schedule"))?;
|
||||
let id = *self.schedules.get(name).ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Prepaid, 1),
|
||||
format!("no schedule {name:?}"),
|
||||
)
|
||||
})?;
|
||||
let plan = self
|
||||
.l()
|
||||
.get_schedule(id)
|
||||
.expect("a registered schedule")
|
||||
.plan()
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Prepaid, 1), e))?;
|
||||
let mut m = JsonMap::new();
|
||||
let mut total = Decimal::ZERO;
|
||||
for (d, amount) in &plan {
|
||||
m.insert(d.to_string(), Value::String(figure(*amount)));
|
||||
total += *amount;
|
||||
}
|
||||
m.insert("total".to_string(), Value::String(figure(total)));
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_register_row(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let as_of = self.q_day(q)?;
|
||||
let name = q.asset.as_deref().ok_or_else(|| self.missing("asset"))?;
|
||||
let id = self.asset(name, name);
|
||||
let r = ledger_core::fixed_asset_register(self.l(), as_of)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Asset, 3), e))?;
|
||||
let row = r
|
||||
.rows
|
||||
.iter()
|
||||
.find(|row| row.asset_id == id)
|
||||
.ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Asset, 3),
|
||||
"not on the register (acquired later)",
|
||||
)
|
||||
})?;
|
||||
Ok(json_figures([
|
||||
("acquired".to_string(), row.acquired_date.to_string()),
|
||||
("in_service".to_string(), row.in_service_date.to_string()),
|
||||
("cost".to_string(), figure(row.cost)),
|
||||
(
|
||||
"accumulated_scheduled".to_string(),
|
||||
figure(row.accumulated_scheduled),
|
||||
),
|
||||
(
|
||||
"accumulated_posted".to_string(),
|
||||
figure(row.accumulated_posted),
|
||||
),
|
||||
(
|
||||
"unposted".to_string(),
|
||||
figure(row.accumulated_scheduled - row.accumulated_posted),
|
||||
),
|
||||
("book_value".to_string(), figure(row.book_value)),
|
||||
]))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_register_totals(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let as_of = self.q_day(q)?;
|
||||
let r = ledger_core::fixed_asset_register(self.l(), as_of)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Asset, 3), e))?;
|
||||
Ok(json_figures([
|
||||
("total_cost".to_string(), figure(r.total_cost)),
|
||||
(
|
||||
"total_accumulated_scheduled".to_string(),
|
||||
figure(r.total_accumulated_scheduled),
|
||||
),
|
||||
(
|
||||
"total_accumulated_posted".to_string(),
|
||||
figure(r.total_accumulated_posted),
|
||||
),
|
||||
("total_book_value".to_string(), figure(r.total_book_value)),
|
||||
(
|
||||
"total_depreciable_basis".to_string(),
|
||||
figure(r.total_depreciable_basis),
|
||||
),
|
||||
(
|
||||
"total_tax_basis_723".to_string(),
|
||||
figure(r.total_tax_basis_723),
|
||||
),
|
||||
("missing_basis".to_string(), r.missing_basis.to_string()),
|
||||
(
|
||||
"unregistered_cost".to_string(),
|
||||
figure(r.unregistered_cost()),
|
||||
),
|
||||
(
|
||||
"unposted_depreciation".to_string(),
|
||||
figure(r.unposted_depreciation()),
|
||||
),
|
||||
(
|
||||
"unattributed_accumulated".to_string(),
|
||||
figure(r.unattributed_accumulated()),
|
||||
),
|
||||
]))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_asset_basis(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let name = q.asset.as_deref().ok_or_else(|| self.missing("asset"))?;
|
||||
let a = self
|
||||
.l()
|
||||
.get_asset(self.asset(name, name))
|
||||
.expect("a registered asset");
|
||||
let f = a
|
||||
.basis_figures()
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Asset, 4), e))?
|
||||
.ok_or_else(|| Refusal::new(RuleId::new(Area::Asset, 4), "no basis recorded"))?;
|
||||
let opt = |d: Option<Decimal>| d.map_or("none".to_string(), figure);
|
||||
let rule = a.basis.as_ref().expect("a basis recorded").rule;
|
||||
Ok(json_figures([
|
||||
("rule".to_string(), rule.key().to_string()),
|
||||
(
|
||||
"contributor_adjusted_basis".to_string(),
|
||||
opt(a.basis.as_ref().and_then(|b| b.contributor_adjusted_basis)),
|
||||
),
|
||||
(
|
||||
"fmv_at_contribution".to_string(),
|
||||
opt(a.fmv_at_contribution()),
|
||||
),
|
||||
("tax_basis_723".to_string(), opt(f.tax_basis_723)),
|
||||
("depreciable_basis".to_string(), figure(f.depreciable_basis)),
|
||||
("built_in_gain_704c".to_string(), opt(f.built_in_gain_704c)),
|
||||
("sec704c_1c".to_string(), a.sec704c_1c().to_string()),
|
||||
]))
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `run` expectation: what the `run_depreciation` event `event`
|
||||
/// posted (`amount`: zero when nothing was due, or the month already had
|
||||
/// its run) and, of it, what it caught up beyond its own month's
|
||||
/// depreciation (`caught_up`), both listed (rules.md B-15).
|
||||
pub(crate) fn check_run(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
undated(ex, x);
|
||||
let n = x
|
||||
.event
|
||||
.unwrap_or_else(|| panic!("{}: run names its event", ex.id));
|
||||
let run = b.runs.get(&n).unwrap_or_else(|| {
|
||||
panic!(
|
||||
"{}: event {n} is no run_depreciation (or not yet run)",
|
||||
ex.id
|
||||
)
|
||||
});
|
||||
let posted = if run.already_posted {
|
||||
Decimal::ZERO
|
||||
} else {
|
||||
run.amount
|
||||
};
|
||||
let caught_up = (posted - run.scheduled).max(Decimal::ZERO);
|
||||
exactly(
|
||||
ex,
|
||||
x,
|
||||
&["amount".to_string(), "caught_up".to_string()].into(),
|
||||
);
|
||||
for (key, got) in [("amount", posted), ("caught_up", caught_up)] {
|
||||
let want = exact(&x.figures(&ex.id)[key], &format!("{} {key}", ex.id));
|
||||
assert_eq!(got, want, "{} run of event {n}: {key}", ex.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `disposal` expectation: what the disposal of `asset` took, as
|
||||
/// the engine computed it when posting it (rules.md B-15), every figure
|
||||
/// listed: `final_depreciation` (posted in its own entry before the
|
||||
/// disposal), `catch_up_depreciation` and `excess_depreciation` (charged,
|
||||
/// and credited back, in the disposal entry), `accumulated` (cleared),
|
||||
/// `book_value` and `gain_loss` (a gain positive).
|
||||
pub(crate) fn check_disposal(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
undated(ex, x);
|
||||
let asset = x
|
||||
.asset
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| panic!("{}: disposal names its asset", ex.id));
|
||||
let p = b
|
||||
.disposals
|
||||
.get(asset)
|
||||
.unwrap_or_else(|| panic!("{}: asset {asset:?} wasn't disposed of", ex.id));
|
||||
let figures = [
|
||||
("final_depreciation", p.final_depreciation),
|
||||
("catch_up_depreciation", p.catch_up_depreciation),
|
||||
("excess_depreciation", p.excess_depreciation),
|
||||
("accumulated", p.accumulated),
|
||||
("book_value", p.book_value),
|
||||
("gain_loss", p.gain_loss),
|
||||
];
|
||||
exactly(ex, x, &figures.iter().map(|(k, _)| k.to_string()).collect());
|
||||
for (key, got) in figures {
|
||||
let want = exact(&x.figures(&ex.id)[key], &format!("{} {key}", ex.id));
|
||||
assert_eq!(got, want, "{} disposal of {asset}: {key}", ex.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `depreciation_schedule` expectation: the schedule of `asset`
|
||||
/// through `as_of` (rules.md B-15), each month named (`"YYYY-MM"`) its
|
||||
/// depreciation, 0.00 for a month the schedule doesn't reach;
|
||||
/// `accumulated` and `book_value` through `as_of`; the example names the
|
||||
/// figures it shows.
|
||||
pub(crate) fn check_depreciation_schedule(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
let as_of = day(ex, x);
|
||||
let name = x
|
||||
.asset
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| panic!("{}: depreciation_schedule names its asset", ex.id));
|
||||
let what = format!("{} depreciation_schedule of {name} through {as_of}", ex.id);
|
||||
let asset = b
|
||||
.l()
|
||||
.get_asset(b.asset(name, &what))
|
||||
.expect("a registered asset");
|
||||
let lines =
|
||||
ledger_core::depreciation_schedule(asset, as_of).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
for (key, want) in x.figures(&ex.id) {
|
||||
let want = exact(want, &format!("{what}: {key}"));
|
||||
let got = match key.as_str() {
|
||||
"accumulated" => ledger_core::accumulated_scheduled_through(asset, as_of),
|
||||
"book_value" => ledger_core::scheduled_book_value(asset, as_of),
|
||||
month => {
|
||||
month_key(month, &what);
|
||||
Ok(lines
|
||||
.iter()
|
||||
.find(|l| l.period == month)
|
||||
.map_or(Decimal::ZERO, |l| l.amount))
|
||||
}
|
||||
}
|
||||
.unwrap_or_else(|e| panic!("{what}: {key}: {e}"));
|
||||
assert_eq!(got, want, "{what}: {key}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `schedule_plan` expectation: what the schedule's plan
|
||||
/// recognizes at each month end named (`"YYYY-MM-DD"`, 0.00 at a month end
|
||||
/// the plan doesn't post), and `total`, all it recognizes (rules.md B-16);
|
||||
/// the example names the figures it shows.
|
||||
pub(crate) fn check_schedule_plan(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
undated(ex, x);
|
||||
let name = x
|
||||
.schedule
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| panic!("{}: schedule_plan names its schedule", ex.id));
|
||||
let what = format!("{} schedule_plan of {name}", ex.id);
|
||||
let id = *b
|
||||
.schedules
|
||||
.get(name)
|
||||
.unwrap_or_else(|| panic!("{what}: no schedule {name:?}"));
|
||||
let plan = b
|
||||
.l()
|
||||
.get_schedule(id)
|
||||
.expect("a registered schedule")
|
||||
.plan()
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
for (key, want) in x.figures(&ex.id) {
|
||||
let want = exact(want, &format!("{what}: {key}"));
|
||||
let got: Decimal = if key == "total" {
|
||||
plan.iter().map(|(_, a)| *a).sum()
|
||||
} else {
|
||||
let d = date(key, &what);
|
||||
assert_eq!(
|
||||
d,
|
||||
ledger_core::schedules::month_end(d),
|
||||
"{what}: {key} is no month end"
|
||||
);
|
||||
plan.iter().filter(|(m, _)| *m == d).map(|(_, a)| *a).sum()
|
||||
};
|
||||
assert_eq!(got, want, "{what}: {key}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `register_row` expectation: the asset's row of the fixed
|
||||
/// asset register as of `as_of` (rules.md B-15 rules 7 and 8, B-24):
|
||||
/// `acquired` and `in_service` (`YYYY-MM-DD`), `cost`,
|
||||
/// `accumulated_scheduled` (the schedule's), `accumulated_posted` (what
|
||||
/// the books carry), `unposted` (the one less the other), `book_value`
|
||||
/// (cost less posted); each 0.00 once disposed; the example names the
|
||||
/// figures it shows. An asset not on the register by `as_of` (acquired
|
||||
/// later) is refused.
|
||||
pub(crate) fn check_register_row(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
let as_of = day(ex, x);
|
||||
let name = x
|
||||
.asset
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| panic!("{}: register_row names its asset", ex.id));
|
||||
let what = format!("{} register_row of {name} as of {as_of}", ex.id);
|
||||
let id = b.asset(name, &what);
|
||||
let r =
|
||||
ledger_core::fixed_asset_register(b.l(), as_of).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let row = r
|
||||
.rows
|
||||
.iter()
|
||||
.find(|row| row.asset_id == id)
|
||||
.unwrap_or_else(|| panic!("{what}: not on the register (acquired later)"));
|
||||
let figures = BTreeMap::from([
|
||||
("acquired", row.acquired_date.to_string()),
|
||||
("in_service", row.in_service_date.to_string()),
|
||||
("cost", figure(row.cost)),
|
||||
("accumulated_scheduled", figure(row.accumulated_scheduled)),
|
||||
("accumulated_posted", figure(row.accumulated_posted)),
|
||||
(
|
||||
"unposted",
|
||||
figure(row.accumulated_scheduled - row.accumulated_posted),
|
||||
),
|
||||
("book_value", figure(row.book_value)),
|
||||
]);
|
||||
named(ex, x, &what, &figures);
|
||||
}
|
||||
|
||||
/// Check one `register_totals` expectation: the fixed asset register's
|
||||
/// totals as of `as_of`, over the assets held (rules.md B-24, B-25):
|
||||
/// `total_cost`, `total_accumulated_scheduled`, `total_accumulated_posted`,
|
||||
/// `total_book_value`, `total_depreciable_basis`, `total_tax_basis_723`,
|
||||
/// `missing_basis` (how many held have none), and how it reconciles to
|
||||
/// the books: `unregistered_cost`, `unposted_depreciation`,
|
||||
/// `unattributed_accumulated`; the example names the figures it shows.
|
||||
pub(crate) fn check_register_totals(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
let as_of = day(ex, x);
|
||||
let what = format!("{} register_totals as of {as_of}", ex.id);
|
||||
let r =
|
||||
ledger_core::fixed_asset_register(b.l(), as_of).unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||
let figures = BTreeMap::from([
|
||||
("total_cost", figure(r.total_cost)),
|
||||
(
|
||||
"total_accumulated_scheduled",
|
||||
figure(r.total_accumulated_scheduled),
|
||||
),
|
||||
(
|
||||
"total_accumulated_posted",
|
||||
figure(r.total_accumulated_posted),
|
||||
),
|
||||
("total_book_value", figure(r.total_book_value)),
|
||||
("total_depreciable_basis", figure(r.total_depreciable_basis)),
|
||||
("total_tax_basis_723", figure(r.total_tax_basis_723)),
|
||||
("missing_basis", r.missing_basis.to_string()),
|
||||
("unregistered_cost", figure(r.unregistered_cost())),
|
||||
("unposted_depreciation", figure(r.unposted_depreciation())),
|
||||
(
|
||||
"unattributed_accumulated",
|
||||
figure(r.unattributed_accumulated()),
|
||||
),
|
||||
]);
|
||||
named(ex, x, &what, &figures);
|
||||
}
|
||||
|
||||
/// Check one `asset_basis` expectation: the asset's basis facts and the
|
||||
/// tax figures they give (rules.md B-25): `rule`,
|
||||
/// `contributor_adjusted_basis`, `fmv_at_contribution`, `tax_basis_723`,
|
||||
/// `depreciable_basis`, `built_in_gain_704c` (a loss negative), each
|
||||
/// `"none"` where the asset has none (a purchase's §723 basis), and
|
||||
/// `sec704c_1c` (`"true"`: a built-in loss, which counts only for the
|
||||
/// contributing member, IRC §704(c)(1)(C)); the example names the figures
|
||||
/// it shows.
|
||||
pub(crate) fn check_asset_basis(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
undated(ex, x);
|
||||
let name = x
|
||||
.asset
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| panic!("{}: asset_basis names its asset", ex.id));
|
||||
let what = format!("{} asset_basis of {name}", ex.id);
|
||||
let a = b
|
||||
.l()
|
||||
.get_asset(b.asset(name, &what))
|
||||
.expect("a registered asset");
|
||||
let f = a
|
||||
.basis_figures()
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"))
|
||||
.unwrap_or_else(|| panic!("{what}: no basis recorded"));
|
||||
let opt = |d: Option<Decimal>| d.map_or("none".to_string(), figure);
|
||||
let rule = a.basis.as_ref().expect("a basis recorded").rule;
|
||||
let figures = BTreeMap::from([
|
||||
("rule", rule.key().to_string()),
|
||||
(
|
||||
"contributor_adjusted_basis",
|
||||
opt(a.basis.as_ref().and_then(|b| b.contributor_adjusted_basis)),
|
||||
),
|
||||
("fmv_at_contribution", opt(a.fmv_at_contribution())),
|
||||
("tax_basis_723", opt(f.tax_basis_723)),
|
||||
("depreciable_basis", figure(f.depreciable_basis)),
|
||||
("built_in_gain_704c", opt(f.built_in_gain_704c)),
|
||||
("sec704c_1c", a.sec704c_1c().to_string()),
|
||||
]);
|
||||
named(ex, x, &what, &figures);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
use crate::*;
|
||||
|
||||
impl Books<'_> {
|
||||
pub(crate) fn answer_command(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let ex = &self.ex;
|
||||
let mut copy = self.l().clone();
|
||||
let result: Result<(), LedgerError> = match q.name.as_str() {
|
||||
"rename_account" => {
|
||||
let code = q.code.as_deref().ok_or_else(|| self.missing("account"))?;
|
||||
let name = q.new_name.as_deref().ok_or_else(|| self.missing("name"))?;
|
||||
let account = self.account_or_refuse(code)?;
|
||||
copy.rename_account(account, name)
|
||||
}
|
||||
"add_account" => {
|
||||
let a = q.account.as_ref().ok_or_else(|| self.missing("account"))?;
|
||||
let kind = account_type(a, &ex.id);
|
||||
let parent = a
|
||||
.parent
|
||||
.as_deref()
|
||||
.map(|p| self.account_or_refuse(p))
|
||||
.transpose()?;
|
||||
copy.add_account(&a.code, &a.name, kind, parent, a.header)
|
||||
.and_then(|id| match &a.tax_category {
|
||||
Some(c) => copy.set_account_tax(id, Some(c), None),
|
||||
None => Ok(()),
|
||||
})
|
||||
.and_then(|()| {
|
||||
self.l().check_tax_category_required(
|
||||
&a.code,
|
||||
&a.name,
|
||||
kind,
|
||||
a.header,
|
||||
a.tax_category.as_deref(),
|
||||
)
|
||||
})
|
||||
}
|
||||
"set_tax_category" => {
|
||||
let code = q.code.as_deref().ok_or_else(|| self.missing("account"))?;
|
||||
let account = self.account_or_refuse(code)?;
|
||||
let category = q.category.as_deref();
|
||||
copy.set_account_tax(account, category, None)
|
||||
.and_then(|()| self.l().check_tax_category_kept(account, category))
|
||||
}
|
||||
other => unreachable!("{other} is no command"),
|
||||
};
|
||||
result
|
||||
.map(|()| Value::Bool(true))
|
||||
.map_err(|e| Refusal::of_reason(refusal(&e)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands an example may try: each on a copy of the books, so it
|
||||
/// changes nothing that is checked after it.
|
||||
pub(crate) const COMMANDS: [&str; 3] = ["rename_account", "add_account", "set_tax_category"];
|
||||
|
||||
/// The account `code` names, for a command.
|
||||
pub(crate) fn command_account(ex: &Example, l: &Ledger, x: &Expect) -> ledger_core::AccountId {
|
||||
let code = x
|
||||
.code
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| panic!("{}: {} names its account (code)", ex.id, x.query));
|
||||
l.chart()
|
||||
.find_by_code(code)
|
||||
.unwrap_or_else(|| panic!("{}: no account {code}", ex.id))
|
||||
.id
|
||||
}
|
||||
|
||||
/// Every balance, by code: what a change that moves no amount leaves as
|
||||
/// it was.
|
||||
pub(crate) fn every_balance(l: &Ledger) -> Vec<(String, Decimal, Decimal)> {
|
||||
trial_balance_as_of(l, ledger_core::calendar::LAST_DAY)
|
||||
.lines
|
||||
.into_iter()
|
||||
.map(|t| (t.code, t.debit, t.credit))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Try one command on a copy of the books, as the books' own command does
|
||||
/// it (the engine's checks, then the policy's: rules.md B-31, B-32), and
|
||||
/// check it is accepted or refused for the reason given.
|
||||
pub(crate) fn check_command(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
let mut copy = l.clone();
|
||||
let result: Result<(), LedgerError> = match x.query.as_str() {
|
||||
"rename_account" => {
|
||||
let account = command_account(ex, l, x);
|
||||
let name = x
|
||||
.name
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| panic!("{}: rename_account gives the name", ex.id));
|
||||
copy.rename_account(account, name).inspect(|()| {
|
||||
// A rename changes the label, nothing else (rules.md B-31).
|
||||
assert_eq!(
|
||||
copy.chart().get(account).unwrap().name,
|
||||
name.trim(),
|
||||
"{}: rename_account keeps the name trimmed",
|
||||
ex.id
|
||||
);
|
||||
assert_eq!(
|
||||
every_balance(©),
|
||||
every_balance(l),
|
||||
"{}: a rename moves no amount",
|
||||
ex.id
|
||||
);
|
||||
})
|
||||
}
|
||||
"add_account" => {
|
||||
let a = x
|
||||
.account
|
||||
.as_ref()
|
||||
.unwrap_or_else(|| panic!("{}: add_account gives the account", ex.id));
|
||||
let kind = account_type(a, &ex.id);
|
||||
let parent = a.parent.as_deref().map(|p| {
|
||||
l.chart()
|
||||
.find_by_code(p)
|
||||
.unwrap_or_else(|| panic!("{}: no account {p}", ex.id))
|
||||
.id
|
||||
});
|
||||
copy.add_account(&a.code, &a.name, kind, parent, a.header)
|
||||
.and_then(|id| match &a.tax_category {
|
||||
Some(c) => copy.set_account_tax(id, Some(c), None),
|
||||
None => Ok(()),
|
||||
})
|
||||
.and_then(|()| {
|
||||
l.check_tax_category_required(
|
||||
&a.code,
|
||||
&a.name,
|
||||
kind,
|
||||
a.header,
|
||||
a.tax_category.as_deref(),
|
||||
)
|
||||
})
|
||||
}
|
||||
"set_tax_category" => {
|
||||
let account = command_account(ex, l, x);
|
||||
let category = x.category.as_deref();
|
||||
copy.set_account_tax(account, category, None)
|
||||
.and_then(|()| l.check_tax_category_kept(account, category))
|
||||
}
|
||||
q => unreachable!("{q} is no command"),
|
||||
};
|
||||
match (result, &x.refused) {
|
||||
(Ok(()), None) => {}
|
||||
(Err(e), Some(want)) => {
|
||||
assert_eq!(refusal(&e), *want, "{}: {} refused ({e})", ex.id, x.query)
|
||||
}
|
||||
(Err(e), None) => panic!("{}: {} refused ({e}), expected accepted", ex.id, x.query),
|
||||
(Ok(()), Some(want)) => panic!("{}: {} accepted, expected refused: {want}", ex.id, x.query),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
use crate::*;
|
||||
|
||||
/// Check one `period` expectation: the period a period report asked with
|
||||
/// these dates covers, by the one rule (rules.md B-30), as `from` and
|
||||
/// `to`; or the rule's refusal.
|
||||
pub(crate) fn check_period(ex: &Example, x: &Expect) {
|
||||
match (resolved_period(ex, x), &x.refused) {
|
||||
(Ok((from, to)), None) => {
|
||||
exactly(ex, x, &["from".to_string(), "to".to_string()].into());
|
||||
let f = x.figures(&ex.id);
|
||||
assert_eq!(from, date(&f["from"], &ex.id), "{}: period from", ex.id);
|
||||
assert_eq!(to, date(&f["to"], &ex.id), "{}: period to", ex.id);
|
||||
}
|
||||
(Err(e), Some(want)) => assert_eq!(refusal(&e), *want, "{}: period refused ({e})", ex.id),
|
||||
(Err(e), None) => panic!("{}: period refused ({e})", ex.id),
|
||||
(Ok((from, to)), Some(want)) => {
|
||||
panic!("{}: period {from} .. {to}, expected refused: {want}", ex.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `day` expectation: the day a report as of a day is made as
|
||||
/// of (rules.md B-30), as `as_of`.
|
||||
pub(crate) fn check_day(ex: &Example, x: &Expect) {
|
||||
exactly(ex, x, &["as_of".to_string()].into());
|
||||
let want = date(&x.figures(&ex.id)["as_of"], &ex.id);
|
||||
assert_eq!(day(ex, x), want, "{}: day", ex.id);
|
||||
}
|
||||
|
||||
/// Check one `calendar_year` expectation: the year a calendar-year count
|
||||
/// (1099s, party totals) asked without one counts (rules.md B-30).
|
||||
pub(crate) fn check_calendar_year(ex: &Example, x: &Expect) {
|
||||
assert!(
|
||||
x.from.is_none() && x.to.is_none() && x.as_of.is_none(),
|
||||
"{}: calendar_year takes no dates",
|
||||
ex.id
|
||||
);
|
||||
exactly(ex, x, &["year".to_string()].into());
|
||||
let want: i32 = x.figures(&ex.id)["year"]
|
||||
.parse()
|
||||
.unwrap_or_else(|e| panic!("{}: calendar_year year: {e}", ex.id));
|
||||
assert_eq!(
|
||||
defaults(ex, &x.query).calendar_year(),
|
||||
want,
|
||||
"{}: calendar_year",
|
||||
ex.id
|
||||
);
|
||||
}
|
||||
|
||||
/// Check one `account_names` expectation: each account's name, by code,
|
||||
/// as the chart holds it and every report prints it (the trial balance
|
||||
/// and the profit and loss, over every date: past periods too, rules.md
|
||||
/// B-31); every account listed.
|
||||
pub(crate) fn check_account_names(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
assert!(
|
||||
x.from.is_none() && x.to.is_none() && x.as_of.is_none(),
|
||||
"{}: account_names takes no dates",
|
||||
ex.id
|
||||
);
|
||||
let keys = l.chart().all().map(|a| a.code.clone()).collect();
|
||||
exactly(ex, x, &keys);
|
||||
let (first, last) = (
|
||||
ledger_core::calendar::FIRST_DAY,
|
||||
ledger_core::calendar::LAST_DAY,
|
||||
);
|
||||
let tb = trial_balance_as_of(l, last);
|
||||
let pl = profit_and_loss_for_period(l, first, last, None)
|
||||
.unwrap_or_else(|e| panic!("{}: {e}", ex.id));
|
||||
for (code, want) in x.figures(&ex.id) {
|
||||
let a = l.chart().find_by_code(code).unwrap();
|
||||
assert_eq!(&a.name, want, "{}: account {code}'s name", ex.id);
|
||||
let printed = tb.lines.iter().map(|t| (&t.code, &t.name)).chain(
|
||||
pl.revenue
|
||||
.iter()
|
||||
.chain(&pl.expenses)
|
||||
.map(|s| (&s.code, &s.name)),
|
||||
);
|
||||
for (c, name) in printed.filter(|(c, _)| *c == code) {
|
||||
assert_eq!(name, want, "{}: a report prints {c} as {name:?}", ex.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `uncategorized_accounts` expectation: every account that
|
||||
/// maps to a line of the return and has no tax category, with activity or
|
||||
/// not, as `"<code> <name>"`, by code (rules.md B-32).
|
||||
pub(crate) fn check_uncategorized_accounts(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
assert!(
|
||||
x.from.is_none() && x.to.is_none() && x.as_of.is_none(),
|
||||
"{}: uncategorized_accounts takes no dates",
|
||||
ex.id
|
||||
);
|
||||
let Values::Lines(want) = x.values(&ex.id) else {
|
||||
panic!("{}: uncategorized_accounts expects a list", ex.id)
|
||||
};
|
||||
let got: Vec<String> = ledger_core::tax::uncategorized_accounts(l)
|
||||
.into_iter()
|
||||
.map(|a| format!("{} {}", a.code, a.name))
|
||||
.collect();
|
||||
assert_eq!(&got, want, "{}: uncategorized_accounts", ex.id);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
use crate::*;
|
||||
|
||||
impl Books<'_> {
|
||||
pub(crate) fn answer_iif(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let as_of = self.q_day(q)?;
|
||||
let iif = export_iif(self.l(), &self.ex.setup.cash_accounts, as_of)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Format, 2), e))?;
|
||||
match q.name.as_str() {
|
||||
"iif_lines" => {
|
||||
let mut lines: Vec<&str> = iif.text.split("\r\n").collect();
|
||||
if lines.last() == Some(&"") {
|
||||
lines.pop();
|
||||
}
|
||||
Ok(Value::Array(
|
||||
lines
|
||||
.into_iter()
|
||||
.map(|l| Value::String(l.to_string()))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
_ => Ok(Value::Array(
|
||||
iif.changes
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let what = match &c.field {
|
||||
IifField::AccountName { code } => format!("name {code}"),
|
||||
IifField::Memo { entry } => format!("memo {entry}"),
|
||||
IifField::AccountNumber | IifField::AccountNumberLeftOut { .. } => {
|
||||
"number".to_string()
|
||||
}
|
||||
IifField::AtTopLevel { code, .. } => format!("top level {code}"),
|
||||
IifField::ClassName { class } => format!("class {class}"),
|
||||
};
|
||||
Value::Array(vec![
|
||||
Value::String(what),
|
||||
Value::String(c.books.clone()),
|
||||
Value::String(c.written.clone()),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The formats appendix's queries, and the test (another crate's) that
|
||||
/// checks them against the engine.
|
||||
pub(crate) const FORMAT_QUERIES: [(&str, &str); 2] = [
|
||||
(
|
||||
"iif_lines",
|
||||
"ledger-package the_bookspec_iif_example_matches_the_engine",
|
||||
),
|
||||
(
|
||||
"iif_changes",
|
||||
"ledger-package the_bookspec_iif_example_matches_the_engine",
|
||||
),
|
||||
];
|
||||
|
||||
/// A format query's shape, checked here; its values are checked by
|
||||
/// [`FORMAT_QUERIES`]' test.
|
||||
pub(crate) fn check_format_shape(ex: &Example, x: &Expect) {
|
||||
assert_eq!(
|
||||
ex.appendix.as_deref(),
|
||||
Some("formats"),
|
||||
"{}: {} is a format's: the example is in appendix \"formats\"",
|
||||
ex.id,
|
||||
x.query
|
||||
);
|
||||
// ledger-package reads the as_of itself: given, never defaulted.
|
||||
assert!(x.as_of.is_some(), "{}: {} gives as_of", ex.id, x.query);
|
||||
day(ex, x);
|
||||
assert!(
|
||||
x.after.is_none(),
|
||||
"{}: {}: a format query is of the books after every event",
|
||||
ex.id,
|
||||
x.query
|
||||
);
|
||||
match (x.query.as_str(), x.values(&ex.id)) {
|
||||
("iif_lines", Values::Lines(_)) => {}
|
||||
("iif_changes", Values::Rows(rows)) => {
|
||||
for r in rows {
|
||||
assert_eq!(r.len(), 3, "{}: iif_changes row {r:?}", ex.id);
|
||||
}
|
||||
}
|
||||
(q, _) => panic!("{}: {q}: values of the wrong shape", ex.id),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
use crate::*;
|
||||
|
||||
pub(crate) mod assets;
|
||||
pub(crate) mod commands;
|
||||
pub(crate) mod dates;
|
||||
pub(crate) mod formats;
|
||||
pub(crate) mod parties;
|
||||
pub(crate) mod statements;
|
||||
pub(crate) mod tax;
|
||||
|
||||
impl Books<'_> {
|
||||
/// A refusal of a question the example did not fill in.
|
||||
pub(crate) fn missing(&self, what: &str) -> Refusal {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Ledger, 1),
|
||||
format!("{} names its {what}", "the query"),
|
||||
)
|
||||
}
|
||||
|
||||
/// The period a query covers, or the rule's refusal.
|
||||
pub(crate) fn q_period(&self, q: &Query) -> Result<(NaiveDate, NaiveDate), Refusal> {
|
||||
resolved_q_period(self.ex, q).map_err(|e| Refusal::of_reason(refusal(&e)))
|
||||
}
|
||||
|
||||
/// The day an as-of query is made as of.
|
||||
pub(crate) fn q_day(&self, q: &Query) -> Result<NaiveDate, Refusal> {
|
||||
resolved_q_day(self.ex, q).map_err(|e| Refusal::of_reason(refusal(&e)))
|
||||
}
|
||||
|
||||
/// The event whose entry `entry` is, counting from 1.
|
||||
pub(crate) fn event_of(&self, entry: EntryId) -> Option<usize> {
|
||||
self.posted
|
||||
.iter()
|
||||
.position(|entries| entries.contains(&entry))
|
||||
.map(|i| i + 1)
|
||||
}
|
||||
|
||||
/// The entry event `n` posted.
|
||||
pub(crate) fn entry_or_refuse(&self, n: usize) -> Result<EntryId, Refusal> {
|
||||
assert!(n >= 1 && n <= self.posted.len(), "event {n} not applied");
|
||||
match self.posted[n - 1].as_slice() {
|
||||
[entry] => Ok(*entry),
|
||||
other => Err(Refusal::new(
|
||||
RuleId::new(Area::Ledger, 1),
|
||||
format!("event {n} posted {} entries", other.len()),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The account `code` names.
|
||||
pub(crate) fn account_or_refuse(&self, code: &str) -> Result<ledger_core::AccountId, Refusal> {
|
||||
self.l()
|
||||
.chart()
|
||||
.find_by_code(code)
|
||||
.map(|a| a.id)
|
||||
.ok_or_else(|| Refusal::new(RuleId::new(Area::Ledger, 1), format!("no account {code}")))
|
||||
}
|
||||
|
||||
/// The payment accounts the example names.
|
||||
pub(crate) fn payment_accounts(&self) -> Result<PaymentAccounts, Refusal> {
|
||||
let ex = &self.ex;
|
||||
Ok(PaymentAccounts {
|
||||
cash: codes(self.l(), &ex.setup.cash_accounts, &ex.id),
|
||||
financing: codes(self.l(), &ex.setup.financing_accounts, &ex.id),
|
||||
})
|
||||
}
|
||||
|
||||
/// The engine's answer to one query, as the runner compares it: exact
|
||||
/// decimal strings, never floats; dates `YYYY-MM-DD`.
|
||||
pub(crate) fn answer(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
match q.name.as_str() {
|
||||
"cash_flow" => self.answer_cash_flow(q),
|
||||
"trial_balance" => self.answer_trial_balance(q),
|
||||
"profit_and_loss" => self.answer_profit_and_loss(q),
|
||||
"entry" => self.answer_entry(q),
|
||||
"balances" => self.answer_balances(q),
|
||||
"members_equity" => self.answer_members_equity(q),
|
||||
"k1" => self.answer_k1(q),
|
||||
"k1_tax_basis" => self.answer_k1_tax_basis(q),
|
||||
"k1_reconciliation" => self.answer_k1_reconciliation(q),
|
||||
"vendor_1099_paid" => self.answer_vendor_1099_paid(q),
|
||||
"vendor_1099" => self.answer_vendor_1099(q),
|
||||
"party_part" => self.answer_party_part(q),
|
||||
"party_totals" => self.answer_party_totals(q),
|
||||
"party_tin_last4" => self.answer_party_tin_last4(q),
|
||||
"project" => self.answer_project(q),
|
||||
"run" => self.answer_run(q),
|
||||
"disposal" => self.answer_disposal(q),
|
||||
"depreciation_schedule" => self.answer_depreciation_schedule(q),
|
||||
"schedule_plan" => self.answer_schedule_plan(q),
|
||||
"register_row" => self.answer_register_row(q),
|
||||
"register_totals" => self.answer_register_totals(q),
|
||||
"asset_basis" => self.answer_asset_basis(q),
|
||||
"period" => {
|
||||
let (from, to) = self.q_period(q)?;
|
||||
Ok(json_figures([
|
||||
("from".to_string(), from.to_string()),
|
||||
("to".to_string(), to.to_string()),
|
||||
]))
|
||||
}
|
||||
"day" => Ok(json_figures([(
|
||||
"as_of".to_string(),
|
||||
self.q_day(q)?.to_string(),
|
||||
)])),
|
||||
"calendar_year" => Ok(json_figures([(
|
||||
"year".to_string(),
|
||||
defaults(self.ex, &q.name).calendar_year().to_string(),
|
||||
)])),
|
||||
"account_names" => Ok(json_figures(
|
||||
self.l()
|
||||
.chart()
|
||||
.all()
|
||||
.map(|a| (a.code.clone(), a.name.clone())),
|
||||
)),
|
||||
"uncategorized_accounts" => Ok(Value::Array(
|
||||
ledger_core::tax::uncategorized_accounts(self.l())
|
||||
.into_iter()
|
||||
.map(|a| Value::String(format!("{} {}", a.code, a.name)))
|
||||
.collect(),
|
||||
)),
|
||||
"iif_lines" | "iif_changes" => self.answer_iif(q),
|
||||
"rename_account" | "add_account" | "set_tax_category" => self.answer_command(q),
|
||||
other => Err(Refusal::new(
|
||||
RuleId::new(Area::Ledger, 1),
|
||||
format!("no answer for query {other:?}"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
use crate::*;
|
||||
|
||||
impl Books<'_> {
|
||||
pub(crate) fn answer_vendor_1099_paid(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let (from, to) = self.q_period(q)?;
|
||||
let year = chrono::Datelike::year(&to);
|
||||
let l = self.l();
|
||||
let sources = self.payment_accounts()?;
|
||||
let r = vendor_1099_report(l, year, None, &sources, &self.party_members, Some(to))
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Tax1099, 1), e))?;
|
||||
let _ = from;
|
||||
let mut m = JsonMap::new();
|
||||
for (name, vendor) in &self.payees {
|
||||
let paid: Decimal = r
|
||||
.vendors
|
||||
.iter()
|
||||
.filter(|v| v.vendor_id == *vendor)
|
||||
.map(|v| v.paid)
|
||||
.sum();
|
||||
m.insert(name.clone(), Value::String(figure(paid)));
|
||||
}
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_vendor_1099(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let (_, to) = self.q_period(q)?;
|
||||
let year = chrono::Datelike::year(&to);
|
||||
let name = q.payee.as_deref().ok_or_else(|| self.missing("payee"))?;
|
||||
let v = *self.payees.get(name).ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Tax1099, 1),
|
||||
format!("payee {name:?} not in setup"),
|
||||
)
|
||||
})?;
|
||||
let sources = self.payment_accounts()?;
|
||||
let r = vendor_1099_report(
|
||||
self.l(),
|
||||
year,
|
||||
None,
|
||||
&sources,
|
||||
&self.party_members,
|
||||
Some(to),
|
||||
)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Tax1099, 1), e))?;
|
||||
let line = r.vendors.iter().find(|l| l.vendor_id == v).ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Tax1099, 1),
|
||||
format!("the 1099 worksheet has no line for {name}"),
|
||||
)
|
||||
})?;
|
||||
Ok(json_figures([
|
||||
("status".to_string(), line.status.key().to_string()),
|
||||
("threshold".to_string(), figure(r.threshold)),
|
||||
("paid".to_string(), figure(line.paid)),
|
||||
("excluded_card".to_string(), figure(line.excluded_card)),
|
||||
("undetermined".to_string(), figure(line.undetermined)),
|
||||
("not_reportable".to_string(), figure(line.not_reportable)),
|
||||
]))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_party_part(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let event = q.entry.ok_or_else(|| self.missing("entry"))?;
|
||||
let n = self.entry_or_refuse(event)?;
|
||||
let name = q.party.as_deref().ok_or_else(|| self.missing("party"))?;
|
||||
let party = *self.parties.get(name).ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Partner, 3),
|
||||
format!("party {name:?} not in setup"),
|
||||
)
|
||||
})?;
|
||||
let ex = &self.ex;
|
||||
let r = ledger_core::shares::resolve(
|
||||
self.l(),
|
||||
n,
|
||||
self.l().entry_parties(n),
|
||||
&party_money(ex, self.l()),
|
||||
&self.party_members,
|
||||
)
|
||||
.map_err(|why| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Partner, 3),
|
||||
format!("entry {n}'s shares: {why}"),
|
||||
)
|
||||
})?;
|
||||
let part = r.part(party).ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Partner, 3),
|
||||
format!("entry {n} doesn't name {name:?}"),
|
||||
)
|
||||
})?;
|
||||
Ok(json_figures([
|
||||
("resolved".to_string(), figure(part.amount)),
|
||||
(
|
||||
"direction".to_string(),
|
||||
r.target.direction.key().to_string(),
|
||||
),
|
||||
("cash".to_string(), figure(part.cash)),
|
||||
("in_kind".to_string(), figure(part.in_kind)),
|
||||
]))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_party_totals(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let (from, to) = self.q_period(q)?;
|
||||
let basis = q
|
||||
.basis
|
||||
.as_deref()
|
||||
.ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Partner, 3),
|
||||
"party_totals names its basis",
|
||||
)
|
||||
})
|
||||
.and_then(|k| {
|
||||
Basis::parse(k).filter(|b| b.key() == k).ok_or_else(|| {
|
||||
Refusal::new(RuleId::new(Area::Partner, 3), format!("basis {k:?}"))
|
||||
})
|
||||
})?;
|
||||
let name = q.party.as_deref().ok_or_else(|| self.missing("party"))?;
|
||||
let party = *self.parties.get(name).ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Partner, 3),
|
||||
format!("party {name:?} not in setup"),
|
||||
)
|
||||
})?;
|
||||
let ex = &self.ex;
|
||||
let a = ledger_core::parties::activity_with(
|
||||
self.l(),
|
||||
party,
|
||||
(from, to),
|
||||
&party_money(ex, self.l()),
|
||||
&self.party_members,
|
||||
);
|
||||
if !a.unresolved.is_empty() {
|
||||
return Err(Refusal::new(
|
||||
RuleId::new(Area::Partner, 3),
|
||||
format!("{name:?}'s entries don't resolve"),
|
||||
));
|
||||
}
|
||||
let (paid, received) = a.totals(basis);
|
||||
Ok(json_figures([
|
||||
("paid".to_string(), figure(paid)),
|
||||
("received".to_string(), figure(received)),
|
||||
]))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_party_tin_last4(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let name = q.party.as_deref().ok_or_else(|| self.missing("party"))?;
|
||||
let party = *self.parties.get(name).ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Partner, 2),
|
||||
format!("party {name:?} not in setup"),
|
||||
)
|
||||
})?;
|
||||
let got = self
|
||||
.l()
|
||||
.get_party(party)
|
||||
.and_then(|p| p.tin_last4())
|
||||
.unwrap_or_default();
|
||||
Ok(json_figures([("tin_last4".to_string(), got.to_string())]))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_project(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let name = q
|
||||
.project
|
||||
.as_deref()
|
||||
.ok_or_else(|| self.missing("project"))?;
|
||||
let id = *self.projects.get(name).ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Statement, 5),
|
||||
format!("project {name:?} not in setup.projects"),
|
||||
)
|
||||
})?;
|
||||
let (from, to) = self.q_period(q)?;
|
||||
let f = ledger_core::project_figures(self.l(), id, from, to)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Statement, 5), e))?;
|
||||
let opt = |d: Option<Decimal>| d.map_or("none".to_string(), figure);
|
||||
Ok(json_figures([
|
||||
("revenue".to_string(), figure(f.period.total_revenue)),
|
||||
("expenses".to_string(), figure(f.period.total_expenses)),
|
||||
("net".to_string(), figure(f.period.net_income())),
|
||||
("to_date.revenue".to_string(), figure(f.to_date.revenue)),
|
||||
("to_date.expenses".to_string(), figure(f.to_date.expenses)),
|
||||
("to_date.net".to_string(), figure(f.to_date.net())),
|
||||
(
|
||||
"unrecovered_cost".to_string(),
|
||||
opt(f.to_date.unrecovered_cost),
|
||||
),
|
||||
]))
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1099 report a `vendor_1099_paid` or `vendor_1099` expectation
|
||||
/// asks for: the calendar year of `to`, from January 1 through `to`, out
|
||||
/// of the cash and financing accounts, an entry's shares resolved with
|
||||
/// the members who are parties (rules.md B-19, B-33).
|
||||
pub(crate) fn report_1099(
|
||||
b: &Books<'_>,
|
||||
x: &Expect,
|
||||
) -> (NaiveDate, NaiveDate, ledger_core::Vendor1099Report) {
|
||||
let (ex, l) = (b.ex, b.l());
|
||||
// A calendar-year count, never the fiscal default (rules.md B-30):
|
||||
// both dates given.
|
||||
assert!(
|
||||
x.from.is_some() && x.to.is_some(),
|
||||
"{}: {} gives from and to",
|
||||
ex.id,
|
||||
x.query
|
||||
);
|
||||
let (from, to) = period(ex, x);
|
||||
let year = chrono::Datelike::year(&to);
|
||||
assert_eq!(
|
||||
Some(from),
|
||||
NaiveDate::from_ymd_opt(year, 1, 1),
|
||||
"{}: a 1099 counts a calendar year: from is January 1 of to's year",
|
||||
ex.id
|
||||
);
|
||||
assert!(
|
||||
!ex.setup.cash_accounts.is_empty(),
|
||||
"{}: {} needs cash_accounts (what payees are paid from)",
|
||||
ex.id,
|
||||
x.query
|
||||
);
|
||||
let sources = PaymentAccounts {
|
||||
cash: codes(l, &ex.setup.cash_accounts, &ex.id),
|
||||
financing: codes(l, &ex.setup.financing_accounts, &ex.id),
|
||||
};
|
||||
let r = vendor_1099_report(l, year, None, &sources, &b.party_members, Some(to))
|
||||
.unwrap_or_else(|e| panic!("{}: {e}", ex.id));
|
||||
(from, to, r)
|
||||
}
|
||||
|
||||
/// Check one `vendor_1099_paid` expectation: each payee's payments that
|
||||
/// count toward its 1099 ([`report_1099`]), a payment card's left out,
|
||||
/// every payee listed (rules.md B-19, B-33).
|
||||
pub(crate) fn check_vendor_1099_paid(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
let (from, to, r) = report_1099(b, x);
|
||||
exactly(ex, x, &b.payees.keys().cloned().collect());
|
||||
for (name, want) in x.figures(&ex.id) {
|
||||
let want = exact(want, &format!("{} {name}", ex.id));
|
||||
let got: Decimal = r
|
||||
.vendors
|
||||
.iter()
|
||||
.filter(|v| v.vendor_id == b.payees[name])
|
||||
.map(|v| v.paid)
|
||||
.sum();
|
||||
assert_eq!(got, want, "{} 1099 paid [{from} .. {to}]: {name}", ex.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `vendor_1099` expectation: one payee's line of the 1099
|
||||
/// worksheet ([`report_1099`]): `status` (`reportable`,
|
||||
/// `under_threshold`, `not_reportable`, `undetermined`), the `threshold`
|
||||
/// applied, and what was `paid` (counts toward its 1099),
|
||||
/// `excluded_card` (a card or payment network's, Form 1099-K),
|
||||
/// `undetermined` (its payment method not recorded) and `not_reportable`
|
||||
/// (paid while decided not reportable); every one given (rules.md B-19).
|
||||
pub(crate) fn check_vendor_1099(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
let name = x
|
||||
.payee
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| panic!("{}: vendor_1099 names its payee", ex.id));
|
||||
let v = *b
|
||||
.payees
|
||||
.get(name)
|
||||
.unwrap_or_else(|| panic!("{}: payee {name:?} not in setup", ex.id));
|
||||
let (from, to, r) = report_1099(b, x);
|
||||
let line = r
|
||||
.vendors
|
||||
.iter()
|
||||
.find(|l| l.vendor_id == v)
|
||||
.unwrap_or_else(|| panic!("{}: the 1099 worksheet has no line for {name}", ex.id));
|
||||
let keys = [
|
||||
"status",
|
||||
"threshold",
|
||||
"paid",
|
||||
"excluded_card",
|
||||
"undetermined",
|
||||
"not_reportable",
|
||||
];
|
||||
exactly(ex, x, &keys.iter().map(|k| k.to_string()).collect());
|
||||
let what = |k: &str| format!("{} 1099 [{from} .. {to}] {name}: {k}", ex.id);
|
||||
for (key, want) in x.figures(&ex.id) {
|
||||
if key == "status" {
|
||||
assert_eq!(line.status.key(), want, "{}", what(key));
|
||||
continue;
|
||||
}
|
||||
let got = match key.as_str() {
|
||||
"threshold" => r.threshold,
|
||||
"paid" => line.paid,
|
||||
"excluded_card" => line.excluded_card,
|
||||
"undetermined" => line.undetermined,
|
||||
_ => line.not_reportable,
|
||||
};
|
||||
assert_eq!(got, exact(want, &what(key)), "{}", what(key));
|
||||
}
|
||||
}
|
||||
|
||||
/// The money party shares resolve against: the cash accounts (every
|
||||
/// asset account but receivables when none are named), the cards and the
|
||||
/// financing accounts (rules.md B-35 item 5).
|
||||
pub(crate) fn party_money(ex: &Example, l: &Ledger) -> MoneyAccounts {
|
||||
ledger_core::parties::money_accounts(
|
||||
l,
|
||||
&codes(l, &ex.setup.cash_accounts, &ex.id),
|
||||
&codes(l, &ex.setup.financing_accounts, &ex.id),
|
||||
)
|
||||
}
|
||||
|
||||
/// The party an expectation names.
|
||||
pub(crate) fn expect_party(b: &Books<'_>, x: &Expect) -> PartyId {
|
||||
let name = x
|
||||
.party
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| panic!("{}: {} names its party", b.ex.id, x.query));
|
||||
*b.parties
|
||||
.get(name)
|
||||
.unwrap_or_else(|| panic!("{}: party {name:?} not in setup.parties", b.ex.id))
|
||||
}
|
||||
|
||||
/// Check one `party_part` expectation: entry N's part for the party
|
||||
/// (rules.md B-35): `resolved`, signed as a line on the party's own
|
||||
/// account (debit-positive: paid or given positive, received negative),
|
||||
/// the entry's `direction` (`paid`, `received` or `neither`), and what
|
||||
/// of it moved as money (`cash`) and as property (`in_kind`); every one
|
||||
/// given.
|
||||
pub(crate) fn check_party_part(b: &Books<'_>, x: &Expect) {
|
||||
let (ex, l) = (b.ex, b.l());
|
||||
assert!(
|
||||
x.from.is_none() && x.to.is_none() && x.as_of.is_none(),
|
||||
"{}: party_part asks about one entry, no dates",
|
||||
ex.id
|
||||
);
|
||||
let event = x
|
||||
.entry
|
||||
.unwrap_or_else(|| panic!("{}: a party_part query names its event", ex.id));
|
||||
let n = b.entry_of(event, &format!("{} party_part", ex.id));
|
||||
let party = expect_party(b, x);
|
||||
let r = ledger_core::shares::resolve(
|
||||
l,
|
||||
n,
|
||||
l.entry_parties(n),
|
||||
&party_money(ex, l),
|
||||
&b.party_members,
|
||||
)
|
||||
.unwrap_or_else(|why| panic!("{}: entry {n}'s shares: {why}", ex.id));
|
||||
let part = r
|
||||
.part(party)
|
||||
.unwrap_or_else(|| panic!("{}: entry {n} doesn't name {:?}", ex.id, x.party));
|
||||
let keys = ["resolved", "direction", "cash", "in_kind"];
|
||||
exactly(ex, x, &keys.iter().map(|k| k.to_string()).collect());
|
||||
let what = |k: &str| format!("{} entry {n} {:?}: {k}", ex.id, x.party);
|
||||
for (key, want) in x.figures(&ex.id) {
|
||||
if key == "direction" {
|
||||
assert_eq!(r.target.direction.key(), want, "{}", what(key));
|
||||
continue;
|
||||
}
|
||||
let got = match key.as_str() {
|
||||
"resolved" => part.amount,
|
||||
"cash" => part.cash,
|
||||
_ => part.in_kind,
|
||||
};
|
||||
assert_eq!(got, exact(want, &what(key)), "{}", what(key));
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `party_totals` expectation: what was `paid` to and
|
||||
/// `received` from the party from `from` through `to` on `basis` (`cash`:
|
||||
/// money; `all`: money and property in kind), each entry's part on its
|
||||
/// root original's side (rules.md B-35 item 4); both given.
|
||||
pub(crate) fn check_party_totals(b: &Books<'_>, x: &Expect) {
|
||||
let (ex, l) = (b.ex, b.l());
|
||||
assert!(
|
||||
x.from.is_some() && x.to.is_some(),
|
||||
"{}: party_totals gives from and to",
|
||||
ex.id
|
||||
);
|
||||
let (from, to) = period(ex, x);
|
||||
let basis = x
|
||||
.basis
|
||||
.as_deref()
|
||||
.map(|k| {
|
||||
Basis::parse(k)
|
||||
.filter(|b| b.key() == k)
|
||||
.unwrap_or_else(|| panic!("{}: basis {k:?}", ex.id))
|
||||
})
|
||||
.unwrap_or_else(|| panic!("{}: party_totals names its basis", ex.id));
|
||||
let party = expect_party(b, x);
|
||||
let a = ledger_core::parties::activity_with(
|
||||
l,
|
||||
party,
|
||||
(from, to),
|
||||
&party_money(ex, l),
|
||||
&b.party_members,
|
||||
);
|
||||
assert!(
|
||||
a.unresolved.is_empty(),
|
||||
"{}: {:?}'s entries {:?} don't resolve",
|
||||
ex.id,
|
||||
x.party,
|
||||
a.unresolved
|
||||
);
|
||||
let (paid, received) = a.totals(basis);
|
||||
exactly(ex, x, &["paid".to_string(), "received".to_string()].into());
|
||||
let f = x.figures(&ex.id);
|
||||
let what = |k: &str| {
|
||||
format!(
|
||||
"{} {:?} [{from} .. {to}] {}: {k}",
|
||||
ex.id,
|
||||
x.party,
|
||||
basis.key()
|
||||
)
|
||||
};
|
||||
assert_eq!(paid, exact(&f["paid"], &what("paid")), "{}", what("paid"));
|
||||
assert_eq!(
|
||||
received,
|
||||
exact(&f["received"], &what("received")),
|
||||
"{}",
|
||||
what("received")
|
||||
);
|
||||
}
|
||||
|
||||
/// Check one `project` expectation (rules.md B-37): the project's
|
||||
/// `revenue`, `expenses` and `net` for the period (B-30 resolving omitted
|
||||
/// dates), the same `to_date` (every tagged line through `to`), and its
|
||||
/// `unrecovered_cost` (`"none"` unless it is on spec); every one given.
|
||||
/// Through ledger_core::project_figures, as the tools and the viewer.
|
||||
pub(crate) fn check_project(b: &Books<'_>, x: &Expect) {
|
||||
let (ex, l) = (b.ex, b.l());
|
||||
let name = x
|
||||
.project
|
||||
.as_ref()
|
||||
.unwrap_or_else(|| panic!("{}: a project query names its project", ex.id));
|
||||
let id = *b
|
||||
.projects
|
||||
.get(name)
|
||||
.unwrap_or_else(|| panic!("{}: project {name:?} not in setup.projects", ex.id));
|
||||
let (from, to) = period(ex, x);
|
||||
let f =
|
||||
ledger_core::project_figures(l, id, from, to).unwrap_or_else(|e| panic!("{}: {e}", ex.id));
|
||||
let keys: BTreeSet<String> = [
|
||||
"revenue",
|
||||
"expenses",
|
||||
"net",
|
||||
"to_date.revenue",
|
||||
"to_date.expenses",
|
||||
"to_date.net",
|
||||
"unrecovered_cost",
|
||||
]
|
||||
.iter()
|
||||
.map(|k| k.to_string())
|
||||
.collect();
|
||||
exactly(ex, x, &keys);
|
||||
let what = |k: &str| format!("{} project {name:?} [{from} .. {to}]: {k}", ex.id);
|
||||
for (key, want) in x.figures(&ex.id) {
|
||||
let got = match key.as_str() {
|
||||
"revenue" => Some(f.period.total_revenue),
|
||||
"expenses" => Some(f.period.total_expenses),
|
||||
"net" => Some(f.period.net_income()),
|
||||
"to_date.revenue" => Some(f.to_date.revenue),
|
||||
"to_date.expenses" => Some(f.to_date.expenses),
|
||||
"to_date.net" => Some(f.to_date.net()),
|
||||
_ => f.to_date.unrecovered_cost,
|
||||
};
|
||||
match (want.as_str(), got) {
|
||||
("none", None) => {}
|
||||
("none", Some(g)) => panic!("{}: {g}, expected none", what(key)),
|
||||
(w, Some(g)) => assert_eq!(g, exact(w, &what(key)), "{}", what(key)),
|
||||
(w, None) => panic!("{}: none, expected {w}", what(key)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `party_tin_last4` expectation: the last four of the party's
|
||||
/// TIN the books keep (its TIN facts', else its W-9's; `""` for none:
|
||||
/// rules.md B-26).
|
||||
pub(crate) fn check_party_tin_last4(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
assert!(
|
||||
x.from.is_none() && x.to.is_none() && x.as_of.is_none(),
|
||||
"{}: party_tin_last4 takes no dates",
|
||||
ex.id
|
||||
);
|
||||
let party = expect_party(b, x);
|
||||
exactly(ex, x, &["tin_last4".to_string()].into());
|
||||
let got = b
|
||||
.l()
|
||||
.get_party(party)
|
||||
.and_then(|p| p.tin_last4())
|
||||
.unwrap_or_default();
|
||||
assert_eq!(
|
||||
got,
|
||||
x.figures(&ex.id)["tin_last4"],
|
||||
"{}: {:?}'s TIN last four",
|
||||
ex.id,
|
||||
x.party
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
use crate::*;
|
||||
|
||||
impl Books<'_> {
|
||||
pub(crate) fn answer_cash_flow(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let (start, end) = self.q_period(q)?;
|
||||
let l = self.l();
|
||||
let params = CashFlowParams {
|
||||
start,
|
||||
end,
|
||||
cash_accounts: codes(l, &self.ex.setup.cash_accounts, &self.ex.id),
|
||||
financing_accounts: codes(l, &self.ex.setup.financing_accounts, &self.ex.id),
|
||||
investing_accounts: codes(l, &self.ex.setup.investing_accounts, &self.ex.id),
|
||||
members: self.members.clone(),
|
||||
};
|
||||
let cf = cash_flow(l, ¶ms)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Statement, 3), e))?;
|
||||
let mut m = JsonMap::new();
|
||||
let put = |m: &mut JsonMap, key: &str, d: Decimal| {
|
||||
m.insert(key.to_string(), Value::String(figure(d)));
|
||||
};
|
||||
put(&mut m, "net_change", cf.net_change_in_cash);
|
||||
put(&mut m, "cash_beginning", cf.cash_beginning);
|
||||
put(&mut m, "cash_ending", cf.cash_ending);
|
||||
put(&mut m, "difference", cf.reconciles.difference);
|
||||
put(&mut m, "net_income", cf.operating_reconciliation.net_income);
|
||||
m.insert(
|
||||
"noncash.count".to_string(),
|
||||
Value::String(cf.noncash_disclosures.len().to_string()),
|
||||
);
|
||||
for (name, section) in [
|
||||
("operating", CashFlowSection::Operating),
|
||||
("investing", CashFlowSection::Investing),
|
||||
("financing", CashFlowSection::Financing),
|
||||
] {
|
||||
put(&mut m, name, cf.total(section));
|
||||
let lines = cf.lines(section);
|
||||
let entries: BTreeSet<EntryId> = lines.iter().map(|l| l.entry).collect();
|
||||
m.insert(
|
||||
format!("{name}.count"),
|
||||
Value::String(entries.len().to_string()),
|
||||
);
|
||||
for l in lines {
|
||||
let Some(n) = self.event_of(l.entry) else {
|
||||
continue;
|
||||
};
|
||||
let key = format!("{name}.{n}");
|
||||
let amount = m
|
||||
.get(&key)
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|s| s.parse::<Decimal>().ok())
|
||||
.unwrap_or_default();
|
||||
m.insert(key, Value::String(figure(amount + l.amount)));
|
||||
let key = format!("{name}.{n}.on_behalf");
|
||||
let amount = m
|
||||
.get(&key)
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|s| s.parse::<Decimal>().ok())
|
||||
.unwrap_or_default();
|
||||
m.insert(key, Value::String(figure(amount + l.on_behalf)));
|
||||
}
|
||||
}
|
||||
for d in &cf.noncash_disclosures {
|
||||
if let Some(n) = self.event_of(d.entry) {
|
||||
let key = format!("noncash.{n}");
|
||||
let amount = m
|
||||
.get(&key)
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|s| s.parse::<Decimal>().ok())
|
||||
.unwrap_or_default();
|
||||
m.insert(key, Value::String(figure(amount + d.amount)));
|
||||
}
|
||||
}
|
||||
for (class, amount) in cf.operating_by_class() {
|
||||
let letter = ["a", "b", "c", "d", "e", "f", "g"]
|
||||
.into_iter()
|
||||
.find(|l| operating_class(l) == Some(class))
|
||||
.expect("a class has its letter");
|
||||
put(&mut m, &format!("class.{letter}"), amount);
|
||||
}
|
||||
for line in &cf.operating_reconciliation.lines {
|
||||
put(&mut m, &reconciliation_key(line), line.amount);
|
||||
}
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_trial_balance(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let as_of = self.q_day(q)?;
|
||||
let tb = trial_balance_as_of(self.l(), as_of);
|
||||
if !tb.balanced() {
|
||||
return Err(Refusal::new(
|
||||
RuleId::new(Area::Statement, 1),
|
||||
"the trial balance balances",
|
||||
));
|
||||
}
|
||||
Ok(json_figures(self.ex.setup.accounts.iter().map(|a| {
|
||||
let (dr, cr) = tb
|
||||
.lines
|
||||
.iter()
|
||||
.find(|t| t.code == a.code)
|
||||
.map_or((Decimal::ZERO, Decimal::ZERO), |t| (t.debit, t.credit));
|
||||
(a.code.clone(), figure(dr - cr))
|
||||
})))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_profit_and_loss(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let (start, end) = self.q_period(q)?;
|
||||
let pl = profit_and_loss_for_period(self.l(), start, end, None)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Statement, 3), e))?;
|
||||
let mut m = JsonMap::new();
|
||||
for a in self
|
||||
.ex
|
||||
.setup
|
||||
.accounts
|
||||
.iter()
|
||||
.filter(|a| matches!(a.kind.as_str(), "revenue" | "expense"))
|
||||
{
|
||||
let amount: Decimal = pl
|
||||
.revenue
|
||||
.iter()
|
||||
.chain(&pl.expenses)
|
||||
.filter(|s| s.code == a.code)
|
||||
.map(|s| s.amount)
|
||||
.sum();
|
||||
m.insert(a.code.clone(), Value::String(figure(amount)));
|
||||
}
|
||||
m.insert(
|
||||
"net_income".to_string(),
|
||||
Value::String(figure(pl.net_income())),
|
||||
);
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_entry(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let n = q.entry.ok_or_else(|| self.missing("entry"))?;
|
||||
let entry = self
|
||||
.l()
|
||||
.get_entry(self.entry_or_refuse(n)?)
|
||||
.expect("an entry an event posted");
|
||||
let mut got: BTreeMap<String, Decimal> = BTreeMap::new();
|
||||
for line in entry.lines() {
|
||||
let code = &self.l().chart().get(line.account).unwrap().code;
|
||||
let side = match line.side {
|
||||
Side::Debit => "debit",
|
||||
Side::Credit => "credit",
|
||||
};
|
||||
*got.entry(format!("{code}.{side}")).or_default() += line.amount.amount;
|
||||
}
|
||||
Ok(json_figures(got.into_iter().map(|(k, v)| (k, figure(v)))))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_balances(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let as_of = self.q_day(q)?;
|
||||
let tb = trial_balance_as_of(self.l(), as_of);
|
||||
let mut m = JsonMap::new();
|
||||
for account in self.l().chart().all() {
|
||||
let (dr, cr) = tb
|
||||
.lines
|
||||
.iter()
|
||||
.find(|t| t.code == account.code)
|
||||
.map_or((Decimal::ZERO, Decimal::ZERO), |t| (t.debit, t.credit));
|
||||
let got = match account.account_type.normal_side() {
|
||||
Side::Debit => dr - cr,
|
||||
Side::Credit => cr - dr,
|
||||
};
|
||||
m.insert(account.code.clone(), Value::String(figure(got)));
|
||||
}
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_members_equity(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let (from, to) = self.q_period(q)?;
|
||||
let st = members_equity(self.l(), from, to, &self.members)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Partner, 1), e))?;
|
||||
let mut m = JsonMap::new();
|
||||
for member in &st.members {
|
||||
for (column, v) in [
|
||||
("beginning", member.beginning),
|
||||
("contributions", member.contributions),
|
||||
("net_income", member.net_income),
|
||||
("distributions", member.distributions),
|
||||
("other", member.other),
|
||||
("ending", member.ending),
|
||||
] {
|
||||
m.insert(
|
||||
format!("{}.{column}", member.name),
|
||||
Value::String(figure(v)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `cash_flow` query's value for `key` (bookspec/README.md), or None
|
||||
/// for a key it doesn't know. A key's `<N>` is event N, whose entry
|
||||
/// `entry_of` gives.
|
||||
pub(crate) fn cash_flow_value(
|
||||
cf: &CashFlowStatement,
|
||||
key: &str,
|
||||
entry_of: &dyn Fn(usize) -> EntryId,
|
||||
) -> Option<Decimal> {
|
||||
let sections = [
|
||||
("operating", CashFlowSection::Operating),
|
||||
("investing", CashFlowSection::Investing),
|
||||
("financing", CashFlowSection::Financing),
|
||||
];
|
||||
let count = |n: usize| Decimal::from(n as u64);
|
||||
Some(match key {
|
||||
"net_change" => cf.net_change_in_cash,
|
||||
"cash_beginning" => cf.cash_beginning,
|
||||
"cash_ending" => cf.cash_ending,
|
||||
"difference" => cf.reconciles.difference,
|
||||
"net_income" => cf.operating_reconciliation.net_income,
|
||||
"noncash.count" => count(cf.noncash_disclosures.len()),
|
||||
_ => {
|
||||
if let Some(&(_, s)) = sections.iter().find(|(k, _)| *k == key) {
|
||||
return Some(cf.total(s));
|
||||
}
|
||||
let (head, tail) = key.split_once('.')?;
|
||||
if head == "noncash" {
|
||||
let n = entry_of(tail.parse().ok()?);
|
||||
return Some(
|
||||
cf.noncash_disclosures
|
||||
.iter()
|
||||
.filter(|d| d.entry == n)
|
||||
.map(|d| d.amount)
|
||||
.sum(),
|
||||
);
|
||||
}
|
||||
if head == "class" {
|
||||
// `class.<a..g>`: the operating class's total (ASC
|
||||
// 230-10-45-25's letters).
|
||||
let c = operating_class(tail)?;
|
||||
return Some(
|
||||
cf.operating_by_class()
|
||||
.into_iter()
|
||||
.filter(|(k, _)| *k == c)
|
||||
.map(|(_, a)| a)
|
||||
.sum(),
|
||||
);
|
||||
}
|
||||
if head == "reconciliation" {
|
||||
let (kind, account) = match tail.split_once('.') {
|
||||
Some((k, a)) => (k, Some(a)),
|
||||
None => (tail, None),
|
||||
};
|
||||
let kind = match kind {
|
||||
"depreciation" => ReconcilingKind::Depreciation,
|
||||
"investing_gain_loss" => ReconcilingKind::InvestingGainLoss,
|
||||
"noncash_through" => ReconcilingKind::NoncashThrough,
|
||||
"other_noncash" => ReconcilingKind::OtherNoncash,
|
||||
"balance_change" => ReconcilingKind::OperatingBalanceChange,
|
||||
_ => return None,
|
||||
};
|
||||
return Some(
|
||||
cf.operating_reconciliation
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|l| l.kind == kind && l.account.as_deref() == account)
|
||||
.map(|l| l.amount)
|
||||
.sum(),
|
||||
);
|
||||
}
|
||||
let &(_, s) = sections.iter().find(|(k, _)| *k == head)?;
|
||||
let lines = cf.lines(s);
|
||||
if tail == "count" {
|
||||
let entries: BTreeSet<EntryId> = lines.iter().map(|l| l.entry).collect();
|
||||
return Some(count(entries.len()));
|
||||
}
|
||||
// `<section>.<N>`, or `<section>.<N>.on_behalf`: of event N's
|
||||
// entry's cash there, what a member or lender handled for the
|
||||
// company.
|
||||
let (n, on_behalf) = match tail.split_once('.') {
|
||||
Some((n, "on_behalf")) => (n, true),
|
||||
Some(_) => return None,
|
||||
None => (tail, false),
|
||||
};
|
||||
let n = entry_of(n.parse().ok()?);
|
||||
lines
|
||||
.iter()
|
||||
.filter(|l| l.entry == n)
|
||||
.map(|l| if on_behalf { l.on_behalf } else { l.amount })
|
||||
.sum()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The operating class ASC 230-10-45-25's letter names.
|
||||
pub(crate) fn operating_class(letter: &str) -> Option<ledger_core::OperatingClass> {
|
||||
use ledger_core::OperatingClass::*;
|
||||
Some(match letter {
|
||||
"a" => FromCustomers,
|
||||
"b" => InterestAndDividendsReceived,
|
||||
"c" => OtherReceipts,
|
||||
"d" => ToSuppliersAndEmployees,
|
||||
"e" => InterestPaid,
|
||||
"f" => IncomeTaxesPaid,
|
||||
"g" => OtherPayments,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The reconciliation key a line answers to.
|
||||
pub(crate) fn reconciliation_key(l: &ledger_core::ReconcilingLine) -> String {
|
||||
let kind = match l.kind {
|
||||
ReconcilingKind::Depreciation => "depreciation",
|
||||
ReconcilingKind::InvestingGainLoss => "investing_gain_loss",
|
||||
ReconcilingKind::NoncashThrough => "noncash_through",
|
||||
ReconcilingKind::OtherNoncash => "other_noncash",
|
||||
ReconcilingKind::OperatingBalanceChange => "balance_change",
|
||||
};
|
||||
match &l.account {
|
||||
Some(a) => format!("reconciliation.{kind}.{a}"),
|
||||
None => format!("reconciliation.{kind}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `cash_flow` expectation, every value it gives.
|
||||
pub(crate) fn check_cash_flow(b: &Books<'_>, x: &Expect) {
|
||||
let (ex, l, members) = (b.ex, b.l(), &b.members);
|
||||
let (start, end) = period(ex, x);
|
||||
let values = x.figures(&ex.id);
|
||||
let params = CashFlowParams {
|
||||
start,
|
||||
end,
|
||||
cash_accounts: codes(l, &ex.setup.cash_accounts, &ex.id),
|
||||
financing_accounts: codes(l, &ex.setup.financing_accounts, &ex.id),
|
||||
investing_accounts: codes(l, &ex.setup.investing_accounts, &ex.id),
|
||||
members: members.to_vec(),
|
||||
};
|
||||
let cf = cash_flow(l, ¶ms).unwrap_or_else(|e| panic!("{}: {e}", ex.id));
|
||||
for (key, want) in values {
|
||||
let want = exact(want, &format!("{} {key}", ex.id));
|
||||
let entry_of = |n: usize| b.entry_of(n, &format!("{} cash_flow {key}", ex.id));
|
||||
let got = cash_flow_value(&cf, key, &entry_of)
|
||||
.unwrap_or_else(|| panic!("{}: unknown cash_flow key {key:?}", ex.id));
|
||||
assert_eq!(
|
||||
got, want,
|
||||
"{} [{} .. {}] {key}",
|
||||
ex.id, params.start, params.end
|
||||
);
|
||||
}
|
||||
// A count given with entries listed: those are all the entries.
|
||||
for section in ["operating", "investing", "financing", "noncash"] {
|
||||
let listed: BTreeSet<&str> = values
|
||||
.keys()
|
||||
.filter_map(|k| k.strip_prefix(section)?.strip_prefix('.'))
|
||||
.filter(|t| *t != "count")
|
||||
.map(|t| t.split_once('.').map_or(t, |(n, _)| n))
|
||||
.collect();
|
||||
if let Some(n) = values.get(&format!("{section}.count"))
|
||||
&& !listed.is_empty()
|
||||
{
|
||||
assert_eq!(
|
||||
Decimal::from(listed.len() as u64),
|
||||
exact(n, &ex.id),
|
||||
"{}: {section}.count against the entries listed",
|
||||
ex.id
|
||||
);
|
||||
}
|
||||
}
|
||||
// Class keys given: every class the statement has is one.
|
||||
if values.keys().any(|k| k.starts_with("class.")) {
|
||||
for (c, amount) in cf.operating_by_class() {
|
||||
let letter = ["a", "b", "c", "d", "e", "f", "g"]
|
||||
.into_iter()
|
||||
.find(|l| operating_class(l) == Some(c))
|
||||
.unwrap();
|
||||
assert!(
|
||||
values.contains_key(&format!("class.{letter}")),
|
||||
"{}: the statement has class.{letter} ({amount}), the example doesn't",
|
||||
ex.id
|
||||
);
|
||||
}
|
||||
}
|
||||
// Reconciliation keys given: every line the statement has is one.
|
||||
if values.keys().any(|k| k.starts_with("reconciliation.")) {
|
||||
for line in &cf.operating_reconciliation.lines {
|
||||
let key = reconciliation_key(line);
|
||||
assert!(
|
||||
values.contains_key(&key),
|
||||
"{}: the statement has {key} ({}), the example doesn't",
|
||||
ex.id,
|
||||
line.amount
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `trial_balance` expectation: each account's balance as of
|
||||
/// the day, debits less credits (a credit balance negative), every
|
||||
/// account listed (rules.md B-6, B-33).
|
||||
pub(crate) fn check_trial_balance(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
let as_of = day(ex, x);
|
||||
let tb = trial_balance_as_of(l, as_of);
|
||||
assert!(tb.balanced(), "{}: the trial balance balances", ex.id);
|
||||
let keys = ex.setup.accounts.iter().map(|a| a.code.clone()).collect();
|
||||
exactly(ex, x, &keys);
|
||||
for (code, want) in x.figures(&ex.id) {
|
||||
let want = exact(want, &format!("{} {code}", ex.id));
|
||||
let got: Decimal = tb
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|t| &t.code == code)
|
||||
.map(|t| t.debit - t.credit)
|
||||
.sum();
|
||||
assert_eq!(got, want, "{} trial balance as of {as_of}: {code}", ex.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `profit_and_loss` expectation: each revenue and expense
|
||||
/// account's activity over the period on its normal side, closing entries
|
||||
/// left out, and `net_income`, revenue less expenses; every revenue and
|
||||
/// expense account listed (rules.md B-14, B-33).
|
||||
pub(crate) fn check_profit_and_loss(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
let (start, end) = period(ex, x);
|
||||
let pl = profit_and_loss_for_period(l, start, end, None)
|
||||
.unwrap_or_else(|e| panic!("{}: {e}", ex.id));
|
||||
let mut keys: BTreeSet<String> = ex
|
||||
.setup
|
||||
.accounts
|
||||
.iter()
|
||||
.filter(|a| matches!(a.kind.as_str(), "revenue" | "expense"))
|
||||
.map(|a| a.code.clone())
|
||||
.collect();
|
||||
keys.insert("net_income".to_string());
|
||||
exactly(ex, x, &keys);
|
||||
for (key, want) in x.figures(&ex.id) {
|
||||
let want = exact(want, &format!("{} {key}", ex.id));
|
||||
let got = if key == "net_income" {
|
||||
pl.net_income()
|
||||
} else {
|
||||
pl.revenue
|
||||
.iter()
|
||||
.chain(&pl.expenses)
|
||||
.filter(|s| &s.code == key)
|
||||
.map(|s| s.amount)
|
||||
.sum()
|
||||
};
|
||||
assert_eq!(
|
||||
got, want,
|
||||
"{} profit and loss [{start} .. {end}]: {key}",
|
||||
ex.id
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `entry` expectation: the lines of event N's entry, `"<code>.debit"` and
|
||||
/// `"<code>.credit"` each summing that account's lines on that side,
|
||||
/// every line of the entry named.
|
||||
pub(crate) fn check_entry(b: &Books<'_>, x: &Expect) {
|
||||
let (ex, l) = (b.ex, b.l());
|
||||
assert!(
|
||||
x.from.is_none() && x.to.is_none() && x.as_of.is_none(),
|
||||
"{}: entry asks about one entry, no dates",
|
||||
ex.id
|
||||
);
|
||||
let n = x
|
||||
.entry
|
||||
.unwrap_or_else(|| panic!("{}: an entry query names its event", ex.id));
|
||||
let entry = l
|
||||
.get_entry(b.entry_of(n, &format!("{} entry {n}", ex.id)))
|
||||
.expect("an entry an event posted");
|
||||
let mut got: BTreeMap<String, Decimal> = BTreeMap::new();
|
||||
for line in entry.lines() {
|
||||
let code = &l.chart().get(line.account).unwrap().code;
|
||||
let side = match line.side {
|
||||
Side::Debit => "debit",
|
||||
Side::Credit => "credit",
|
||||
};
|
||||
*got.entry(format!("{code}.{side}")).or_default() += line.amount.amount;
|
||||
}
|
||||
let keys = got.keys().cloned().collect();
|
||||
exactly(ex, x, &keys);
|
||||
for (key, want) in x.figures(&ex.id) {
|
||||
let want = exact(want, &format!("{} {key}", ex.id));
|
||||
assert_eq!(got[key], want, "{} entry {n}: {key}", ex.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `balances` expectation: each account named, its balance as
|
||||
/// of the day on its normal side (so a member's capital after a loss is
|
||||
/// negative); the accounts named are the example's choice.
|
||||
pub(crate) fn check_balances(ex: &Example, l: &Ledger, x: &Expect) {
|
||||
let as_of = day(ex, x);
|
||||
let tb = trial_balance_as_of(l, as_of);
|
||||
for (code, want) in x.figures(&ex.id) {
|
||||
let want = exact(want, &format!("{} {code}", ex.id));
|
||||
let account = l
|
||||
.chart()
|
||||
.find_by_code(code)
|
||||
.unwrap_or_else(|| panic!("{}: no account {code}", ex.id));
|
||||
let (dr, cr) = tb
|
||||
.lines
|
||||
.iter()
|
||||
.find(|t| &t.code == code)
|
||||
.map_or((Decimal::ZERO, Decimal::ZERO), |t| (t.debit, t.credit));
|
||||
let got = match account.account_type.normal_side() {
|
||||
Side::Debit => dr - cr,
|
||||
Side::Credit => cr - dr,
|
||||
};
|
||||
assert_eq!(got, want, "{} balance as of {as_of}: {code}", ex.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `members_equity` expectation: the statement of changes in
|
||||
/// members' equity over the period, `"<member>.<column>"` for the columns
|
||||
/// `beginning`, `contributions`, `net_income`, `distributions`, `other`
|
||||
/// and `ending`; the figures named are the example's choice (rules.md
|
||||
/// B-13).
|
||||
pub(crate) fn check_members_equity(
|
||||
ex: &Example,
|
||||
l: &Ledger,
|
||||
members: &[MemberCapital],
|
||||
x: &Expect,
|
||||
) {
|
||||
let (from, to) = period(ex, x);
|
||||
assert!(
|
||||
!members.is_empty() && members.iter().all(|m| m.share > Decimal::ZERO),
|
||||
"{}: members_equity needs the members and their shares",
|
||||
ex.id
|
||||
);
|
||||
let st = members_equity(l, from, to, members).unwrap_or_else(|e| panic!("{}: {e}", ex.id));
|
||||
let mut got = BTreeMap::new();
|
||||
for m in &st.members {
|
||||
for (column, v) in [
|
||||
("beginning", m.beginning),
|
||||
("contributions", m.contributions),
|
||||
("net_income", m.net_income),
|
||||
("distributions", m.distributions),
|
||||
("other", m.other),
|
||||
("ending", m.ending),
|
||||
] {
|
||||
got.insert(format!("{}.{column}", m.name), v);
|
||||
}
|
||||
}
|
||||
for (key, want) in x.figures(&ex.id) {
|
||||
let want = exact(want, &format!("{} {key}", ex.id));
|
||||
let got = got
|
||||
.get(key)
|
||||
.unwrap_or_else(|| panic!("{}: members_equity has no {key}", ex.id));
|
||||
assert_eq!(
|
||||
*got, want,
|
||||
"{} members' equity [{from} .. {to}]: {key}",
|
||||
ex.id
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
use crate::*;
|
||||
|
||||
impl Books<'_> {
|
||||
pub(crate) fn answer_k1(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let (from, to) = self.q_period(q)?;
|
||||
let cash = codes(self.l(), &self.ex.setup.cash_accounts, &self.ex.id);
|
||||
let rows = ledger_core::k1::k1_worksheet(self.l(), from, to, &self.members, &cash)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Partner, 1), e))?;
|
||||
let mut m = JsonMap::new();
|
||||
for r in &rows {
|
||||
for (column, v) in [
|
||||
("beginning", r.beginning),
|
||||
("contributions_cash", r.contributions_cash),
|
||||
("contributions_property", r.contributions_property),
|
||||
("net_income", r.net_income),
|
||||
("distributions", r.distributions),
|
||||
("other", r.other),
|
||||
("ending", r.ending),
|
||||
] {
|
||||
m.insert(format!("{}.{column}", r.name), Value::String(figure(v)));
|
||||
}
|
||||
}
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
|
||||
pub(crate) fn tax_rows(
|
||||
&self,
|
||||
from: NaiveDate,
|
||||
to: NaiveDate,
|
||||
) -> Result<Vec<TaxCapitalRow>, Refusal> {
|
||||
let cash = codes(self.l(), &self.ex.setup.cash_accounts, &self.ex.id);
|
||||
ledger_core::tax_capital::tax_basis_capital(self.l(), from, to, &self.members, &cash)
|
||||
.map(|r| r.rows)
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Partner, 4), e))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_k1_tax_basis(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let (from, to) = self.q_period(q)?;
|
||||
let mut m = JsonMap::new();
|
||||
for row in self.tax_rows(from, to)? {
|
||||
let name = &row.book.name;
|
||||
m.insert(
|
||||
format!("{name}.contributions_cash"),
|
||||
Value::String(figure(row.contributions_cash)),
|
||||
);
|
||||
for (line, tax) in [
|
||||
("beginning", &row.beginning),
|
||||
("contributions_property", &row.contributions_property),
|
||||
("net_income", &row.net_income),
|
||||
("other", &row.other),
|
||||
("distributions", &row.distributions),
|
||||
("ending", &row.ending),
|
||||
] {
|
||||
m.insert(
|
||||
format!("{name}.{line}"),
|
||||
Value::String(tax.tax().map_or("open".to_string(), figure)),
|
||||
);
|
||||
m.insert(
|
||||
format!("{name}.known_{line}"),
|
||||
Value::String(figure(tax.known)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
|
||||
pub(crate) fn answer_k1_reconciliation(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let (from, to) = self.q_period(q)?;
|
||||
let mut m = JsonMap::new();
|
||||
for row in self.tax_rows(from, to)? {
|
||||
let r = &row.reconciliation;
|
||||
let total = r.total().ok_or_else(|| {
|
||||
Refusal::new(
|
||||
RuleId::new(Area::Partner, 4),
|
||||
"the reconciliation's total is too large",
|
||||
)
|
||||
})?;
|
||||
for (cause, v) in RECONCILING_CAUSES.into_iter().zip([
|
||||
r.beginning,
|
||||
r.built_in_gain_704c,
|
||||
r.property_without_basis,
|
||||
r.property_distributed,
|
||||
total,
|
||||
]) {
|
||||
m.insert(
|
||||
format!("{}.{cause}", row.book.name),
|
||||
Value::String(figure(v)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
}
|
||||
|
||||
/// Check one `k1` expectation: the K-1 worksheet over the period (rules.md
|
||||
/// B-13; Schedule K-1 Item L), `"<member>.<column>"` for the columns
|
||||
/// `beginning`, `contributions_cash`, `contributions_property`,
|
||||
/// `net_income`, `distributions`, `other` and `ending`; the figures named
|
||||
/// are the example's choice. It needs `cash_accounts` (what is money
|
||||
/// rather than property).
|
||||
pub(crate) fn check_k1(ex: &Example, l: &Ledger, members: &[MemberCapital], x: &Expect) {
|
||||
let (from, to) = period(ex, x);
|
||||
assert!(
|
||||
!members.is_empty() && members.iter().all(|m| m.share > Decimal::ZERO),
|
||||
"{}: k1 needs the members and their shares",
|
||||
ex.id
|
||||
);
|
||||
assert!(
|
||||
!ex.setup.cash_accounts.is_empty(),
|
||||
"{}: k1 needs cash_accounts (what is money rather than property)",
|
||||
ex.id
|
||||
);
|
||||
let cash = codes(l, &ex.setup.cash_accounts, &ex.id);
|
||||
let rows = ledger_core::k1::k1_worksheet(l, from, to, members, &cash)
|
||||
.unwrap_or_else(|e| panic!("{}: {e}", ex.id));
|
||||
let mut got = BTreeMap::new();
|
||||
for r in &rows {
|
||||
for (column, v) in [
|
||||
("beginning", r.beginning),
|
||||
("contributions_cash", r.contributions_cash),
|
||||
("contributions_property", r.contributions_property),
|
||||
("net_income", r.net_income),
|
||||
("distributions", r.distributions),
|
||||
("other", r.other),
|
||||
("ending", r.ending),
|
||||
] {
|
||||
got.insert(format!("{}.{column}", r.name), v);
|
||||
}
|
||||
}
|
||||
for (key, want) in x.figures(&ex.id) {
|
||||
let want = exact(want, &format!("{} {key}", ex.id));
|
||||
let got = got
|
||||
.get(key)
|
||||
.unwrap_or_else(|| panic!("{}: k1 has no {key}", ex.id));
|
||||
assert_eq!(*got, want, "{} K-1 [{from} .. {to}]: {key}", ex.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The tax-basis capital worksheet for `[from, to]` (rules.md B-36), a
|
||||
/// row a member, as `k1` reads the book one: it needs the members and
|
||||
/// their shares, and `cash_accounts`.
|
||||
pub(crate) fn tax_capital_rows(b: &Books<'_>, x: &Expect, what: &str) -> Vec<TaxCapitalRow> {
|
||||
let ex = b.ex;
|
||||
let (from, to) = period(ex, x);
|
||||
assert!(
|
||||
!b.members.is_empty() && b.members.iter().all(|m| m.share > Decimal::ZERO),
|
||||
"{what}: needs the members and their shares"
|
||||
);
|
||||
assert!(
|
||||
!ex.setup.cash_accounts.is_empty(),
|
||||
"{what}: the K-1 worksheet needs cash_accounts"
|
||||
);
|
||||
let cash = codes(b.l(), &ex.setup.cash_accounts, &ex.id);
|
||||
ledger_core::tax_capital::tax_basis_capital(b.l(), from, to, &b.members, &cash)
|
||||
.unwrap_or_else(|e| panic!("{what}: {e}"))
|
||||
.rows
|
||||
}
|
||||
|
||||
/// Check one `k1_tax_basis` expectation: each member's capital account
|
||||
/// for `[from, to]` on the tax basis, as Schedule K-1 Item L reports it
|
||||
/// (rules.md B-36), `"<member>.<line>"` for the lines `beginning`,
|
||||
/// `contributions_cash`, `contributions_property`, `net_income`, `other`,
|
||||
/// `distributions` and `ending`, beside `k1`'s book figures; a line the
|
||||
/// books can't know is `"open"`, with what they know so far as
|
||||
/// `"<member>.known_<line>"`. The example names the figures it shows.
|
||||
pub(crate) fn check_k1_tax_basis(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
let what = format!("{} k1_tax_basis", ex.id);
|
||||
let mut figures = BTreeMap::new();
|
||||
for row in tax_capital_rows(b, x, &what) {
|
||||
let m = &row.book.name;
|
||||
figures.insert(
|
||||
format!("{m}.contributions_cash"),
|
||||
figure(row.contributions_cash),
|
||||
);
|
||||
for (line, tax) in [
|
||||
("beginning", &row.beginning),
|
||||
("contributions_property", &row.contributions_property),
|
||||
("net_income", &row.net_income),
|
||||
("other", &row.other),
|
||||
("distributions", &row.distributions),
|
||||
("ending", &row.ending),
|
||||
] {
|
||||
figures.insert(
|
||||
format!("{m}.{line}"),
|
||||
tax.tax().map_or("open".to_string(), figure),
|
||||
);
|
||||
figures.insert(format!("{m}.known_{line}"), figure(tax.known));
|
||||
}
|
||||
}
|
||||
named(ex, x, &what, &figures);
|
||||
}
|
||||
|
||||
/// The causes `k1_reconciliation` reports, each member's every one.
|
||||
pub(crate) const RECONCILING_CAUSES: [&str; 5] = [
|
||||
"beginning",
|
||||
"built_in_gain_704c",
|
||||
"property_without_basis",
|
||||
"property_distributed",
|
||||
"total",
|
||||
];
|
||||
|
||||
/// Check one `k1_reconciliation` expectation: each member's book capital
|
||||
/// less tax-basis capital at the end of `[from, to]`, by cause (rules.md
|
||||
/// B-36), `"<member>.<cause>"` for `beginning`, `built_in_gain_704c`
|
||||
/// (their share of the §704(c) gain or loss at contribution),
|
||||
/// `property_without_basis`, `property_distributed` and `total`: the
|
||||
/// example names the members it shows, each with every cause.
|
||||
pub(crate) fn check_k1_reconciliation(b: &Books<'_>, x: &Expect) {
|
||||
let ex = b.ex;
|
||||
let what = format!("{} k1_reconciliation", ex.id);
|
||||
let mut figures = BTreeMap::new();
|
||||
for row in tax_capital_rows(b, x, &what) {
|
||||
let r = &row.reconciliation;
|
||||
let total = r
|
||||
.total()
|
||||
.unwrap_or_else(|| panic!("{what}: the total is too large"));
|
||||
for (cause, v) in RECONCILING_CAUSES.into_iter().zip([
|
||||
r.beginning,
|
||||
r.built_in_gain_704c,
|
||||
r.property_without_basis,
|
||||
r.property_distributed,
|
||||
total,
|
||||
]) {
|
||||
figures.insert(format!("{}.{cause}", row.book.name), figure(v));
|
||||
}
|
||||
}
|
||||
let named_members: BTreeSet<&str> = x
|
||||
.figures(&ex.id)
|
||||
.keys()
|
||||
.map(|k| k.split_once('.').map_or(k.as_str(), |(m, _)| m))
|
||||
.collect();
|
||||
for m in named_members {
|
||||
for cause in RECONCILING_CAUSES {
|
||||
assert!(
|
||||
x.figures(&ex.id).contains_key(&format!("{m}.{cause}")),
|
||||
"{what}: {m} is shown with every cause: {m}.{cause} is missing"
|
||||
);
|
||||
}
|
||||
}
|
||||
named(ex, x, &what, &figures);
|
||||
}
|
||||
Reference in new issue
Block a user