1
//! Row resolution and lowering shared by the transaction create and edit
2
//! submits: stage 2 (resolution) and stage 3 (domain rules on ids).
3

            
4
use chrono::{DateTime, Utc};
5
use forms::{FieldError, FormValues, Row, address, parse_post_date};
6
use num_rational::Rational64;
7
use server::logical::{
8
    LogicalSplit, PhysicalSplit, PriceRow, RowTags, SplitFault, SplitField,
9
    lower_logical_split_located,
10
};
11

            
12
use super::hidden::Hidden;
13
use crate::lowering::Lowered;
14
use crate::resolve::{Directory, RowKeys};
15

            
16
type LoweredRow = (PhysicalSplit, PhysicalSplit, Option<PriceRow>);
17

            
18
7187
pub(super) fn error_at(field: String, message: impl Into<String>) -> FieldError {
19
7187
    FieldError {
20
7187
        field,
21
7187
        message: message.into(),
22
7187
    }
23
7187
}
24

            
25
/// The to-commodity cell of a loaded row: empty when it is the from-commodity,
26
/// which a submit already reads as the same commodity.
27
19324
pub(super) fn to_commodity_cell<T: PartialEq + ToString>(from: &T, to: &T) -> String {
28
19324
    match from == to {
29
10826
        true => String::new(),
30
8498
        false => to.to_string(),
31
    }
32
19324
}
33

            
34
/// A field error at `field` when `value` spans several lines.
35
8255
pub(super) fn single_line(field: &str, value: &str) -> Result<(), FieldError> {
36
8255
    match value.contains(['\n', '\r']) {
37
8
        true => Err(error_at(field.to_string(), "must be a single line")),
38
8247
        false => Ok(()),
39
    }
40
8255
}
41

            
42
/// Both results, or the field errors of every failed one.
43
120143
pub(super) fn joined<A, B>(
44
120143
    first: Result<A, Vec<FieldError>>,
45
120143
    second: Result<B, Vec<FieldError>>,
46
120143
) -> Result<(A, B), Vec<FieldError>> {
47
120143
    match (first, second) {
48
118949
        (Ok(first), Ok(second)) => Ok((first, second)),
49
1194
        (first, second) => Err(first
50
1194
            .err()
51
1194
            .into_iter()
52
1194
            .chain(second.err())
53
1194
            .flatten()
54
1194
            .collect()),
55
    }
56
120143
}
57

            
58
38139
pub(super) fn post_date(values: &FormValues) -> Result<DateTime<Utc>, FieldError> {
59
38139
    let text = values.text("date").unwrap_or_default();
60
38139
    parse_post_date(text).map_err(|message| error_at("date".to_string(), message))
61
38139
}
62

            
63
/// Resolve and lower every row, collecting the errors of all of them. A row
64
/// with hidden data keeps it: unchanged cells submit the hidden ids, an
65
/// unchanged FX row its price date. Each row's `tags` go on its legs.
66
37976
pub(super) fn lower_rows(
67
37976
    directory: &Directory,
68
37976
    rows: &[Row],
69
37976
    hidden: &[Option<Hidden>],
70
37976
    tags: &[RowTags],
71
37976
) -> Result<Lowered, Vec<FieldError>> {
72
37976
    let mut lowered = Lowered {
73
37976
        splits: Vec::new(),
74
37976
        prices: Vec::new(),
75
37976
        split_tags: Vec::new(),
76
37976
    };
77
37976
    let mut errors = Vec::new();
78
37976
    let mut failed = false;
79
37976
    for (index, row) in rows.iter().enumerate() {
80
42515
        let hidden = hidden.get(index).and_then(Option::as_ref);
81
42515
        match lower_row(directory, row, index, hidden) {
82
            Ok((from, to, price)) => {
83
41841
                if let Some(tags) = tags.get(index) {
84
41832
                    lowered.split_tags.extend(tags.on_legs(from.id, to.id));
85
9
                }
86
41841
                lowered.splits.extend([from, to]);
87
41841
                lowered.prices.extend(price);
88
            }
89
            Err(mut row_errors) => {
90
674
                failed = true;
91
674
                errors.append(&mut row_errors);
92
            }
93
        }
94
    }
95
37976
    match failed {
96
658
        true => Err(errors),
97
37318
        false => Ok(lowered),
98
    }
99
37976
}
100

            
101
253744
fn cell<'a>(row: &'a Row, key: &str) -> &'a str {
102
253744
    row.get(key).map_or("", |text| text.trim())
