Merge branch 'main' into t3/k-u3-kernel-shares
This commit is contained in:
commit
73879044b2
44 files changed
+3908
-241
No files matched your search
@@ -38,6 +38,8 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
|
||||
);
|
||||
only(x.basis.is_some(), "basis", &["party_totals"]);
|
||||
only(x.payee.is_some(), "payee", &["vendor_1099"]);
|
||||
only(x.document.is_some(), "document", &["document_dates"]);
|
||||
only(x.of.is_some(), "of", &["aging"]);
|
||||
only(
|
||||
x.code.is_some(),
|
||||
"code",
|
||||
@@ -101,6 +103,8 @@ pub(crate) fn check(b: &Books<'_>, x: &Expect) -> Option<&'static str> {
|
||||
"party_totals" => check_party_totals(b, x),
|
||||
"party_tin_last4" => check_party_tin_last4(b, x),
|
||||
"project" => check_project(b, x),
|
||||
"aging" => check_aging(b, x),
|
||||
"document_dates" => check_document_dates(b, x),
|
||||
q => {
|
||||
let &(_, by) = FORMAT_QUERIES
|
||||
.iter()
|
||||
|
||||
@@ -143,6 +143,7 @@ pub(crate) fn refusal(e: &LedgerError) -> String {
|
||||
LedgerError::InvalidDepreciationPeriod(_) => "invalid_depreciation_period",
|
||||
LedgerError::InvalidSchedule(_) => "invalid_schedule",
|
||||
LedgerError::UntaggedControlLine { .. } => "untagged_control_line",
|
||||
LedgerError::PaymentBeforeDocument { .. } => "payment_before_document",
|
||||
LedgerError::UnbalancedEntry { .. } => "unbalanced",
|
||||
LedgerError::TooFewLines => "too_few_lines",
|
||||
LedgerError::NegativeAmountLine => "negative_amount",
|
||||
|
||||
@@ -41,6 +41,25 @@ impl Engine for Books<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why wanderbooks does not run `ex`: it is an example for an option of a
|
||||
/// CHOICE rule (`under`) that wanderbooks did not pick (`PICKS`). The
|
||||
/// runner skips such an example for the same reason; the loader tests do
|
||||
/// it with this.
|
||||
pub(crate) fn unpicked_option(ex: &Example) -> Option<String> {
|
||||
ex.under.iter().find_map(|u| {
|
||||
let rule = RuleId::parse(&u.rule).ok()?;
|
||||
let &(_, _, pick) = PICKS
|
||||
.iter()
|
||||
.find(|&&(area, n, _)| RuleId::new(area, n) == rule)?;
|
||||
(pick != u.option).then(|| {
|
||||
format!(
|
||||
"for {} under {}; wanderbooks picks {pick}",
|
||||
u.rule, u.option
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The option wanderbooks picks for each CHOICE record split out of an
|
||||
/// embedded choice (P14 unit S-C7); each is recorded in
|
||||
/// `docs/spec/claims/<area>.md` as `**Pick (BS-<area>-<n>):**`.
|
||||
|
||||
@@ -13,6 +13,7 @@ impl Books<'_> {
|
||||
("bill", e.bill.is_some()),
|
||||
("invoice", e.invoice.is_some()),
|
||||
("write_off", e.write_off.is_some()),
|
||||
("payment", e.payment.is_some()),
|
||||
("run_depreciation", e.run_depreciation.is_some()),
|
||||
("dispose_asset", e.dispose_asset.is_some()),
|
||||
("run_schedules", e.run_schedules.is_some()),
|
||||
@@ -21,7 +22,7 @@ impl Books<'_> {
|
||||
match kinds.iter().filter(|(_, given)| *given).collect::<Vec<_>>()[..] {
|
||||
[(kind, _)] => kind,
|
||||
_ => panic!(
|
||||
"{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, run_depreciation, dispose_asset, run_schedules or register_schedule",
|
||||
"{} event {n}: an event is one of lines, reverses, close, bill, invoice, write_off, payment, run_depreciation, dispose_asset, run_schedules or register_schedule",
|
||||
self.ex.id
|
||||
),
|
||||
}
|
||||
@@ -35,7 +36,7 @@ impl Books<'_> {
|
||||
// disposal is dated; the other commands date their own entries,
|
||||
// and every command describes its own.
|
||||
let own = matches!(kind, "lines" | "reverses" | "close" | "bill" | "invoice");
|
||||
let dated = own || matches!(kind, "dispose_asset" | "write_off");
|
||||
let dated = own || matches!(kind, "dispose_asset" | "write_off" | "payment");
|
||||
assert_eq!(
|
||||
e.date.is_some(),
|
||||
dated,
|
||||
@@ -84,6 +85,10 @@ impl Books<'_> {
|
||||
e.write_off.is_none() || kind == "write_off",
|
||||
"{ex} event {n}: a write_off is its own event"
|
||||
);
|
||||
assert!(
|
||||
e.payment.is_none() || kind == "payment",
|
||||
"{ex} event {n}: a payment is its own event"
|
||||
);
|
||||
}
|
||||
|
||||
/// Take event `n` as the books take it, keep what it posted and tag it
|
||||
@@ -192,11 +197,39 @@ impl Books<'_> {
|
||||
"{what}: entry {id}, which it made, is posted"
|
||||
);
|
||||
}
|
||||
if (own || kind == "write_off") && e.refused.is_none() {
|
||||
if (own || matches!(kind, "write_off" | "payment")) && e.refused.is_none() {
|
||||
assert_eq!(posted.len(), 1, "{what}: {kind} posts one entry");
|
||||
}
|
||||
}
|
||||
|
||||
/// The terms a document's example gives, and the due date the books take
|
||||
/// them to (BS-arap-3): the engine's own `Terms::due_date` for every
|
||||
/// kind, a date the parties agreed ("Due 2026-11-15") included. The
|
||||
/// example's spelling is the canonical one, so the engine must print it
|
||||
/// back as written. Nothing of the date is read out of the text here:
|
||||
/// the example can only pass if the engine computes it. Without terms a
|
||||
/// document is due on its own date.
|
||||
pub(crate) fn terms_due(
|
||||
&self,
|
||||
terms: Option<&str>,
|
||||
date: NaiveDate,
|
||||
what: &str,
|
||||
) -> (NaiveDate, Option<Terms>) {
|
||||
let Some(text) = terms else {
|
||||
return (date, None);
|
||||
};
|
||||
let parsed = Terms::parse(text).unwrap_or_else(|e| panic!("{what}: terms {text:?}: {e}"));
|
||||
assert_eq!(
|
||||
parsed.describe(),
|
||||
text,
|
||||
"{what}: the engine prints terms {text:?} back as written"
|
||||
);
|
||||
let due = parsed
|
||||
.due_date(date)
|
||||
.unwrap_or_else(|e| panic!("{what}: terms {text:?} on {date}: {e}"));
|
||||
(due, Some(parsed))
|
||||
}
|
||||
|
||||
/// An invoice's or bill's lines: `amount` (one line, described as the
|
||||
/// event) or `lines`, exactly one; each project a `setup.projects`
|
||||
/// name.
|
||||
@@ -368,8 +401,18 @@ impl Books<'_> {
|
||||
v
|
||||
}
|
||||
};
|
||||
let (due, terms) = self.terms_due(b.terms.as_deref(), day(), what);
|
||||
self.store
|
||||
.create_bill(vendor, day(), day(), lines)
|
||||
.create_bill_with(
|
||||
vendor,
|
||||
day(),
|
||||
due,
|
||||
lines,
|
||||
BillFields {
|
||||
terms,
|
||||
..BillFields::default()
|
||||
},
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
"invoice" => {
|
||||
@@ -383,8 +426,18 @@ impl Books<'_> {
|
||||
c
|
||||
}
|
||||
};
|
||||
let (due, terms) = self.terms_due(i.terms.as_deref(), day(), what);
|
||||
self.store
|
||||
.create_invoice(customer, day(), day(), lines)
|
||||
.create_invoice_with(
|
||||
customer,
|
||||
day(),
|
||||
due,
|
||||
lines,
|
||||
InvoiceFields {
|
||||
terms,
|
||||
..InvoiceFields::default()
|
||||
},
|
||||
)
|
||||
.map(|_| ())
|
||||
}
|
||||
"write_off" => {
|
||||
@@ -432,6 +485,36 @@ impl Books<'_> {
|
||||
)
|
||||
.map(drop)
|
||||
}
|
||||
"payment" => {
|
||||
let p = e.payment.as_ref().expect("checked: a payment");
|
||||
let entry = self.entry_of(p.document, what);
|
||||
let amount = money(&p.amount);
|
||||
let cash = self.id(&p.account);
|
||||
let invoice = self
|
||||
.store
|
||||
.ledger()
|
||||
.invoices()
|
||||
.into_iter()
|
||||
.find(|i| i.entry_id == entry)
|
||||
.map(|i| i.id);
|
||||
let bill = self
|
||||
.store
|
||||
.ledger()
|
||||
.bills()
|
||||
.into_iter()
|
||||
.find(|b| b.entry_id == entry)
|
||||
.map(|b| b.id);
|
||||
match (invoice, bill) {
|
||||
(Some(invoice), _) => self
|
||||
.store
|
||||
.receive_payment(invoice, day(), amount, cash)
|
||||
.map(drop),
|
||||
(None, Some(bill)) => self.store.pay_bill(bill, day(), amount, cash).map(drop),
|
||||
(None, None) => {
|
||||
panic!("{what}: event {} posted no invoice or bill", p.document)
|
||||
}
|
||||
}
|
||||
}
|
||||
"run_depreciation" => {
|
||||
let r = e.run_depreciation.as_ref().expect("checked: a run");
|
||||
let asset = self.asset(&r.asset, what);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::engine::unpicked_option;
|
||||
use crate::*;
|
||||
|
||||
/// The `Engine` adapter over `Store` runs every example through the
|
||||
@@ -17,6 +18,40 @@ pub(crate) fn the_runner_reports_every_claimed_rule_green() {
|
||||
"the runner is not green:\n{}",
|
||||
report.failures().join("\n")
|
||||
);
|
||||
// An example for an option wanderbooks did not pick is not run; every
|
||||
// other one is, and passes.
|
||||
let skipped = report.skipped();
|
||||
let unpicked: Vec<&str> = examples
|
||||
.iter()
|
||||
.filter(|ex| unpicked_option(ex).is_some())
|
||||
.map(|ex| ex.id.as_str())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
skipped.len(),
|
||||
unpicked.len(),
|
||||
"the runner skips exactly the examples for unpicked options: {skipped:?}"
|
||||
);
|
||||
for id in &unpicked {
|
||||
assert!(
|
||||
skipped.iter().any(|s| s.starts_with(&format!("{id}:"))),
|
||||
"{id} is skipped"
|
||||
);
|
||||
}
|
||||
let ran = report.examples.len() - skipped.len();
|
||||
let passed = report
|
||||
.examples
|
||||
.iter()
|
||||
.filter(|e| e.skipped.is_none() && e.failure.is_none())
|
||||
.count();
|
||||
eprintln!(
|
||||
"bookspec runner: {} examples, {ran} run, {passed} passed, {} skipped (an option wanderbooks did not pick)",
|
||||
report.examples.len(),
|
||||
skipped.len()
|
||||
);
|
||||
for s in &skipped {
|
||||
eprintln!(" skipped {s}");
|
||||
}
|
||||
assert_eq!(ran, passed, "every example run passed");
|
||||
for rule in bookspec_checker::covered_rules() {
|
||||
assert_eq!(
|
||||
report.rules.get(&rule.id),
|
||||
@@ -39,6 +74,7 @@ pub(crate) fn every_bookspec_example_holds() {
|
||||
let files = bookspec_checker::examples();
|
||||
let mut ids = BTreeSet::new();
|
||||
let mut checked: BTreeMap<String, usize> = BTreeMap::new();
|
||||
let mut skipped = Vec::new();
|
||||
for (name, text) in &files {
|
||||
let ex = Example::from_toml(text).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
let stem = name.strip_suffix(".toml").unwrap();
|
||||
@@ -57,6 +93,12 @@ pub(crate) fn every_bookspec_example_holds() {
|
||||
);
|
||||
assert!(!ex.sources.is_empty(), "{}: every rule is sourced", ex.id);
|
||||
assert!(!ex.expect.is_empty(), "{}: something to expect", ex.id);
|
||||
// The examples for an option wanderbooks did not pick are for
|
||||
// another engine; they are read (above) and not run.
|
||||
if let Some(why) = unpicked_option(&ex) {
|
||||
skipped.push(format!("{} {why}", ex.id));
|
||||
continue;
|
||||
}
|
||||
for (q, by) in run(&ex) {
|
||||
if let Some(by) = by {
|
||||
eprintln!("{}: {q} is checked by {by}", ex.id);
|
||||
@@ -102,8 +144,24 @@ pub(crate) fn every_bookspec_example_holds() {
|
||||
("k1_tax_basis", 4),
|
||||
("k1_reconciliation", 2),
|
||||
("project", 6),
|
||||
("aging", 4),
|
||||
("document_dates", 8),
|
||||
] {
|
||||
let n = checked.get(q).copied().unwrap_or(0);
|
||||
assert!(n >= at_least, "{q} ran {n} times, fewer than {at_least}");
|
||||
}
|
||||
eprintln!(
|
||||
"bookspec examples: {} files, {} run, {} skipped (an option wanderbooks did not pick): {skipped:?}",
|
||||
files.len(),
|
||||
files.len() - skipped.len(),
|
||||
skipped.len()
|
||||
);
|
||||
// The examples for an option wanderbooks did not pick: the other option
|
||||
// of BS-arap-7, -8 and -9, BS-prepaid-2's equal-months and BS-ledger-20's
|
||||
// refuse (each option's example, so no allow-list grows).
|
||||
assert_eq!(
|
||||
skipped.len(),
|
||||
5,
|
||||
"the five unpicked-option examples: {skipped:?}"
|
||||
);
|
||||
}
|
||||
@@ -50,13 +50,13 @@ pub(crate) use ledger_core::parties::{Basis, MoneyAccounts};
|
||||
pub(crate) use ledger_core::settings::{Company, Source};
|
||||
pub(crate) use ledger_core::tax_capital::TaxCapitalRow;
|
||||
pub(crate) use ledger_core::{
|
||||
AccountType, AssetId, CashFlowParams, CashFlowSection, CashFlowStatement, CloseTo, Currency,
|
||||
Dated1099, Decision1099, DocumentLine, EntryId, EntryStatus, ExemptReason, Form1099,
|
||||
InstrumentId, InstrumentKind, Ledger, LedgerError, MemberCapital, MemberClose, Money, NewAsset,
|
||||
NewSchedule, PartyId, PartyMember, PartyShare, PaymentAccounts, ReconcilingKind, Role,
|
||||
ScheduleConvention, ScheduleId, ScheduleKind, Share, Side, TinFacts, TinType, VendorId,
|
||||
W9Facts, cash_flow, members_equity, profit_and_loss_for_period, trial_balance_as_of,
|
||||
vendor_1099_report,
|
||||
AccountType, AssetId, BillFields, CashFlowParams, CashFlowSection, CashFlowStatement, CloseTo,
|
||||
Currency, Dated1099, Decision1099, DocumentLine, EntryId, EntryStatus, ExemptReason, Form1099,
|
||||
InstrumentId, InstrumentKind, InvoiceFields, Ledger, LedgerError, MemberCapital, MemberClose,
|
||||
Money, NewAsset, NewSchedule, PartyId, PartyMember, PartyShare, PaymentAccounts,
|
||||
ReconcilingKind, Role, ScheduleConvention, ScheduleId, ScheduleKind, Share, Side, Terms,
|
||||
TinFacts, TinType, VendorId, W9Facts, cash_flow, members_equity, profit_and_loss_for_period,
|
||||
trial_balance_as_of, vendor_1099_report,
|
||||
};
|
||||
pub(crate) use ledger_store::{DepreciationRun, DisposalPreview, Store, StoreError};
|
||||
pub(crate) use rust_decimal::Decimal;
|
||||
@@ -75,6 +75,7 @@ pub(crate) use common::*;
|
||||
pub(crate) use queries::assets::*;
|
||||
pub(crate) use queries::commands::*;
|
||||
pub(crate) use queries::dates::*;
|
||||
pub(crate) use queries::documents::*;
|
||||
pub(crate) use queries::formats::*;
|
||||
pub(crate) use queries::parties::*;
|
||||
pub(crate) use queries::statements::*;
|
||||
@@ -95,3 +96,4 @@ mod rules_md;
|
||||
mod run;
|
||||
mod source_refs;
|
||||
mod sources;
|
||||
mod traceability;
|
||||
@@ -0,0 +1,98 @@
|
||||
use crate::*;
|
||||
|
||||
/// The buckets of an aging, as the examples key them (BS-arap-1), beside
|
||||
/// the engine's `AgingRow` fields they read.
|
||||
const BUCKETS: [&str; 5] = ["current", "1-30", "31-60", "61-90", "90+"];
|
||||
|
||||
impl Books<'_> {
|
||||
/// The engine's `ar_aging` or `ap_aging` as of the day (BS-arap-1): the
|
||||
/// buckets in total, `total`, and each party's buckets, read straight
|
||||
/// from the engine's rows, never recomputed here.
|
||||
pub(crate) fn answer_aging(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let as_of = self.q_day(q)?;
|
||||
let rows = match q.of.as_deref() {
|
||||
Some("receivables") => self.l().ar_aging(as_of),
|
||||
Some("payables") => self.l().ap_aging(as_of),
|
||||
_ => return Err(self.missing("receivables or payables")),
|
||||
}
|
||||
.map_err(|e| engine_refusal(RuleId::new(Area::Arap, 1), e))?;
|
||||
let mut m = JsonMap::new();
|
||||
let mut totals = [Decimal::ZERO; 5];
|
||||
for row in &rows {
|
||||
let buckets = [
|
||||
row.current,
|
||||
row.days_30,
|
||||
row.days_60,
|
||||
row.days_90,
|
||||
row.days_90_plus,
|
||||
];
|
||||
for ((name, owed), total) in BUCKETS.iter().zip(buckets).zip(totals.iter_mut()) {
|
||||
m.insert(format!("{}.{name}", row.name), Value::String(figure(owed)));
|
||||
*total += owed;
|
||||
}
|
||||
}
|
||||
for (name, total) in BUCKETS.iter().zip(totals) {
|
||||
m.insert(name.to_string(), Value::String(figure(total)));
|
||||
}
|
||||
m.insert(
|
||||
"total".to_string(),
|
||||
Value::String(figure(totals.iter().copied().sum())),
|
||||
);
|
||||
Ok(Value::Object(m))
|
||||
}
|
||||
|
||||
/// The due date and discount date the document event's terms give
|
||||
/// (BS-arap-3), as the engine stored the document and its terms.
|
||||
pub(crate) fn answer_document_dates(&self, q: &Query) -> Result<Value, Refusal> {
|
||||
let n = q.document.ok_or_else(|| self.missing("document"))?;
|
||||
let entry = self.entry_or_refuse(n)?;
|
||||
let l = self.l();
|
||||
let (date, due, terms) = match (
|
||||
l.invoices().into_iter().find(|i| i.entry_id == entry),
|
||||
l.bills().into_iter().find(|b| b.entry_id == entry),
|
||||
) {
|
||||
(Some(i), _) => (i.date, i.due_date, i.terms.clone()),
|
||||
(None, Some(b)) => (b.date, b.due_date, b.terms.clone()),
|
||||
(None, None) => return Err(self.missing("invoice or bill")),
|
||||
};
|
||||
let discount_by = terms
|
||||
.and_then(|t| t.discount_by(date))
|
||||
.map_or_else(|| "none".to_string(), |d| d.to_string());
|
||||
Ok(json_figures([
|
||||
("due".to_string(), due.to_string()),
|
||||
("discount_by".to_string(), discount_by),
|
||||
]))
|
||||
}
|
||||
}
|
||||
|
||||
/// Check an `aging` expectation: every figure the engine gives, and no
|
||||
/// other (the example lists everything it covers).
|
||||
pub(crate) fn check_aging(b: &Books<'_>, x: &Expect) {
|
||||
check_figures(b, x, b.answer_aging(&x.query()));
|
||||
}
|
||||
|
||||
/// Check a `document_dates` expectation: `due` and `discount_by`, both
|
||||
/// given.
|
||||
pub(crate) fn check_document_dates(b: &Books<'_>, x: &Expect) {
|
||||
check_figures(b, x, b.answer_document_dates(&x.query()));
|
||||
}
|
||||
|
||||
fn check_figures(b: &Books<'_>, x: &Expect, answer: Result<Value, Refusal>) {
|
||||
let ex = b.ex;
|
||||
let Value::Object(got) =
|
||||
answer.unwrap_or_else(|r| panic!("{}: {}: {}", ex.id, x.query, r.reason))
|
||||
else {
|
||||
panic!("{}: {} answers a table", ex.id, x.query)
|
||||
};
|
||||
let keys: BTreeSet<String> = got.keys().cloned().collect();
|
||||
exactly(ex, x, &keys);
|
||||
for (key, want) in x.figures(&ex.id) {
|
||||
assert_eq!(
|
||||
got[key].as_str(),
|
||||
Some(want.as_str()),
|
||||
"{}: {} {key}",
|
||||
ex.id,
|
||||
x.query
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ use crate::*;
|
||||
pub(crate) mod assets;
|
||||
pub(crate) mod commands;
|
||||
pub(crate) mod dates;
|
||||
pub(crate) mod documents;
|
||||
pub(crate) mod formats;
|
||||
pub(crate) mod parties;
|
||||
pub(crate) mod statements;
|
||||
@@ -84,6 +85,8 @@ impl Books<'_> {
|
||||
"party_totals" => self.answer_party_totals(q),
|
||||
"party_tin_last4" => self.answer_party_tin_last4(q),
|
||||
"project" => self.answer_project(q),
|
||||
"aging" => self.answer_aging(q),
|
||||
"document_dates" => self.answer_document_dates(q),
|
||||
"run" => self.answer_run(q),
|
||||
"disposal" => self.answer_disposal(q),
|
||||
"depreciation_schedule" => self.answer_depreciation_schedule(q),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,42 @@
|
||||
//! U8 bridge properties: control and aging (kernel sweep).
|
||||
//!
|
||||
//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here,
|
||||
//! beside `main.rs` and the other units.
|
||||
//! `kernel::running_bounds` and `kernel::bounds_kept` at `i64` cents (what
|
||||
//! Kani proves, law 34) against the same on `Decimal` (what the engine
|
||||
//! runs), on random documents.
|
||||
|
||||
use super::{arb_cents, dec};
|
||||
use ledger_core::kernel;
|
||||
use proptest::prelude::*;
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(1000))]
|
||||
|
||||
/// The same running balances are within bounds, or leave them at the
|
||||
/// same step, at both types.
|
||||
#[test]
|
||||
fn running_bounds_agree(
|
||||
total in arb_cents(),
|
||||
deltas in prop::collection::vec(arb_cents(), 0..7),
|
||||
) {
|
||||
let wide: Vec<_> = deltas.iter().map(|&c| dec(c)).collect();
|
||||
prop_assert_eq!(
|
||||
kernel::running_bounds(total, &deltas),
|
||||
kernel::running_bounds(dec(total), &wide)
|
||||
);
|
||||
}
|
||||
|
||||
/// The same step keeps (or breaks) a document's bounds at both types.
|
||||
#[test]
|
||||
fn bounds_kept_agree(
|
||||
total in arb_cents(),
|
||||
before in prop::collection::vec(arb_cents(), 0..7),
|
||||
after in prop::collection::vec(arb_cents(), 0..7),
|
||||
) {
|
||||
let wide_before: Vec<_> = before.iter().map(|&c| dec(c)).collect();
|
||||
let wide_after: Vec<_> = after.iter().map(|&c| dec(c)).collect();
|
||||
prop_assert_eq!(
|
||||
kernel::bounds_kept(total, &before, &after),
|
||||
kernel::bounds_kept(dec(total), &wide_before, &wide_after)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! Entries bridge properties: the small amount-generic pieces the
|
||||
//! statement of cash flows builds on.
|
||||
//!
|
||||
//! `kernel::take`, `entry_movements` and `flows_of` at `i64` cents (what
|
||||
//! Kani proves, law 10) against the same on `Decimal` (what the engine
|
||||
//! runs), on random lines.
|
||||
|
||||
use super::{arb_cents, dec};
|
||||
use ledger_core::Side;
|
||||
use ledger_core::kernel::{self, Flow};
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn arb_flow() -> impl Strategy<Value = Flow> {
|
||||
prop_oneof![
|
||||
Just(Flow::Cash),
|
||||
Just(Flow::Operating),
|
||||
Just(Flow::Investing),
|
||||
Just(Flow::Financing),
|
||||
]
|
||||
}
|
||||
|
||||
fn arb_side() -> impl Strategy<Value = Side> {
|
||||
prop_oneof![Just(Side::Debit), Just(Side::Credit)]
|
||||
}
|
||||
|
||||
fn arb_flow_lines() -> impl Strategy<Value = Vec<(Flow, Side, i64)>> {
|
||||
prop::collection::vec((arb_flow(), arb_side(), arb_cents()), 0..6)
|
||||
}
|
||||
|
||||
fn to_dec(lines: &[(Flow, Side, i64)]) -> Vec<(Flow, Side, rust_decimal::Decimal)> {
|
||||
lines.iter().map(|&(f, s, a)| (f, s, dec(a))).collect()
|
||||
}
|
||||
|
||||
fn arb_direction() -> impl Strategy<Value = kernel::Direction> {
|
||||
prop_oneof![
|
||||
Just(kernel::Direction::Paid),
|
||||
Just(kernel::Direction::Received),
|
||||
Just(kernel::Direction::Neither),
|
||||
]
|
||||
}
|
||||
|
||||
/// Cents, plus the `i64` range's edges: [`arb_cents`] is bounded to ±2^40
|
||||
/// (what a journal line may carry), so it never reaches the negation that
|
||||
/// overflows, and the refusal path would go untested.
|
||||
fn arb_edge_cents() -> impl Strategy<Value = i64> {
|
||||
prop_oneof![arb_cents(), Just(i64::MIN), Just(i64::MAX)]
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(1000))]
|
||||
|
||||
/// `kernel::take` takes the same part of a movement at both types.
|
||||
#[test]
|
||||
fn take_agrees(remaining in arb_cents(), movement in arb_cents()) {
|
||||
prop_assert_eq!(
|
||||
kernel::take(remaining, movement).map(dec),
|
||||
kernel::take(dec(remaining), dec(movement))
|
||||
);
|
||||
}
|
||||
|
||||
/// `kernel::entry_movements` nets the cash and each section the same.
|
||||
#[test]
|
||||
fn entry_movements_agree(lines in arb_flow_lines()) {
|
||||
let i = kernel::entry_movements(&lines)
|
||||
.map(|(cash, moved)| (dec(cash), moved.map(dec)));
|
||||
let d = kernel::entry_movements(&to_dec(&lines));
|
||||
prop_assert_eq!(i, d);
|
||||
}
|
||||
|
||||
/// `kernel::flows_of` splits the cash the same, and refuses the same
|
||||
/// lines that do not net to zero.
|
||||
#[test]
|
||||
fn flows_of_agree(
|
||||
cash in arb_cents(),
|
||||
moved in (arb_cents(), arb_cents(), arb_cents())
|
||||
.prop_map(|(a, b, c)| [a, b, c]),
|
||||
) {
|
||||
let i = kernel::flows_of(cash, moved);
|
||||
let d = kernel::flows_of(dec(cash), moved.map(dec));
|
||||
prop_assert_eq!(
|
||||
i.map(|f| (dec(f.cash), f.flows.map(dec), f.noncash.map(dec))),
|
||||
d.map(|f| (f.cash, f.flows, f.noncash))
|
||||
);
|
||||
}
|
||||
|
||||
/// `kernel::catch_ups` gives every suffix's catch-up at both types.
|
||||
#[test]
|
||||
fn catch_ups_agree(
|
||||
pairs in prop::collection::vec((arb_cents(), arb_cents()), 0..6),
|
||||
) {
|
||||
let scheduled: Vec<i64> = pairs.iter().map(|&(s, _)| s).collect();
|
||||
let posted: Vec<i64> = pairs.iter().map(|&(_, p)| p).collect();
|
||||
let mut i = vec![0i64; scheduled.len()];
|
||||
let mut d = vec![dec(0); scheduled.len()];
|
||||
let ri = kernel::catch_ups(&scheduled, &posted, &mut i);
|
||||
let rd = kernel::catch_ups(
|
||||
&scheduled.iter().map(|&c| dec(c)).collect::<Vec<_>>(),
|
||||
&posted.iter().map(|&c| dec(c)).collect::<Vec<_>>(),
|
||||
&mut d,
|
||||
);
|
||||
prop_assert_eq!(ri, rd);
|
||||
prop_assert_eq!(i.into_iter().map(dec).collect::<Vec<_>>(), d);
|
||||
}
|
||||
|
||||
/// `kernel::unrecovered_cost` is the same shortfall at both types.
|
||||
#[test]
|
||||
fn unrecovered_cost_agree(revenue in arb_cents(), expenses in arb_cents()) {
|
||||
prop_assert_eq!(
|
||||
kernel::unrecovered_cost(revenue, expenses).map(dec),
|
||||
kernel::unrecovered_cost(dec(revenue), dec(expenses))
|
||||
);
|
||||
}
|
||||
|
||||
/// `kernel::Direction::of` classifies the same sign at both types, and
|
||||
/// each case keeps its meaning (law 23).
|
||||
#[test]
|
||||
fn direction_of_agrees(cents in arb_cents()) {
|
||||
let i = kernel::Direction::of(cents);
|
||||
let d = kernel::Direction::of(dec(cents));
|
||||
prop_assert_eq!(i, d);
|
||||
if cents > 0 {
|
||||
prop_assert_eq!(i, kernel::Direction::Paid);
|
||||
} else if cents < 0 {
|
||||
prop_assert_eq!(i, kernel::Direction::Received);
|
||||
} else {
|
||||
prop_assert_eq!(i, kernel::Direction::Neither);
|
||||
}
|
||||
}
|
||||
|
||||
/// `kernel::reverse_target` is the exact opposite at both types, and
|
||||
/// `i64` refuses its range's edge (`i64::MIN`, which no negation can
|
||||
/// hold): the edge strategy reaches that arm, and Decimal, which can
|
||||
/// hold the negation, answers the opposite (law 24). The refusal is
|
||||
/// the integer proof model's bound, not the law's.
|
||||
#[test]
|
||||
fn reverse_target_agrees(
|
||||
amount in arb_edge_cents(),
|
||||
cash in arb_edge_cents(),
|
||||
in_kind in arb_edge_cents(),
|
||||
direction in arb_direction(),
|
||||
) {
|
||||
let t = kernel::PartyTarget {
|
||||
amount,
|
||||
direction,
|
||||
cash,
|
||||
in_kind,
|
||||
};
|
||||
let d = kernel::PartyTarget {
|
||||
amount: dec(amount),
|
||||
direction,
|
||||
cash: dec(cash),
|
||||
in_kind: dec(in_kind),
|
||||
};
|
||||
let as_dec = |r: kernel::PartyTarget<i64>| kernel::PartyTarget {
|
||||
amount: dec(r.amount),
|
||||
direction: r.direction,
|
||||
cash: dec(r.cash),
|
||||
in_kind: dec(r.in_kind),
|
||||
};
|
||||
match kernel::reverse_target(t) {
|
||||
Some(r) => prop_assert_eq!(Some(as_dec(r)), kernel::reverse_target(d)),
|
||||
None => {
|
||||
prop_assert!(
|
||||
amount == i64::MIN || cash == i64::MIN || in_kind == i64::MIN,
|
||||
"reverse_target refused an in-range target"
|
||||
);
|
||||
prop_assert_eq!(
|
||||
kernel::reverse_target(d),
|
||||
Some(kernel::PartyTarget {
|
||||
amount: -dec(amount),
|
||||
direction: direction.flip(),
|
||||
cash: -dec(cash),
|
||||
in_kind: -dec(in_kind),
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `kernel::part_weight` is the same weight at i32, i64 and i128, and
|
||||
/// `None` exactly for a part no calendar month has (laws 26-28).
|
||||
#[test]
|
||||
fn part_weight_agrees(month_days in 0u32..=40, days in 0u32..=40) {
|
||||
let part = kernel::MonthPart { days, month_days };
|
||||
let w32: Option<i32> = kernel::part_weight(part);
|
||||
let w64: Option<i64> = kernel::part_weight(part);
|
||||
let w128: Option<i128> = kernel::part_weight(part);
|
||||
prop_assert_eq!(w64, w32.map(i64::from));
|
||||
prop_assert_eq!(w128, w64.map(i128::from));
|
||||
if part.is_valid() {
|
||||
prop_assert_eq!(
|
||||
w64,
|
||||
Some(i64::from(days) * i64::from(kernel::MONTH_L / month_days))
|
||||
);
|
||||
} else {
|
||||
prop_assert_eq!(w64, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
// One file per kernel-sweep unit; the properties above stay here.
|
||||
mod allocate;
|
||||
mod control;
|
||||
mod entries;
|
||||
mod fx;
|
||||
mod payroll;
|
||||
mod ratio;
|
||||
|
||||
@@ -1637,6 +1637,60 @@ fn doc_line(
|
||||
}
|
||||
}
|
||||
|
||||
/// BS-arap-3 statement 1: custom terms are due on the date they give, not
|
||||
/// on the document's own date. A document dated 2026-11-01 on "Due
|
||||
/// 2026-11-15" is due on the 15th (through Terms::due_date and through the
|
||||
/// stored document); an agreed date before the document's is refused like
|
||||
/// any due date before its document; terms read back from storage (even
|
||||
/// written before they carried the date) keep the date.
|
||||
#[test]
|
||||
fn custom_terms_are_due_on_the_date_they_give() {
|
||||
let on = d(2026, 11, 1);
|
||||
let agreed = d(2026, 11, 15);
|
||||
let terms = Terms::parse("Due 2026-11-15").unwrap();
|
||||
assert_eq!(terms.agreed_date(), Some(agreed));
|
||||
assert_eq!(terms.due_date(on).unwrap(), agreed);
|
||||
// The same, whichever day the document is dated (up to the 15th).
|
||||
assert_eq!(terms.due_date(d(2026, 11, 15)).unwrap(), agreed);
|
||||
assert_eq!(terms.due_date(d(2026, 1, 3)).unwrap(), agreed);
|
||||
// Dated after the agreed day, the terms contradict the document.
|
||||
assert!(terms.due_date(d(2026, 11, 16)).is_err());
|
||||
// Other kinds give no agreed date.
|
||||
assert_eq!(Terms::parse("Net 30").unwrap().agreed_date(), None);
|
||||
|
||||
// Through the engine: an invoice and a bill on those terms.
|
||||
let mut b = books();
|
||||
let invoice =
|
||||
b.l.create_invoice_with(
|
||||
b.customer,
|
||||
on,
|
||||
terms.due_date(on).unwrap(),
|
||||
line("Work", 10_000),
|
||||
InvoiceFields {
|
||||
terms: Some(terms.clone()),
|
||||
..InvoiceFields::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let stored = b.l.get_invoice(invoice).unwrap();
|
||||
assert_eq!(stored.due_date, agreed);
|
||||
assert_eq!(stored.terms.as_ref().unwrap().describe(), "Due 2026-11-15");
|
||||
|
||||
// Storage round-trips the date; an older stored form, which had the
|
||||
// text only, reads back with the date from its text.
|
||||
let json = serde_json::to_value(&terms).unwrap();
|
||||
assert_eq!(json["agreed"], "2026-11-15");
|
||||
assert_eq!(serde_json::from_value::<Terms>(json).unwrap(), terms);
|
||||
let old = serde_json::json!({"kind": "custom", "text": "Due 2026-11-15"});
|
||||
assert_eq!(serde_json::from_value::<Terms>(old).unwrap(), terms);
|
||||
// Custom terms with no readable date are refused, not invented.
|
||||
let none = serde_json::json!({"kind": "custom", "text": "Due"});
|
||||
assert!(serde_json::from_value::<Terms>(none).is_err());
|
||||
// A date on any other kind is refused.
|
||||
let stray = serde_json::json!({"kind": {"net": 30}, "text": "Net 30", "agreed": "2026-11-15"});
|
||||
assert!(serde_json::from_value::<Terms>(stray).is_err());
|
||||
}
|
||||
|
||||
/// BS-arap-3 SCENARIOS: Net 30, Net 15 EOM, a leap day, due on receipt, a
|
||||
/// custom date, and the 9999-12 bound refused instead of panicking.
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user