Lines
97.4 %
Functions
86.67 %
Branches
100 %
//! Conservative inversion of the forward lowering: physical splits and price
//! rows back into logical from→to rows.
//!
//! The lowering stores no link between a row's two splits, so pairing is
//! only accepted when it is provable; anything ambiguous is an error rather
//! than a guess.
use std::collections::{BTreeMap, HashMap, HashSet};
use finance::{price::Price, split::Split};
use num_rational::Rational64;
use sqlx::types::Uuid;
use super::reduced_fx_ratio;
use crate::command::CmdError;
/// One recovered from→to row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RaisedRow {
pub from_split: Uuid,
pub to_split: Uuid,
pub from_account: Uuid,
pub to_account: Uuid,
pub from_commodity: Uuid,
pub to_commodity: Uuid,
/// Positive magnitude of the FROM side.
pub value: Rational64,
/// Present only for cross-commodity rows.
pub to_amount: Option<Rational64>,
pub from_reconcile: Option<bool>,
pub to_reconcile: Option<bool>,
}
struct Leg<'a> {
split: &'a Split,
position: usize,
negative: bool,
magnitude: Rational64,
type Bucket<'a, 'b> = (Vec<&'b Leg<'a>>, Vec<&'b Leg<'a>>);
fn args(message: String) -> CmdError {
CmdError::Args(message)
impl<'a> Leg<'a> {
fn new(position: usize, split: &'a Split) -> Result<Self, CmdError> {
let magnitude_numer = split
.value_num
.checked_abs()
.ok_or_else(|| args(format!("split {} value overflows i64", split.id)))?;
if split.reconcile_state == Some(true)
|| split.reconcile_date.is_some()
|| split.lot_id.is_some()
{
return Err(args(format!(
"split {} carries reconciliation or lot data the form cannot keep",
split.id
)));
if split.value_num == 0 {
return Err(args(format!("split {} has zero value", split.id)));
if split.value_denom <= 0 {
return Err(args(format!("split {} has invalid denominator", split.id)));
Ok(Self {
split,
position,
negative: split.value_num < 0,
magnitude: Rational64::new(magnitude_numer, split.value_denom),
})
fn row(&self, to: &Leg<'_>, cross_commodity: bool) -> (usize, RaisedRow) {
let row = RaisedRow {
from_split: self.split.id,
to_split: to.split.id,
from_account: self.split.account_id,
to_account: to.split.account_id,
from_commodity: self.split.commodity_id,
to_commodity: to.split.commodity_id,
value: self.magnitude,
to_amount: cross_commodity.then_some(to.magnitude),
from_reconcile: self.split.reconcile_state,
to_reconcile: to.split.reconcile_state,
};
(self.position, row)
fn parse_legs<'a>(splits: impl IntoIterator<Item = &'a Split>) -> Result<Vec<Leg<'a>>, CmdError> {
let mut seen = HashSet::new();
let mut legs = Vec::new();
for (position, split) in splits.into_iter().enumerate() {
if !seen.insert(split.id) {
return Err(args(format!("split {} appears twice", split.id)));
legs.push(Leg::new(position, split)?);
Ok(legs)
fn priced_leg<'a, 'b>(
legs: &'b HashMap<Uuid, &'b Leg<'a>>,
id: Option<Uuid>,
side: &str,
) -> Result<&'b Leg<'a>, CmdError> {
let id = id.ok_or_else(|| args(format!("price has no {side} split")))?;
legs.get(&id)
.copied()
.ok_or_else(|| args(format!("price {side} split {id} is not in the transaction")))
fn claim(claimed: &mut HashSet<Uuid>, leg: &Leg<'_>) -> Result<(), CmdError> {
if claimed.insert(leg.split.id) {
return Ok(());
Err(args(format!(
"split {} is referenced by several prices",
leg.split.id
)))
fn check_rebuilds(price: &Price, from: &Leg<'_>, to: &Leg<'_>) -> Result<(), CmdError> {
let (num, denom) = reduced_fx_ratio(from.magnitude, to.magnitude).map_err(CmdError::Args)?;
// Equal as rationals: an unreduced stored rate is rewritten to the same value.
let matches = price.commodity_id == to.split.commodity_id
&& price.currency_id == from.split.commodity_id
&& i128::from(price.value_num) * i128::from(denom)
== i128::from(num) * i128::from(price.value_denom);
match matches {
true => Ok(()),
false => Err(args(
"the stored exchange rate does not match the split amounts".to_string(),
)),
fn priced_rows(
legs: &[Leg<'_>],
prices: &[Price],
claimed: &mut HashSet<Uuid>,
) -> Result<Vec<(usize, RaisedRow)>, CmdError> {
let by_id: HashMap<Uuid, &Leg<'_>> = legs.iter().map(|l| (l.split.id, l)).collect();
let mut rows = Vec::with_capacity(prices.len());
for price in prices {
let from = priced_leg(&by_id, price.currency_split, "currency")?;
let to = priced_leg(&by_id, price.commodity_split, "commodity")?;
if !from.negative {
"cross-currency FROM split {} must be negative",
from.split.id
if to.negative {
"cross-currency TO split {} must be positive",
to.split.id
check_rebuilds(price, from, to)?;
claim(claimed, from)?;
claim(claimed, to)?;
rows.push(from.row(to, true));
Ok(rows)
fn pair_bucket(
commodity: Uuid,
(negatives, positives): Bucket<'_, '_>,
) -> Result<(usize, RaisedRow), CmdError> {
match (negatives.as_slice(), positives.as_slice()) {
([from], [to]) => Ok(from.row(to, false)),
_ if negatives.len() > 1 || positives.len() > 1 => Err(args(format!(
"several splits of {magnitude} in commodity {commodity} cannot be paired"
))),
_ => Err(args(format!(
"unpaired split of {magnitude} in commodity {commodity}"
fn plain_rows(
claimed: &HashSet<Uuid>,
let mut buckets: BTreeMap<(Uuid, Rational64), Bucket<'_, '_>> = BTreeMap::new();
for leg in legs.iter().filter(|l| !claimed.contains(&l.split.id)) {
let bucket = buckets
.entry((leg.split.commodity_id, leg.magnitude))
.or_default();
match leg.negative {
true => bucket.0.push(leg),
false => bucket.1.push(leg),
buckets
.into_iter()
.map(|((commodity, magnitude), bucket)| pair_bucket(commodity, magnitude, bucket))
.collect()
/// Recover from→to rows in input order of their FROM splits, or fail when the
/// pairing is not provable.
pub fn raise_transaction<'a>(
splits: impl IntoIterator<Item = &'a Split>,
) -> Result<Vec<RaisedRow>, CmdError> {
let legs = parse_legs(splits)?;
let mut claimed = HashSet::new();
let mut rows = priced_rows(&legs, prices, &mut claimed)?;
rows.extend(plain_rows(&legs, &claimed)?);
rows.sort_by_key(|(position, _)| *position);
Ok(rows.into_iter().map(|(_, row)| row).collect())