1
//! Conservative inversion of the forward lowering: physical splits and price
2
//! rows back into logical from→to rows.
3
//!
4
//! The lowering stores no link between a row's two splits, so pairing is
5
//! only accepted when it is provable; anything ambiguous is an error rather
6
//! than a guess.
7

            
8
use std::collections::{BTreeMap, HashMap, HashSet};
9

            
10
use finance::{price::Price, split::Split};
11
use num_rational::Rational64;
12
use sqlx::types::Uuid;
13

            
14
use super::reduced_fx_ratio;
15
use crate::command::CmdError;
16

            
17
/// One recovered from→to row.
18
#[derive(Debug, Clone, PartialEq, Eq)]
19
pub struct RaisedRow {
20
    pub from_split: Uuid,
21
    pub to_split: Uuid,
22
    pub from_account: Uuid,
23
    pub to_account: Uuid,
24
    pub from_commodity: Uuid,
25
    pub to_commodity: Uuid,
26
    /// Positive magnitude of the FROM side.
27
    pub value: Rational64,
28
    /// Present only for cross-commodity rows.
29
    pub to_amount: Option<Rational64>,
30
    pub from_reconcile: Option<bool>,
31
    pub to_reconcile: Option<bool>,
32
}
33

            
34
struct Leg<'a> {
35
    split: &'a Split,
36
    position: usize,
37
    negative: bool,
38
    magnitude: Rational64,
39
}
40

            
41
type Bucket<'a, 'b> = (Vec<&'b Leg<'a>>, Vec<&'b Leg<'a>>);
42

            
43
2537
fn args(message: String) -> CmdError {
44
2537
    CmdError::Args(message)
45
2537
}
46

            
47
impl<'a> Leg<'a> {
48
208138
    fn new(position: usize, split: &'a Split) -> Result<Self, CmdError> {
49
208138
        let magnitude_numer = split
50
208138
            .value_num
51
208138
            .checked_abs()
52
1
            .ok_or_else(|| args(format!("split {} value overflows i64", split.id)))?;
53
208137
        if split.reconcile_state == Some(true)
54
207056
            || split.reconcile_date.is_some()
55
207055
            || split.lot_id.is_some()
56
        {
57
1083
            return Err(args(format!(
58
1083
                "split {} carries reconciliation or lot data the form cannot keep",
59
1083
                split.id
60
1083
            )));
61
207054
        }
62
207054
        if split.value_num == 0 {
63
1
            return Err(args(format!("split {} has zero value", split.id)));
64
207053
        }
65
207053
        if split.value_denom <= 0 {
66
1
            return Err(args(format!("split {} has invalid denominator", split.id)));
67
207052
        }
68
207052
        Ok(Self {
69
207052
            split,
70
207052
            position,
71
207052
            negative: split.value_num < 0,
72
207052
            magnitude: Rational64::new(magnitude_numer, split.value_denom),
73
207052
        })
74
208138
    }
75

            
76
101533
    fn row(&self, to: &Leg<'_>, cross_commodity: bool) -> (usize, RaisedRow) {
77
101533
        let row = RaisedRow {
78
101533
            from_split: self.split.id,
79
101533
            to_split: to.split.id,
80
101533
            from_account: self.split.account_id,
81
101533
            to_account: to.split.account_id,
82
101533
            from_commodity: self.split.commodity_id,
83
101533
            to_commodity: to.split.commodity_id,
84
101533
            value: self.magnitude,
85
101533
            to_amount: cross_commodity.then_some(to.magnitude),
86
101533
            from_reconcile: self.split.reconcile_state,
87
101533
            to_reconcile: to.split.reconcile_state,
88
101533
        };
89
101533
        (self.position, row)
90
101533
    }
91
}
92

            
93
81389
fn parse_legs<'a>(splits: impl IntoIterator<Item = &'a Split>) -> Result<Vec<Leg<'a>>, CmdError> {
94
81389
    let mut seen = HashSet::new();
95
81389
    let mut legs = Vec::new();
96
81389
    for (position, split) in splits.into_iter().enumerate() {
97
208139
        if !seen.insert(split.id) {
98
1
            return Err(args(format!("split {} appears twice", split.id)));
99
208138
        }
100
208138
        legs.push(Leg::new(position, split)?);
101
    }
102
80302
    Ok(legs)
