1
use finance::error::{FinanceError, ReportError};
2
use num_rational::Rational64;
3
use num_traits::{CheckedAdd, CheckedMul};
4
use sqlx::types::Uuid;
5
use std::collections::HashMap;
6
use std::collections::hash_map::Entry;
7

            
8
use super::super::{CmdError, CommodityAmount, ReportNode};
9

            
10
pub(super) struct AccountRow {
11
    pub account_id: Uuid,
12
    pub parent_id: Option<Uuid>,
13
    pub account_name: String,
14
    pub account_type: Option<String>,
15
}
16

            
17
pub(super) type AmountMap = HashMap<Uuid, (Rational64, String)>;
18
pub(super) type AccountAmounts = HashMap<Uuid, AmountMap>;
19

            
20
/// The ratio `numer/denom` of stored columns; a zero or unnormalizable denominator is data damage.
21
274357
pub(super) fn ratio(numer: i64, denom: i64) -> Result<Rational64, ReportError> {
22
274357
    let unnormalizable = denom == i64::MIN || (denom < 0 && numer == i64::MIN);
23
274357
    if denom == 0 || unnormalizable {
24
4
        return Err(ReportError::InvalidRatio { numer, denom });
25
274353
    }
26
274353
    Ok(Rational64::new(numer, denom))
27
274357
}
28

            
29
146078
pub(super) fn checked_sum(a: Rational64, b: Rational64) -> Result<Rational64, ReportError> {
30
146078
    a.checked_add(&b).ok_or(ReportError::AmountOverflow)
31
146078
}
32

            
33
2907
pub(super) fn checked_product(a: Rational64, b: Rational64) -> Result<Rational64, ReportError> {
34
2907
    a.checked_mul(&b).ok_or(ReportError::AmountOverflow)
35
2907
}
36

            
37
361
pub(super) fn report_failure(err: ReportError) -> CmdError {
38
361
    CmdError::Finance(FinanceError::Report(err))
39
361
}
40

            
41
/// Adds `value` to the amount held under `commodity_id`, or starts it.
42
388821
pub(super) fn add_amount(
43
388821
    amounts: &mut AmountMap,
44
388821
    commodity_id: Uuid,
45
388821
    value: Rational64,
46
388821
    symbol: &str,
47
388821
) -> Result<(), ReportError> {
48
388821
    match amounts.entry(commodity_id) {
49
141558
        Entry::Occupied(mut held) => held.get_mut().0 = checked_sum(held.get().0, value)?,
50
        Entry::Vacant(free) => {
51
247263
            free.insert((value, symbol.to_owned()));
52
        }
53
    }
54
388458
    Ok(())
55
388821
}
56

            
57
204127
pub(super) fn accumulate_split(
58
204127
    amounts: &mut AccountAmounts,
59
204127
    account_id: Uuid,
60
204127
    commodity_id: Uuid,
61
204127
    value: Rational64,
62
204127
    symbol: &str,
63
204127
) -> Result<(), ReportError> {
64
204127
    add_amount(
65
204127
        amounts.entry(account_id).or_default(),
66
204127
        commodity_id,
67
204127
        value,
68
204127
        symbol,
69
204127
    )
70
204127
}
71

            
72
pub(super) struct ConversionTarget<'a> {
73
    pub commodity_id: Uuid,
74
    pub symbol: &'a str,
