diff --git a/crates/ledger-core/src/kernel/schedule.rs b/crates/ledger-core/src/kernel/schedule.rs index 10af9855..7cd5b28c 100644 --- a/crates/ledger-core/src/kernel/schedule.rs +++ b/crates/ledger-core/src/kernel/schedule.rs @@ -1,5 +1,80 @@ //! U5: schedule plans, the monthly charge a schedule books (kernel sweep). //! -//! Empty in U0: the unit adds its arithmetic here, in this file alone, so -//! no two sweep units ever edit the same file. The module root re-exports -//! it, keeping every path `crate::kernel::foo`. +//! `even_parts` is the arithmetic of an equal-months (monthly-even) +//! schedule: the total spread over its months, each month but the last +//! the quotient rounded to the currency's step, the last taking what the +//! others leave. `schedules::amortization_plan` calls it; the date half of +//! a plan (which month end each part books on) stays there. + +use super::{Amount, Rounding, plug_last, round_step}; + +/// Fill `parts` (one slot per month) with the equal-months split of +/// `total`: every part but the last is `total / months` rounded to a whole +/// multiple of `step`, half to even; the last is the total less the +/// others, so the parts sum to `total` exactly. `None` for no months, a +/// step that is not positive, or an amount that cannot be held; `parts` +/// is then unspecified, and the caller discards it. +/// +/// ```text +/// GOAL: an equal-months schedule books exactly its total across its +/// months, each month a whole number of the currency's smallest +/// unit, and no month is ever more than a rounding from the rest. +/// SOURCE: BS-prepaid-1 (a schedule recognizes exactly its total over its +/// months, each month rounded to the currency's minor unit), BS-prepaid-2 +/// (equal months is one of the two methods an engine picks), +/// BS-prepaid-4 (the unit is the currency's minor unit for a new +/// schedule, the cent for one written before the choice: the +/// caller passes the step, never this function), BS-ledger-1 +/// (whole smallest units), BS-entry-3 (exact totals; round only +/// where a rule says to); owner decision D-72; the `plug_last` +/// rule of BS-partner-1 for the remainder. +/// INVARIANTS: +/// 1. Some(()) means the parts sum to `total` exactly, and there are as +/// many parts as months. +/// 2. Every part but the last is equal: `each = round(total / months)` +/// to `step`, half to even (the schedule rule, frozen by replay), so +/// each is a whole multiple of `step`. +/// A single month has no part but the last: it is the whole total, +/// even one finer than the step (the plug takes it; the cent rule +/// always did). +/// 3. `each` is within half a step of the quotient the type's division +/// gives: for `Decimal` that is the exact quotient wherever the +/// division terminates, otherwise the quotient rounded at 28 +/// significant digits (`Amount::checked_div`: the K-U10 item, +/// checked against an exact reference in the bridge), and for a +/// machine integer it is the truncated quotient, so the bound against +/// the true quotient is one unit wider. Lean proves the exact-rational +/// law at any size (`Bookspec.Schedule.each_near`). +/// 4. The last part is `total - (months - 1) x each`, which is `each` +/// plus the rounding the others left: at most `months x step / 2` +/// from `each` (Lean: `Schedule.last_near`). It is therefore not +/// near the others for a long schedule of a coarse step; it is what +/// makes the sum exact. +/// 5. None for no months (`parts` empty), a step <= 0, or overflow; +/// never a panic. The kernel multiplies nothing: the only rounding +/// is `round_step`, which is exact integer arithmetic, and the +/// division's own. The caller keeps `total` below the size Decimal +/// adds exactly (`schedules::EXACT_LIMIT`). +/// SCENARIOS: +/// 1. IF 1,000.00 over 3 months at the cent: SHOULD be 333.33, 333.33, +/// 333.34 +/// BECAUSE the quotient 333.333... rounds down and the last takes +/// the odd cent. +/// 2. IF 100,000 yen over 3 months at one yen: SHOULD be 33,333, 33,333, +/// 33,334; and 1.000 dinar over 3 at 0.001: 0.333, 0.333, 0.334 +/// BECAUSE each month is a whole number of the currency's smallest +/// unit (the cent rule gave 33,333.33 yen and 0.33 dinar). +/// 3. IF 0.01 over 3 months at the cent: SHOULD be 0.00, 0.00, 0.01 +/// BECAUSE the quotient rounds to nothing and the last takes it all. +/// 4. IF there are no months, or the step is zero or negative: SHOULD be +/// None, never a guess. +/// ``` +pub fn even_parts(total: T, step: T, parts: &mut [T]) -> Option<()> { + let months = u32::try_from(parts.len()).ok().filter(|&m| m > 0)?; + let quotient = total.checked_div(T::from_u32(months)?)?; + let each = round_step(quotient, step, Rounding::HalfToEven)?; + for part in parts.iter_mut() { + *part = each; + } + plug_last(total, parts) +} diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index 62e78825..4b94a9ff 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -441,8 +441,22 @@ impl Ledger { /// Register an amortization schedule. Returns its id. pub fn register_schedule(&mut self, new: NewSchedule) -> Result { - schedules::validate_schedule(&new, &self.chart)?; - self.replay_register_schedule(new) + self.register_schedule_under(new, schedules::ScheduleRounding::Cent) + } + + /// [`Self::register_schedule`] for a monthly_even schedule written + /// under `rounding` (D-72, BS-prepaid-4): the store registers new + /// schedules under the currency's minor unit once its books declare + /// the journal feature `schedule_minor_unit`. The plain + /// `register_schedule` is the cent rule, the rule of every schedule + /// before it. + pub fn register_schedule_under( + &mut self, + new: NewSchedule, + rounding: schedules::ScheduleRounding, + ) -> Result { + schedules::validate_schedule_under(&new, rounding, &self.chart)?; + self.replay_register_schedule_under(new, rounding) } /// [`Self::register_schedule`] without the total's range and minor-unit @@ -452,6 +466,17 @@ impl Ledger { pub fn replay_register_schedule( &mut self, new: NewSchedule, + ) -> Result { + self.replay_register_schedule_under(new, schedules::ScheduleRounding::Cent) + } + + /// [`Self::replay_register_schedule`] for a schedule the journal says + /// was written under `rounding` (`schedule.registered`'s `rounding`, + /// absent for every schedule before D-72). + pub fn replay_register_schedule_under( + &mut self, + new: NewSchedule, + rounding: schedules::ScheduleRounding, ) -> Result { schedules::validate_schedule_shape(&new, &self.chart)?; let id = self.next_schedule_id; @@ -469,6 +494,7 @@ impl Ledger { pl_account: new.pl_account, posted: Default::default(), convention: new.convention, + rounding, postings: Default::default(), }, ); diff --git a/crates/ledger-core/src/lib.rs b/crates/ledger-core/src/lib.rs index ec6579bc..74d2a3c4 100644 --- a/crates/ledger-core/src/lib.rs +++ b/crates/ledger-core/src/lib.rs @@ -102,7 +102,7 @@ pub use reports::{ }; pub use schedules::{ AmortizationSchedule, Frequency, NewRecurring, NewSchedule, RecurringEntry, RecurringId, - ScheduleConvention, ScheduleId, ScheduleKind, TemplateLine, + ScheduleConvention, ScheduleId, ScheduleKind, ScheduleRounding, TemplateLine, }; pub use shares::{PartyMember, PartyShare, Share}; pub use tax::{ diff --git a/crates/ledger-core/src/schedules.rs b/crates/ledger-core/src/schedules.rs index 5d76e0c1..e1a118b3 100644 --- a/crates/ledger-core/src/schedules.rs +++ b/crates/ledger-core/src/schedules.rs @@ -90,6 +90,79 @@ impl ScheduleConvention { } } +/// The unit an equal-months (monthly-even) schedule rounds each month to: +/// the rule it was written under (BS-prepaid-4, owner decision D-72). +/// +/// ```text +/// GOAL: a monthly-even schedule's months are whole units of its currency +/// (yen, not 33,333.33 yen), and a schedule written under the old +/// cent rule is never re-planned under a new one. +/// SOURCE: BS-prepaid-4 (new monthly-even schedules round to the +/// currency's minor unit, earlier ones keep the cent rule they +/// were written under), BS-prepaid-1 (months whole to the minor +/// unit), BS-entry-8 (what is journaled never moves); +/// plan/served.md D-72 (owner, 2026-11-08). +/// INVARIANTS: +/// 1. A schedule carries the rule it was written under, journaled on +/// its `schedule.registered` line as `"rounding": "minor_unit"`, +/// and nothing else decides it: not the books' later format, not the +/// currency, not the date. A line with no `rounding` is `Cent`, as +/// every schedule written before D-72 is, and replays exactly as it +/// was posted (the sequence position of the format feature is never +/// consulted: a flag survives a snapshot, a copy and a replay that +/// starts mid-journal; a position survives none of them). +/// 2. `Cent` is two places for every currency, replay-frozen. For a +/// currency with two places, `MinorUnit` gives the same plan +/// (the same call), so a dollar schedule never differs by rule. +/// 3. `MinorUnit` is the currency's ISO 4217 minor unit (`Currency:: +/// minor_units`: USD 0.01, JPY 1, KWD 0.001), and two places for a +/// code ISO gives none (gold, SDRs), as the daily plan does. +/// 4. Only `monthly_even` schedules carry it: a daily schedule always +/// rounds to the minor unit, and is written without the flag. +/// ``` +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ScheduleRounding { + /// Two places, whatever the currency: every schedule written before + /// D-72, and the default of [`crate::Ledger::register_schedule`]. + #[default] + Cent, + /// The currency's minor unit: a monthly-even schedule written after + /// the store's `schedule_minor_unit` feature. + MinorUnit, +} + +impl ScheduleRounding { + /// Its wire name: `cent` or `minor_unit`. + pub fn key(self) -> &'static str { + match self { + ScheduleRounding::Cent => "cent", + ScheduleRounding::MinorUnit => "minor_unit", + } + } + + /// The rule named `key`. + pub fn parse(key: &str) -> Option { + [Self::Cent, Self::MinorUnit] + .into_iter() + .find(|r| r.key() == key) + } + + /// True for [`ScheduleRounding::Cent`] (which the journal and the + /// serialized ledger leave unsaid, as every schedule before D-72 is). + pub fn is_cent(&self) -> bool { + *self == ScheduleRounding::Cent + } + + /// The decimal places each month is rounded to, for `currency`. + pub fn places(self, currency: crate::Currency) -> u32 { + match self { + ScheduleRounding::Cent => 2, + ScheduleRounding::MinorUnit => currency.minor_units().unwrap_or(2), + } + } +} + /// An amortization schedule. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AmortizationSchedule { @@ -119,6 +192,11 @@ pub struct AmortizationSchedule { /// before P3 serialize as they did. #[serde(default, skip_serializing_if = "ScheduleConvention::is_monthly_even")] pub convention: ScheduleConvention, + /// The unit a monthly_even schedule's months round to: the rule it was + /// written under ([`ScheduleRounding`]). Left unsaid when cent, so + /// books from before D-72 serialize as they did. + #[serde(default, skip_serializing_if = "ScheduleRounding::is_cent")] + pub rounding: ScheduleRounding, /// Every entry that ever posted each month, in order: a reversal of /// one un-posts its month, and reversing that reversal posts it again /// (Ledger::reverse_entry). Derived on replay, never serialized. @@ -163,13 +241,17 @@ pub fn month_end(d: NaiveDate) -> NaiveDate { pub const EXACT_LIMIT: Decimal = Decimal::from_parts(0xe400_0000, 0xdcc8_0cd2, 0x0052_b7d2, false, 0); -/// The schedule's monthly postings: (month-end date, amount). Equal -/// amounts to the cent, the last month absorbing rounding, so they sum to -/// the total exactly. +/// The schedule's monthly postings under the cent rule: (month-end date, +/// amount). Equal amounts to the cent, the last month absorbing rounding, +/// so they sum to the total exactly. The rule every schedule written +/// before D-72 replays under ([`ScheduleRounding::Cent`]); a schedule +/// written since rounds to its currency's minor unit +/// ([`amortization_plan_under`]). /// /// ```text /// INVARIANTS: -/// 1. The amounts sum to `total` exactly; all but the last are equal. +/// 1. The amounts sum to `total` exactly; all but the last are equal +/// (kernel::even_parts, at two places). /// 2. NEVER panics: a schedule an earlier version journaled whose months /// run past chrono's last day is refused with DateOutOfRange, and one /// whose amounts exact arithmetic can't hold with TooLargeToCompute @@ -179,6 +261,10 @@ pub const EXACT_LIMIT: Decimal = /// sum of them (none exceeds the total), fits Decimal's 28 significant /// digits, so INVARIANT 1 holds exactly; at it, Decimal's checked /// operations round instead of failing. +/// 4. Unchanged forever: the figures, and the scale they print at, are +/// exactly those every earlier version produced (a posted month's +/// replay compares journaled lines as text). `tests/schedules.rs` +/// checks it against a verbatim copy of the function before K-U5. /// ``` /// /// Replay is unaffected: a posted schedule month passed the line limit @@ -188,40 +274,107 @@ pub fn amortization_plan( total: Decimal, start: NaiveDate, months: u32, +) -> Result, LedgerError> { + plan_in_places(total, 2, start, months) +} + +/// The equal-months plan of `total` under `rounding`: the cent rule +/// ([`amortization_plan`]), or each month a whole number of the currency's +/// minor unit (¥100,000 over 3 months is ¥33,333, ¥33,333, ¥33,334). +/// A currency with two places gives the same plan under both rules. +/// +/// ```text +/// GOAL: an equal-months plan whose months are whole units of its +/// currency. +/// SOURCE: BS-prepaid-1, BS-prepaid-4 (D-72); the arithmetic and its +/// laws are kernel::even_parts (BS-prepaid-1, law 43). +/// INVARIANTS: +/// 1. The amounts sum to `total` exactly; all but the last are equal and +/// a whole multiple of the rule's unit. +/// 2. Under `Cent`, exactly `amortization_plan`; under `MinorUnit` at +/// two places, the same call, so the same figures. +/// 3. Never panics: the refusals are `amortization_plan`'s. +/// ``` +pub fn amortization_plan_under( + rounding: ScheduleRounding, + total: Money, + start: NaiveDate, + months: u32, +) -> Result, LedgerError> { + plan_in_places(total.amount, rounding.places(total.currency), start, months) +} + +/// The equal-months plan to `places` decimal places: the dates, and +/// `kernel::even_parts` for the amounts. +fn plan_in_places( + total: Decimal, + places: u32, + start: NaiveDate, + months: u32, ) -> Result, LedgerError> { let too_large = || LedgerError::TooLargeToCompute(format!("a {months}-month plan of {total}")); if total.abs() >= EXACT_LIMIT { return Err(too_large()); } - // Two places whatever the currency: the monthly-even plan's cent rule is - // replay-frozen, and moving it to the currency's minor unit is K-U5 - // (owner decision D-72), not this behaviour-preserving rounding unit. - let each = kernel::round_places( - total - .checked_div(Decimal::from(months)) - .ok_or_else(too_large)?, - 2, - kernel::Rounding::HalfToEven, - ) - .ok_or_else(too_large)?; let first = start .with_day(1) .ok_or(LedgerError::DateOutOfRange(start))?; - (0..months) + // Every month end first, so a plan running past chrono's last day is + // refused (DateOutOfRange) before a month is allocated. + let ends = (0..months) .map(|i| { - let month = first + first .checked_add_months(Months::new(i)) - .ok_or(LedgerError::DateOutOfRange(start))?; - let amount = if i + 1 == months { - each.checked_mul(Decimal::from(months - 1)) - .and_then(|before| total.checked_sub(before)) - .ok_or_else(too_large)? - } else { - each - }; - Ok((month_end(month), amount)) + .map(month_end) + .ok_or(LedgerError::DateOutOfRange(start)) }) - .collect() + .collect::, _>>()?; + let step = Decimal::try_from_i128_with_scale(1, places).map_err(|_| too_large())?; + let mut parts = vec![Decimal::ZERO; ends.len()]; + kernel::even_parts(total, step, &mut parts).ok_or_else(too_large)?; + present_as_rounded(&mut parts, total, places); + Ok(ends.into_iter().zip(parts).collect()) +} + +/// The scale the plan's figures print at: what `kernel::round_places` and +/// the plan's own subtraction gave every schedule before the kernel +/// computed it. `even_parts` rounds with `round_step`, which returns an +/// amount that is already a whole multiple of the step as it came (so +/// 0.250 stays 0.250) and a zero as a bare 0; the plan has always shown +/// such an amount at `places` places (0.25, 0.00), and a posted month's +/// replay compares its journaled lines as text, so the same figure must +/// print the same. The last month is `total` less the others, whose scale +/// is the wider of the two (or the total's own, when the others are zero). +/// Values never change: every rescale below is +/// to or from trailing zeros, which the debug assertions check. +/// +/// A zero total is never registered (validate_schedule_shape), and a +/// one-month plan is its total; both are left as the kernel gives them. +fn present_as_rounded(parts: &mut [Decimal], total: Decimal, places: u32) { + if total.is_zero() { + return; + } + let Some((last, rest)) = parts.split_last_mut() else { + return; + }; + let Some(&first) = rest.first() else { + return; + }; + let mut each = first; + if each.scale() > places || each.is_zero() { + each.rescale(places); + debug_assert_eq!(each, first, "rescaling an amount never changes it"); + } + // Subtracting a zero (a month that rounded to nothing) leaves the + // total as it was, scale included; any other subtrahend widens it. + if !each.is_zero() { + let before = *last; + last.rescale(total.scale().max(each.scale())); + debug_assert_eq!(*last, before, "rescaling an amount never changes it"); + } + for part in rest.iter_mut() { + *part = each; + } } /// The schedule's postings by the day: one per calendar month the span @@ -286,9 +439,22 @@ pub fn plan_for( total: Money, start: NaiveDate, months: u32, +) -> Result, LedgerError> { + plan_under(ScheduleRounding::Cent, convention, total, start, months) +} + +/// [`plan_for`] for a schedule written under `rounding`: the rule decides +/// only a monthly_even plan's months (a daily plan always rounds to the +/// currency's minor unit). +pub fn plan_under( + rounding: ScheduleRounding, + convention: ScheduleConvention, + total: Money, + start: NaiveDate, + months: u32, ) -> Result, LedgerError> { match convention { - ScheduleConvention::MonthlyEven => amortization_plan(total.amount, start, months), + ScheduleConvention::MonthlyEven => amortization_plan_under(rounding, total, start, months), ScheduleConvention::Daily => daily_plan(total, start, months), } } @@ -317,6 +483,18 @@ pub fn plan_for( /// BECAUSE such a month could never post. /// ``` pub fn validate_schedule(new: &NewSchedule, chart: &ChartOfAccounts) -> Result<(), LedgerError> { + validate_schedule_under(new, ScheduleRounding::Cent, chart) +} + +/// [`validate_schedule`] for a schedule that will be written under +/// `rounding` (the store's choice, by the journal feature +/// `schedule_minor_unit`): under `MinorUnit` a yen schedule's months are +/// whole yen, so ¥1,000 over 3 months (¥333, ¥333, ¥334) is accepted. +pub fn validate_schedule_under( + new: &NewSchedule, + rounding: ScheduleRounding, + chart: &ChartOfAccounts, +) -> Result<(), LedgerError> { validate_schedule_shape(new, chart)?; crate::calendar::check(new.start)?; let past_the_calendar = || { @@ -361,7 +539,7 @@ pub fn validate_schedule(new: &NewSchedule, chart: &ChartOfAccounts) -> Result<( } crate::ledger::check_minor_units(new.total)?; let currency = new.total.currency; - if let Some((_, fine)) = plan_for(new.convention, new.total, new.start, new.months)? + if let Some((_, fine)) = plan_under(rounding, new.convention, new.total, new.start, new.months)? .into_iter() .find(|(_, a)| crate::ledger::check_minor_units(Money::new(*a, currency)).is_err()) { @@ -428,7 +606,13 @@ impl AmortizationSchedule { /// [`daily_plan`]); refused, never a panic, for one that can't be /// computed. pub fn plan(&self) -> Result, LedgerError> { - plan_for(self.convention, self.total, self.start, self.months) + plan_under( + self.rounding, + self.convention, + self.total, + self.start, + self.months, + ) } /// The first day it covers: its start (daily), or the 1st of its start's @@ -723,6 +907,7 @@ mod tests { pl_account: 2, posted: BTreeSet::new(), convention: ScheduleConvention::MonthlyEven, + rounding: ScheduleRounding::Cent, postings: BTreeMap::new(), }; assert!(s.due(NaiveDate::MAX).is_err()); diff --git a/crates/ledger-core/tests/schedule_minor_unit.rs b/crates/ledger-core/tests/schedule_minor_unit.rs new file mode 100644 index 00000000..3d75d502 --- /dev/null +++ b/crates/ledger-core/tests/schedule_minor_unit.rs @@ -0,0 +1,318 @@ +//! Equal-months schedules round to the currency's minor unit (K-U5, D-72, +//! BS-prepaid-4), and a schedule written before that keeps the cent rule. +//! +//! ```text +//! GOAL: a new monthly-even schedule's months are whole units of its +//! currency, while every schedule written under the cent rule +//! replays to the same figures, printed the same way. +//! SOURCE: BS-prepaid-1, BS-prepaid-4, BS-entry-8; plan/served.md D-72. +//! INVARIANTS: +//! 1. The cent rule (`amortization_plan`) is exactly what every earlier +//! version computed: the same amounts at the same printed scale, +//! checked against a verbatim copy of the function as it was. +//! 2. A currency with two places gets the same plan under both rules. +//! 3. Under the minor-unit rule every month is a whole multiple of the +//! currency's unit and the months sum to the total. +//! SCENARIOS: +//! 1. IF 100,000 yen over 3 months, minor unit: SHOULD be 33,333, +//! 33,333, 33,334 (the cent rule: 33,333.33, 33,333.33, 33,333.34). +//! 2. IF 1.000 dinar over 3 months, minor unit: SHOULD be 0.333, 0.333, +//! 0.334 (the cent rule: 0.33, 0.33, 0.340). +//! ``` + +use chrono::{Datelike, Months, NaiveDate}; +use ledger_core::schedules::{ + ScheduleRounding, amortization_plan, amortization_plan_under, month_end, +}; +use ledger_core::{ + AccountType, Currency, Ledger, LedgerError, Money, NewSchedule, ScheduleConvention, + ScheduleKind, kernel, +}; +use proptest::prelude::*; +use rust_decimal::Decimal; + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} + +fn dec(s: &str) -> Decimal { + s.parse().unwrap() +} + +fn kwd() -> Currency { + Currency::new("KWD").unwrap() +} + +fn amounts(plan: &[(NaiveDate, Decimal)]) -> Vec { + plan.iter().map(|(_, a)| a.to_string()).collect() +} + +/// `amortization_plan` verbatim as every version before K-U5 had it +/// (`round_places` at two places, the last month the total less +/// `each x (months - 1)`): the oracle for "the cent rule never moves". +fn legacy_plan( + total: Decimal, + start: NaiveDate, + months: u32, +) -> Result, LedgerError> { + let too_large = || LedgerError::TooLargeToCompute(format!("a {months}-month plan of {total}")); + let each = kernel::round_places( + total + .checked_div(Decimal::from(months)) + .ok_or_else(too_large)?, + 2, + kernel::Rounding::HalfToEven, + ) + .ok_or_else(too_large)?; + let first = start + .with_day(1) + .ok_or(LedgerError::DateOutOfRange(start))?; + (0..months) + .map(|i| { + let month = first + .checked_add_months(Months::new(i)) + .ok_or(LedgerError::DateOutOfRange(start))?; + let amount = if i + 1 == months { + each.checked_mul(Decimal::from(months - 1)) + .and_then(|before| total.checked_sub(before)) + .ok_or_else(too_large)? + } else { + each + }; + Ok((month_end(month), amount)) + }) + .collect() +} + +/// Same dates, same values, and the same text for every amount: a posted +/// month's replay compares its journaled lines as text. +fn assert_same_plan( + got: &[(NaiveDate, Decimal)], + want: &[(NaiveDate, Decimal)], + what: impl std::fmt::Display, +) { + assert_eq!(got.len(), want.len(), "{what}: months"); + for (g, w) in got.iter().zip(want) { + assert_eq!(g.0, w.0, "{what}: date"); + assert_eq!(g.1.to_string(), w.1.to_string(), "{what}: amount text"); + } +} + +/// SCENARIOS 1 and 2, recomputed by hand. +/// +/// 100,000 yen over 3: 100,000 / 3 = 33,333.33..., to a whole yen 33,333; +/// the last month takes 100,000 - 2 x 33,333 = 33,334. 1.000 dinar over 3: +/// 0.3333... to a thousandth 0.333; the last 1.000 - 0.666 = 0.334. A tie +/// goes to the even multiple: 5 yen over 2 is 2.5, to 2 (the last takes 3); +/// 7 over 2 is 3.5, to 4 (the last takes 3, less than the others). +#[test] +fn a_jpy_and_a_kwd_plan_are_whole_units() { + let start = d(2027, 1, 1); + let yen = |a: &str| Money::new(dec(a), Currency::JPY); + let dinar = |a: &str| Money::new(dec(a), kwd()); + let minor = ScheduleRounding::MinorUnit; + let plan = amortization_plan_under(minor, yen("100000"), start, 3).unwrap(); + assert_eq!(amounts(&plan), ["33333", "33333", "33334"]); + assert_eq!( + plan.iter().map(|(m, _)| *m).collect::>(), + [d(2027, 1, 31), d(2027, 2, 28), d(2027, 3, 31)] + ); + let plan = amortization_plan_under(minor, dinar("1.000"), start, 3).unwrap(); + assert_eq!(amounts(&plan), ["0.333", "0.333", "0.334"]); + let plan = amortization_plan_under(minor, yen("5"), start, 2).unwrap(); + assert_eq!(amounts(&plan), ["2", "3"]); + let plan = amortization_plan_under(minor, yen("7"), start, 2).unwrap(); + assert_eq!(amounts(&plan), ["4", "3"]); + // The cent rule, which every schedule before D-72 replays under, is + // unchanged: ¥33,333.33 months no yen account can post. + let cent = amortization_plan(dec("100000"), start, 3).unwrap(); + assert_eq!(amounts(¢), ["33333.33", "33333.33", "33333.34"]); + let cent = amortization_plan(dec("1.000"), start, 3).unwrap(); + assert_eq!(amounts(¢), ["0.33", "0.33", "0.340"]); +} + +/// Prints the numbers the change moves (read with --nocapture): the +/// verification protocol's "show the figures". +#[test] +fn print_the_plans_before_and_after() { + let start = d(2027, 1, 1); + for (label, money) in [ + ("JPY 100000", Money::new(dec("100000"), Currency::JPY)), + ("KWD 1.000", Money::new(dec("1.000"), kwd())), + ("USD 1000.00", Money::new(dec("1000.00"), Currency::USD)), + ] { + let before = amortization_plan(money.amount, start, 3).unwrap(); + let after = amortization_plan_under(ScheduleRounding::MinorUnit, money, start, 3).unwrap(); + println!("{label} over 3 months"); + println!(" cent rule (before): {:?}", amounts(&before)); + println!(" minor unit (after): {:?}", amounts(&after)); + } +} + +/// INVARIANT 1 and 2 over a large range: totals of every scale 0 to 5, +/// months 1 to 40. The cent rule equals the legacy copy value for value +/// and text for text, and a two-place currency gets the same plan under +/// the minor-unit rule (the same call, so this is a check of the claim, +/// not its proof). +#[test] +fn the_cent_rule_is_unchanged_and_usd_is_the_same_under_both_rules() { + let start = d(2027, 3, 1); + let mut checked = 0u64; + for scale in 0..=5u32 { + for mantissa in (1..=1_200i64).chain([9_999, 10_000, 99_999, 123_456_789, 4_000_000_007]) { + let total = Decimal::new(mantissa, scale); + for months in (1..=40u32).chain([360, 600]) { + let want = legacy_plan(total, start, months).unwrap(); + let got = amortization_plan(total, start, months).unwrap(); + assert_same_plan(&got, &want, format!("{total} over {months}")); + if scale <= 2 { + let usd = Money::new(total, Currency::USD); + let under = + amortization_plan_under(ScheduleRounding::MinorUnit, usd, start, months) + .unwrap(); + assert_same_plan(&under, &want, format!("USD {total} over {months}")); + } + checked += 1; + } + } + } + assert!(checked > 300_000, "{checked}"); +} + +/// Under the minor-unit rule, for every 0-, 2-, 3- and 4-place currency: +/// the months sum to the total, all but the last are equal, and each is a +/// whole multiple of the unit. +#[test] +fn the_minor_unit_rule_gives_whole_units_that_sum_to_the_total() { + let start = d(2027, 1, 1); + for (currency, places) in [ + (Currency::JPY, 0u32), + (Currency::USD, 2), + (kwd(), 3), + (Currency::new("CLF").unwrap(), 4), + ] { + for units in (1..=2_000i64).chain([99_991, 1_000_003]) { + let total = Decimal::new(units, places); + for months in 1..=24u32 { + let plan = amortization_plan_under( + ScheduleRounding::MinorUnit, + Money::new(total, currency), + start, + months, + ) + .unwrap(); + let sum: Decimal = plan.iter().map(|(_, a)| *a).sum(); + assert_eq!(sum, total, "{currency} {total} over {months}"); + let each = plan[0].1; + for (_, a) in &plan[..plan.len() - 1] { + assert_eq!(*a, each); + } + for (_, a) in &plan { + assert!(a.normalize().scale() <= places, "{currency} {a}"); + assert!(a.scale() <= places, "{currency} {a} prints past its unit"); + } + } + } + } +} + +proptest! { + /// The cent rule is the legacy rule for any total below the exact + /// limit, at any scale up to 8, and any number of months: values and + /// printed text. + #[test] + fn prop_the_cent_rule_is_the_legacy_rule( + mantissa in 1i128..=99_999_999_999_999_999_999_999_999i128, + scale in 0u32..=8, + months in 1u32..=600, + ) { + let total = Decimal::try_from_i128_with_scale(mantissa, scale).unwrap(); + prop_assume!(total < Decimal::from_i128_with_scale(10i128.pow(25), 0)); + let start = d(2027, 1, 1); + let want = legacy_plan(total, start, months).unwrap(); + let got = amortization_plan(total, start, months).unwrap(); + assert_same_plan(&got, &want, format!("{total} over {months}")); + } +} + +fn ledger_in(currency: Currency) -> (Ledger, u64, u64) { + let mut l = Ledger::new(currency); + let prepaid = l + .add_account("1300", "Prepaid", AccountType::Asset, None, false) + .unwrap(); + let insurance = l + .add_account("6300", "Insurance", AccountType::Expense, None, false) + .unwrap(); + (l, prepaid, insurance) +} + +fn monthly_even(total: Money, prepaid: u64, expense: u64) -> NewSchedule { + NewSchedule { + description: "Insurance".into(), + kind: ScheduleKind::PrepaidExpense, + total, + start: d(2027, 1, 1), + months: 3, + balance_account: prepaid, + pl_account: expense, + convention: ScheduleConvention::MonthlyEven, + } +} + +/// The two registrations side by side: the plain one (the cent rule) +/// still refuses ¥1,000 over 3 months, a schedule registered under the +/// minor-unit rule takes it, plans ¥333, ¥333, ¥334 and carries the rule. +#[test] +fn a_schedule_carries_the_rule_it_was_written_under() { + let yen = |a: &str| Money::new(dec(a), Currency::JPY); + let (mut l, prepaid, expense) = ledger_in(Currency::JPY); + match l.register_schedule(monthly_even(yen("1000"), prepaid, expense)) { + Err(LedgerError::InvalidSchedule(m)) => assert!(m.contains("333.33"), "{m}"), + other => panic!("{other:?}"), + } + let id = l + .register_schedule_under( + monthly_even(yen("1000"), prepaid, expense), + ScheduleRounding::MinorUnit, + ) + .unwrap(); + let s = l.get_schedule(id).unwrap(); + assert_eq!(s.rounding, ScheduleRounding::MinorUnit); + assert_eq!(amounts(&s.plan().unwrap()), ["333", "333", "334"]); + for (m, _) in s.due(d(2027, 12, 31)).unwrap() { + l.post_schedule_month(id, m).unwrap(); + } + assert_eq!(l.get_schedule(id).unwrap().remaining().unwrap(), dec("0")); + // A schedule written the old way, in the same books, still plans in + // cents: a dollar-sized yen total that divides evenly. + let old = l + .register_schedule(monthly_even(yen("900"), prepaid, expense)) + .unwrap(); + let s = l.get_schedule(old).unwrap(); + assert_eq!(s.rounding, ScheduleRounding::Cent); + assert_eq!(amounts(&s.plan().unwrap()), ["300", "300", "300"]); +} + +/// The rule is journaled only when it isn't the cent rule: a serialized +/// ledger from before D-72 reads back as the cent rule, and a cent +/// schedule serializes exactly as it did (no `rounding` key). +#[test] +fn the_cent_rule_is_left_unsaid_in_a_serialized_ledger() { + let (mut l, prepaid, expense) = ledger_in(Currency::USD); + let usd = |a: &str| Money::new(dec(a), Currency::USD); + let old = l + .register_schedule(monthly_even(usd("1000.00"), prepaid, expense)) + .unwrap(); + let new = l + .register_schedule_under( + monthly_even(usd("1000.00"), prepaid, expense), + ScheduleRounding::MinorUnit, + ) + .unwrap(); + let old_json = serde_json::to_value(l.get_schedule(old).unwrap()).unwrap(); + let new_json = serde_json::to_value(l.get_schedule(new).unwrap()).unwrap(); + assert!(old_json.get("rounding").is_none(), "{old_json}"); + assert_eq!(new_json["rounding"], "minor_unit"); + let back: ledger_core::AmortizationSchedule = serde_json::from_value(old_json).unwrap(); + assert_eq!(back.rounding, ScheduleRounding::Cent); +}