103
253744
}
104

            
105
42515
fn lower_row(
106
42515
    directory: &Directory,
107
42515
    row: &Row,
108
42515
    index: usize,
109
42515
    hidden: Option<&Hidden>,
110
42515
) -> Result<LoweredRow, Vec<FieldError>> {
111
42515
    if let Some(hidden) = hidden {
112
8560
        hidden
113
8560
            .verify(directory)
114
2
            .map_err(|message| vec![error_at(address::row("splits", index), message)])?;
115
33955
    }
116
42513
    let split = resolve_row(directory, row, index, hidden)?;
117
    let (from, to, price) =
118
41846
        lower_logical_split_located(&split).map_err(|fault| vec![fault_error(index, fault)])?;
119
41841
    let kept_date = hidden
120
8396
        .filter(|hidden| hidden.unchanged(&split))
121
8233
        .and_then(|hidden| hidden.price_date);
122
41841
    let price = price.map(|price| PriceRow {
123
8029
        date: kept_date,
124
8029
        ..price
125
8029
    });
126
41841
    Ok((from, to, price))
127
42515
}
128

            
129
42513
fn resolve_row(
130
42513
    directory: &Directory,
131
42513
    row: &Row,
132
42513
    index: usize,
133
42513
    hidden: Option<&Hidden>,
134
42513
) -> Result<LogicalSplit, Vec<FieldError>> {
135
    let keys = RowKeys {
136
42513
        from: cell(row, "from"),
137
42513
        to: cell(row, "to"),
138
42513
        from_commodity: cell(row, "from-commodity"),
139
42513
        to_commodity: Some(cell(row, "to-commodity")).filter(|text| !text.is_empty()),
140
    };
141
42513
    let ids = directory.resolve_row(&keys).map_err(|faults| {
142
667
        faults
143
667
            .into_iter()
144
1000
            .map(|(field, err)| {
145
1000
                error_at(address::cell("splits", index, field.key()), err.to_string())
146
1000
            })
147
            .collect::<Vec<_>>()
148
667
    })?;
149
41846
    let value = amount_at(row, "value", index).map_err(|e| vec![e])?;
150
41846
    let to_amount = amount_at(row, "to-amount", index).map_err(|e| vec![e])?;
151
    Ok(LogicalSplit {
152
41846
        from: ids.from,
153
41846
        to: ids.to,
154
41846
        from_commodity: ids.from_commodity,
155
41846
        to_commodity: ids.to_commodity,
156
41846
        value: value.unwrap_or_default(),
157
41846
        to_amount,
158
41846
        from_reconcile: hidden.and_then(|hidden| hidden.reconcile[0]),
159
41846
        to_reconcile: hidden.and_then(|hidden| hidden.reconcile[1]),
160
    })
161
42513
}
162

            
163
/// An amount token as an exact rational.
164
63267
pub(super) fn parse_rational(text: &str) -> Result<Rational64, String> {
165
63267
    let (numer, denom) = amount::parse_amount(text).map_err(|err| err.to_string())?;
166
63265
    Ok(Rational64::new(numer, denom))
167
63267
}
168

            
169
/// An empty cell is absent; syntax was already checked, so a failure here
170
/// only guards the conversion.
171
83692
fn amount_at(row: &Row, key: &str, index: usize) -> Result<Option<Rational64>, FieldError> {
172
83692
    let text = cell(row, key);
173
83692
    if text.is_empty() {
174
33815
        return Ok(None);
175
49877
    }
176
49877
    parse_rational(text)
177
49877
        .map(Some)
178
        .map_err(|err| error_at(address::cell("splits", index, key), err))
179
83692
}
180

            
181
5
fn fault_error(index: usize, fault: SplitFault) -> FieldError {
182
5
    let field = match fault.field {
183
2
        Some(SplitField::Value) => address::cell("splits", index, "value"),
184
3
        Some(SplitField::ToAmount) => address::cell("splits", index, "to-amount"),
185
        None => address::row("splits", index),
186
    };
187
5
    error_at(field, fault.message)
188
5
}