75
}
76

            
77
24790
pub(super) fn accumulate_split_converted(
78
24790
    amounts: &mut AccountAmounts,
79
24790
    account_id: Uuid,
80
24790
    commodity_id: Uuid,
81
24790
    value: Rational64,
82
24790
    symbol: &str,
83
24790
    target: &ConversionTarget<'_>,
84
24790
    price: (Option<i64>, Option<i64>),
85
24790
) -> Result<(), ReportError> {
86
24790
    if commodity_id == target.commodity_id {
87
21520
        accumulate_split(
88
21520
            amounts,
89
21520
            account_id,
90
21520
            target.commodity_id,
91
21520
            value,
92
21520
            target.symbol,
93
21520
        )
94
3270
    } else if let (Some(pn), Some(pd)) = price {
95
2364
        let converted = checked_product(value, ratio(pn, pd)?)?;
96
2364
        accumulate_split(
97
2364
            amounts,
98
2364
            account_id,
99
2364
            target.commodity_id,
100
2364
            converted,
101
2364
            target.symbol,
102
2364
        )
103
    } else {
104
906
        Err(ReportError::MissingConversion {
105
906
            from_commodity: symbol.to_owned(),
106
906
            to_commodity: target.symbol.to_owned(),
107
906
        })
108
    }
109
24790
}
110

            
111
/// Symbol order, UUID as tie-break: stable across runs for every client.
112
761319
pub(super) fn sort_amounts(amounts: &mut [CommodityAmount]) {
113
761319
    amounts.sort_by(|a, b| {
114
80529
        (&a.commodity_symbol, a.commodity_id).cmp(&(&b.commodity_symbol, b.commodity_id))
115
80529
    });
116
761319
}
117

            
118
716210
fn sorted_commodity_amounts(amounts: AmountMap) -> Vec<CommodityAmount> {
119
716210
    let mut sorted: Vec<CommodityAmount> = amounts
120
716210
        .into_iter()
121
        .map(|(cid, (amount, symbol))| CommodityAmount {
122
291220
            commodity_id: cid,
123
291220
            commodity_symbol: symbol,
124
291220
            amount,
125
291220
        })
126
        .collect();
127
716210
    sort_amounts(&mut sorted);
128
716210
    sorted
129
716210
}
130

            
131
49237
pub(super) fn build_tree(
132
49237
    accounts: &[AccountRow],
133
49237
    amounts: &AccountAmounts,
134
49237
) -> Result<Vec<ReportNode>, ReportError> {
135
    let children_map: HashMap<Option<Uuid>, Vec<&AccountRow>> = {
136
49237
        let mut m: HashMap<Option<Uuid>, Vec<&AccountRow>> = HashMap::new();
137
49237
        for a in accounts {
138
358106
            m.entry(a.parent_id).or_default().push(a);
139
        }
140
49237
        m
141
    };
142

            
143
49237
    let roots = children_map.get(&None).cloned().unwrap_or_default();
144
49237
    let mut tree = Vec::new();
145
49237
    for root in roots {
146
141446
        let node = build_node(root, &children_map, amounts, "", 0)?;
147
141445
        if !node.amounts.is_empty() {
148
52494
            tree.push(node);
149
88951
        }
150
    }
151
49236
    Ok(tree)
152
49237
}
153

            
154
358106
fn build_node(
155
358106
    account: &AccountRow,
156
358106
    children_map: &HashMap<Option<Uuid>, Vec<&AccountRow>>,
157
358106
    amounts: &AccountAmounts,
158
358106
    parent_path: &str,
159
358106
    depth: usize,
160
358106
) -> Result<ReportNode, ReportError> {
161
358106
    let path = if parent_path.is_empty() {
162
141446
        account.account_name.clone()
163
    } else {
164
216660
        format!("{parent_path}:{}", account.account_name)
165
    };
166

            
167
358106
    let children: Vec<ReportNode> = children_map
168
358106
        .get(&Some(account.account_id))
169
358106
        .cloned()
170
358106
        .unwrap_or_default()
171
358106
        .iter()
172
216660
        .map(|child| build_node(child, children_map, amounts, &path, depth + 1))
173
        .collect::<Result<_, _>>()?;
174

            
175
358106
    let split_amounts: AmountMap = amounts
176
358106
        .get(&account.account_id)
177
358106
        .cloned()
178
358106
        .unwrap_or_default();
179
358106
    let mut own_amounts = split_amounts.clone();
180

            
181
358106
    for child in &children {
182
216660
        for ca in &child.amounts {
183
120448
            add_amount(
184
120448
                &mut own_amounts,
185
120448
                ca.commodity_id,
186
120448
                ca.amount,
187
120448
                &ca.commodity_symbol,
188
120448
            )?;
189
        }
190
    }
191

            
192
358105
    let children: Vec<ReportNode> = children
193
358105
        .into_iter()
194
216659
        .filter(|n| !n.amounts.is_empty())
195
        .collect();
196

            
197
358105
    let sorted_amounts = sorted_commodity_amounts(own_amounts);
198

            
199
358105
    Ok(ReportNode {
200
358105
        account_id: account.account_id,
201
358105
        account_name: account.account_name.clone(),
202
358105
        account_path: path,
203
358105
        depth,
204
358105
        account_type: account.account_type.clone(),
205
358105
        amounts: sorted_amounts,
206
358105
        own_amounts: sorted_commodity_amounts(split_amounts),
207
358105
        children,
208
358105
    })
209
358106
}
210

            
211
#[cfg(test)]
212
#[path = "tree_tests.rs"]
213
mod tests;