1use std::collections::{BTreeMap, HashMap, HashSet};
9
10use finance::{price::Price, split::Split};
11use num_rational::Rational64;
12use sqlx::types::Uuid;
13
14use super::reduced_fx_ratio;
15use crate::command::CmdError;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub 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 pub value: Rational64,
28 pub to_amount: Option<Rational64>,
30 pub from_reconcile: Option<bool>,
31 pub to_reconcile: Option<bool>,
32}
33
34struct Leg<'a> {
35 split: &'a Split,
36 position: usize,
37 negative: bool,
38 magnitude: Rational64,
39}
40
41type Bucket<'a, 'b> = (Vec<&'b Leg<'a>>, Vec<&'b Leg<'a>>);
42
43fn args(message: String) -> CmdError {
44 CmdError::Args(message)
45}
46
47impl<'a> Leg<'a> {
48 fn new(position: usize, split: &'a Split) -> Result<Self, CmdError> {
49 let magnitude_numer = split
50 .value_num
51 .checked_abs()
52 .ok_or_else(|| args(format!("split {} value overflows i64", split.id)))?;
53 if split.reconcile_state == Some(true)
54 || split.reconcile_date.is_some()
55 || split.lot_id.is_some()
56 {
57 return Err(args(format!(
58 "split {} carries reconciliation or lot data the form cannot keep",
59 split.id
60 )));
61 }
62 if split.value_num == 0 {
63 return Err(args(format!("split {} has zero value", split.id)));
64 }
65 if split.value_denom <= 0 {
66 return Err(args(format!("split {} has invalid denominator", split.id)));
67 }
68 Ok(Self {
69 split,
70 position,
71 negative: split.value_num < 0,
72 magnitude: Rational64::new(magnitude_numer, split.value_denom),
73 })
74 }
75
76 fn row(&self, to: &Leg<'_>, cross_commodity: bool) -> (usize, RaisedRow) {
77 let row = RaisedRow {
78 from_split: self.split.id,
79 to_split: to.split.id,
80 from_account: self.split.account_id,
81 to_account: to.split.account_id,
82 from_commodity: self.split.commodity_id,
83 to_commodity: to.split.commodity_id,
84 value: self.magnitude,
85 to_amount: cross_commodity.then_some(to.magnitude),
86 from_reconcile: self.split.reconcile_state,
87 to_reconcile: to.split.reconcile_state,
88 };
89 (self.position, row)
90 }
91}
92
93fn parse_legs<'a>(splits: impl IntoIterator<Item = &'a Split>) -> Result<Vec<Leg<'a>>, CmdError> {
94 let mut seen = HashSet::new();
95 let mut legs = Vec::new();
96 for (position, split) in splits.into_iter().enumerate() {
97 if !seen.insert(split.id) {
98 return Err(args(format!("split {} appears twice", split.id)));
99 }
100 legs.push(Leg::new(position, split)?);
101 }
102 Ok(legs)
103}
104
105fn priced_leg<'a, 'b>(
106 legs: &'b HashMap<Uuid, &'b Leg<'a>>,
107 id: Option<Uuid>,
108 side: &str,
109) -> Result<&'b Leg<'a>, CmdError> {
110 let id = id.ok_or_else(|| args(format!("price has no {side} split")))?;
111 legs.get(&id)
112 .copied()
113 .ok_or_else(|| args(format!("price {side} split {id} is not in the transaction")))
114}
115
116fn claim(claimed: &mut HashSet<Uuid>, leg: &Leg<'_>) -> Result<(), CmdError> {
117 if claimed.insert(leg.split.id) {
118 return Ok(());
119 }
120 Err(args(format!(
121 "split {} is referenced by several prices",
122 leg.split.id
123 )))
124}
125
126fn check_rebuilds(price: &Price, from: &Leg<'_>, to: &Leg<'_>) -> Result<(), CmdError> {
127 let (num, denom) = reduced_fx_ratio(from.magnitude, to.magnitude).map_err(CmdError::Args)?;
128 let matches = price.commodity_id == to.split.commodity_id
130 && price.currency_id == from.split.commodity_id
131 && i128::from(price.value_num) * i128::from(denom)
132 == i128::from(num) * i128::from(price.value_denom);
133 match matches {
134 true => Ok(()),
135 false => Err(args(
136 "the stored exchange rate does not match the split amounts".to_string(),
137 )),
138 }
139}
140
141fn priced_rows(
142 legs: &[Leg<'_>],
143 prices: &[Price],
144 claimed: &mut HashSet<Uuid>,
145) -> Result<Vec<(usize, RaisedRow)>, CmdError> {
146 let by_id: HashMap<Uuid, &Leg<'_>> = legs.iter().map(|l| (l.split.id, l)).collect();
147 let mut rows = Vec::with_capacity(prices.len());
148 for price in prices {
149 let from = priced_leg(&by_id, price.currency_split, "currency")?;
150 let to = priced_leg(&by_id, price.commodity_split, "commodity")?;
151 if !from.negative {
152 return Err(args(format!(
153 "cross-currency FROM split {} must be negative",
154 from.split.id
155 )));
156 }
157 if to.negative {
158 return Err(args(format!(
159 "cross-currency TO split {} must be positive",
160 to.split.id
161 )));
162 }
163 check_rebuilds(price, from, to)?;
164 claim(claimed, from)?;
165 claim(claimed, to)?;
166 rows.push(from.row(to, true));
167 }
168 Ok(rows)
169}
170
171fn pair_bucket(
172 commodity: Uuid,
173 magnitude: Rational64,
174 (negatives, positives): Bucket<'_, '_>,
175) -> Result<(usize, RaisedRow), CmdError> {
176 match (negatives.as_slice(), positives.as_slice()) {
177 ([from], [to]) => Ok(from.row(to, false)),
178 _ if negatives.len() > 1 || positives.len() > 1 => Err(args(format!(
179 "several splits of {magnitude} in commodity {commodity} cannot be paired"
180 ))),
181 _ => Err(args(format!(
182 "unpaired split of {magnitude} in commodity {commodity}"
183 ))),
184 }
185}
186
187fn plain_rows(
188 legs: &[Leg<'_>],
189 claimed: &HashSet<Uuid>,
190) -> Result<Vec<(usize, RaisedRow)>, CmdError> {
191 let mut buckets: BTreeMap<(Uuid, Rational64), Bucket<'_, '_>> = BTreeMap::new();
192 for leg in legs.iter().filter(|l| !claimed.contains(&l.split.id)) {
193 let bucket = buckets
194 .entry((leg.split.commodity_id, leg.magnitude))
195 .or_default();
196 match leg.negative {
197 true => bucket.0.push(leg),
198 false => bucket.1.push(leg),
199 }
200 }
201 buckets
202 .into_iter()
203 .map(|((commodity, magnitude), bucket)| pair_bucket(commodity, magnitude, bucket))
204 .collect()
205}
206
207pub fn raise_transaction<'a>(
210 splits: impl IntoIterator<Item = &'a Split>,
211 prices: &[Price],
212) -> Result<Vec<RaisedRow>, CmdError> {
213 let legs = parse_legs(splits)?;
214 let mut claimed = HashSet::new();
215 let mut rows = priced_rows(&legs, prices, &mut claimed)?;
216 rows.extend(plain_rows(&legs, &claimed)?);
217 rows.sort_by_key(|(position, _)| *position);
218 Ok(rows.into_iter().map(|(_, row)| row).collect())
219}