103
81389
}
104

            
105
66261
fn priced_leg<'a, 'b>(
106
66261
    legs: &'b HashMap<Uuid, &'b Leg<'a>>,
107
66261
    id: Option<Uuid>,
108
66261
    side: &str,
109
66261
) -> Result<&'b Leg<'a>, CmdError> {
110
66261
    let id = id.ok_or_else(|| args(format!("price has no {side} split")))?;
111
66260
    legs.get(&id)
112
66260
        .copied()
113
1
        .ok_or_else(|| args(format!("price {side} split {id} is not in the transaction")))
114
66261
}
115

            
116
65529
fn claim(claimed: &mut HashSet<Uuid>, leg: &Leg<'_>) -> Result<(), CmdError> {
117
65529
    if claimed.insert(leg.split.id) {
118
65528
        return Ok(());
119
1
    }
120
1
    Err(args(format!(
121
1
        "split {} is referenced by several prices",
122
1
        leg.split.id
123
1
    )))
124
65529
}
125

            
126
33128
fn check_rebuilds(price: &Price, from: &Leg<'_>, to: &Leg<'_>) -> Result<(), CmdError> {
127
33128
    let (num, denom) = reduced_fx_ratio(from.magnitude, to.magnitude).map_err(CmdError::Args)?;
128
    // Equal as rationals: an unreduced stored rate is rewritten to the same value.
129
33128
    let matches = price.commodity_id == to.split.commodity_id
130
33127
        && price.currency_id == from.split.commodity_id
131
33126
        && i128::from(price.value_num) * i128::from(denom)
132
33126
            == i128::from(num) * i128::from(price.value_denom);
133
33128
    match matches {
134
32765
        true => Ok(()),
135
363
        false => Err(args(
136
363
            "the stored exchange rate does not match the split amounts".to_string(),
137
363
        )),
138
    }
139
33128
}
140

            
141
80302
fn priced_rows(
142
80302
    legs: &[Leg<'_>],
143
80302
    prices: &[Price],
144
80302
    claimed: &mut HashSet<Uuid>,
145
80302
) -> Result<Vec<(usize, RaisedRow)>, CmdError> {
146
207048
    let by_id: HashMap<Uuid, &Leg<'_>> = legs.iter().map(|l| (l.split.id, l)).collect();
147
80302
    let mut rows = Vec::with_capacity(prices.len());
148
80302
    for price in prices {
149
33131
        let from = priced_leg(&by_id, price.currency_split, "currency")?;
150
33130
        let to = priced_leg(&by_id, price.commodity_split, "commodity")?;
151
33129
        if !from.negative {
152
1
            return Err(args(format!(
153
1
                "cross-currency FROM split {} must be negative",
154
1
                from.split.id
155
1
            )));
156
33128
        }
157
33128
        if to.negative {
158
            return Err(args(format!(
159
                "cross-currency TO split {} must be positive",
160
                to.split.id
161
            )));
162
33128
        }
163
33128
        check_rebuilds(price, from, to)?;
164
32765
        claim(claimed, from)?;
165
32764
        claim(claimed, to)?;
166
32764
        rows.push(from.row(to, true));
167
    }
168
79935
    Ok(rows)
169
80302
}
170

            
171
69852
fn pair_bucket(
172
69852
    commodity: Uuid,
173
69852
    magnitude: Rational64,
174
69852
    (negatives, positives): Bucket<'_, '_>,
175
69852
) -> Result<(usize, RaisedRow), CmdError> {
176
69852
    match (negatives.as_slice(), positives.as_slice()) {
177
68769
        ([from], [to]) => Ok(from.row(to, false)),
178
1083
        _ if negatives.len() > 1 || positives.len() > 1 => Err(args(format!(
179
1
            "several splits of {magnitude} in commodity {commodity} cannot be paired"
180
1
        ))),
181
1082
        _ => Err(args(format!(
182
1082
            "unpaired split of {magnitude} in commodity {commodity}"
183
1082
        ))),
184
    }
185
69852
}
186

            
187
79935
fn plain_rows(
188
79935
    legs: &[Leg<'_>],
189
79935
    claimed: &HashSet<Uuid>,
190
79935
) -> Result<Vec<(usize, RaisedRow)>, CmdError> {
191
79935
    let mut buckets: BTreeMap<(Uuid, Rational64), Bucket<'_, '_>> = BTreeMap::new();
192
206313
    for leg in legs.iter().filter(|l| !claimed.contains(&l.split.id)) {
193
140787
        let bucket = buckets
194
140787
            .entry((leg.split.commodity_id, leg.magnitude))
195
140787
            .or_default();
196
140787
        match leg.negative {
197
69853
            true => bucket.0.push(leg),
198
70934
            false => bucket.1.push(leg),
199
        }
200
    }
201
79935
    buckets
202
79935
        .into_iter()
203
69852
        .map(|((commodity, magnitude), bucket)| pair_bucket(commodity, magnitude, bucket))
204
        .collect()
205
79935
}
206

            
207
/// Recover from→to rows in input order of their FROM splits, or fail when the
208
/// pairing is not provable.
209
81389
pub fn raise_transaction<'a>(
210
81389
    splits: impl IntoIterator<Item = &'a Split>,
211
81389
    prices: &[Price],
212
81389
) -> Result<Vec<RaisedRow>, CmdError> {
213
81389
    let legs = parse_legs(splits)?;
214
80302
    let mut claimed = HashSet::new();
215
80302
    let mut rows = priced_rows(&legs, prices, &mut claimed)?;
216
79935
    rows.extend(plain_rows(&legs, &claimed)?);
217
78852
    rows.sort_by_key(|(position, _)| *position);
218
78852
    Ok(rows.into_iter().map(|(_, row)| row).collect())
219
81389
}