1
use forms::{Field, Row, Source};
2

            
3
use super::{Cell, References};
4

            
5
/// The converted amount of a split is needed only when its commodities differ.
6
pub(super) struct Conversion {
7
    rows: &'static str,
8
    amount: &'static str,
9
    from: &'static str,
10
    to: &'static str,
11
}
12

            
13
pub(super) const CONVERSION: Conversion = Conversion {
14
    rows: "splits",
15
    amount: "to-amount",
16
    from: "from-commodity",
17
    to: "to-commodity",
18
};
19

            
20
impl Conversion {
21
    /// Whether the row names two commodities; texts the `references` cannot
22
    /// resolve are compared as written.
23
1008
    pub(super) fn differs(&self, row: Option<&Row>, references: &References) -> bool {
24
2016
        let get = |key: &str| row.and_then(|r| r.get(key)).map_or("", String::as_str);
25
1008
        let (from, to) = (get(self.from).trim(), get(self.to).trim());
26
1008
        if from.is_empty() || to.is_empty() {
27
918
            return false;
28
90
        }
29
180
        let id = |text| {
30
180
            references
31
180
                .resolve(Source::Commodities, text)
32
58
                .map(|option| option.id)
33
180
        };
34
90
        id(from).zip(id(to)).map_or(from != to, |(a, b)| a != b)
35
1008
    }
36

            
37
    /// The fields of a row in the order a person tabs through them: a split
38
    /// states its value before the commodity it is received in.
39
1008
    pub(super) fn flow<'f>(&self, rows: &str, fields: &'f [Field]) -> Vec<&'f Field> {
40
1008
        let mut ordered: Vec<&Field> = fields.iter().collect();
41
7999
        let at = |key| ordered.iter().position(|f| f.key == key);
42
1008
        if let (true, Some(to), Some(value)) = (rows == self.rows, at(self.to), at("value")) {
43
294
            ordered.swap(to, value);
44
714
        }
45
1008
        ordered
46
1008
    }
47

            
48
5280
    pub(super) fn mark(&self, rows: &str, key: &str, cell: &mut Cell, differs: bool) {
49
5280
        let Cell::Control(control) = cell else { return };
50
4299
        if (rows, key) == (self.rows, self.amount) {
51
294
            control.converts = Some((self.from, self.to));
52
294
            control.dormant = !differs && control.errors.is_empty();
53
294
            if control.dormant {
54
219
                control.class = "field hidden-field";
55
75
            }
56
4005
        }
57
5280
    }
58
}