1
//! HTML form fields named by address, and their inverse.
2

            
3
use std::collections::{BTreeMap, BTreeSet};
4

            
5
use crate::address;
6
use crate::descriptor::{Field, Form, Kind};
7
use crate::labels::is_select_companion;
8
use crate::values::{FieldError, FormValues, Row};
9

            
10
pub(crate) enum Address<'a> {
11
    Flat(&'a Field),
12
    Row(&'a Field, usize),
13
    Cell(&'a Field, usize, &'a Field),
14
}
15

            
16
impl FormValues {
17
    /// Decode address-named fields (`date`, `splits.0.from`); a bare `rows`
18
    /// key is the presence marker and a bare `rows.i` with an empty value marks
19
    /// row `i` present. CRLF and lone CR become LF. The typed text of a select
20
    /// control (`label:` plus its address) and its `filled:` mark are skipped; see [`crate::labels`].
21
    ///
22
    /// # Errors
23
    /// Unknown or duplicate addresses and index gaps are whole-form errors
24
    /// (field `""`); a marker carrying text is an error at its address.
25
609
    pub fn from_pairs(
26
609
        form: &Form,
27
609
        pairs: impl IntoIterator<Item = (String, String)>,
28
609
    ) -> Result<Self, Vec<FieldError>> {
29
609
        let mut decoder = Decoder::default();
30
609
        for (name, value) in pairs {
31
4245
            decoder.accept(form, &name, normalize_newlines(&value));
32
        }
33
609
        decoder.finish()
34
609
    }
35

            
36
    /// Inverse of [`FormValues::from_pairs`]: a marker for every present
37
    /// `rows` field, then its row cells; a row without cells becomes a bare
38
    /// `rows.i` marker.
39
    #[must_use]
40
46656
    pub fn to_pairs(&self, form: &Form) -> Vec<(String, String)> {
41
46656
        let mut pairs = Vec::new();
42
46656
        for field in form.fields {
43
222528
            match field.kind {
44
25152
                Kind::Rows { fields, .. } => self.rows_pairs(field.key, fields, &mut pairs),
45
197376
                _ => pairs.extend(self.text(field.key).map(|v| (field.key.into(), v.into()))),
46
            }
47
        }
48
46656
        pairs
49
46656
    }
50

            
51
25152
    fn rows_pairs(&self, key: &str, fields: &[Field], pairs: &mut Vec<(String, String)>) {
52
25152
        let Some(rows) = self.rows(key) else {
53
3264
            return;
54
        };
55
21888
        pairs.push((key.into(), String::new()));
56
21888
        for (index, row) in rows.iter().enumerate() {
57
29760
            let start = pairs.len();
58
29760
            for sub in fields {
59
136128
                let cell = row.get(sub.key);
60
136128
                pairs.extend(cell.map(|v| (address::cell(key, index, sub.key), v.clone())));
61
            }
62
29760
            if pairs.len() == start {
63
768
                pairs.push((address::row(key, index), String::new()));
64
28992
            }
65
        }
66
25152
    }
67
}
68

            
69
815040
fn normalize_newlines(value: &str) -> String {
70
815040
    value.replace("\r\n", "\n").replace('\r', "\n")
71
815040
}
72

            
73
5376
fn whole_form(message: String) -> FieldError {
74
5376
    FieldError {
75
5376
        field: String::new(),
76
5376
        message,
77
5376
    }
78
5376
}
79

            
80
527616
fn parse_index(text: &str) -> Option<usize> {
81
532032
    let canonical = text.bytes().all(|b| b.is_ascii_digit())
82
526848
        && !text.is_empty()
83
526656
        && (text == "0" || !text.starts_with('0'));
84
527616
    canonical.then(|| text.parse().ok()).flatten()
85
527616
}
86

            
87
899328
pub(crate) fn resolve<'a>(form: &'a Form, name: &str) -> Option<Address<'a>> {
88
5414016
    let find = |fields: &'a [Field], key: &str| fields.iter().find(|f| f.key == key);
89
899328
    match name.split('.').collect::<Vec<_>>()[..] {
90
370560
        [key] => find(form.fields, key).map(Address::Flat),
91
2112
        [key, index] => match find(form.fields, key)? {
92
            field @ Field {
93
                kind: Kind::Rows { .. },
94
                ..
95
1728
            } => Some(Address::Row(field, parse_index(index)?)),
96
192
            _ => None,
97
        },
98
        [key, index, cell] => {
99
526464
            let field = find(form.fields, key)?;
100
526080
            let Kind::Rows { fields, .. } = field.kind else {
101
192
                return None;
102
            };
103
            Some(Address::Cell(
104
525888
                field,
105
525888
                parse_index(index)?,
106
524544
                find(fields, cell)?,
107
            ))
108
        }
109
192
        _ => None,
110
    }
111
899328
}
112

            
113
#[derive(Default)]
114
struct Decoder<'a> {
115
    values: FormValues,
116
    seen: BTreeSet<String>,
117
    marked: BTreeSet<&'a str>,
118
    cells: BTreeMap<&'a str, BTreeMap<usize, Row>>,
119
    errors: Vec<FieldError>,
120
}
121

            
122
impl<'a> Decoder<'a> {
123
815040
    fn accept(&mut self, form: &'a Form, name: &str, value: String) {
124
815040
        if is_select_companion(form, name) {
125
45888
            return;
126
769152
        }
127
769152
        let Some(address) = resolve(form, name) else {
128
3456
            self.errors
129
3456
                .push(whole_form(format!("unknown field {name}")));
130
3456
            return;
131
        };
132
765696
        if !self.seen.insert(name.to_string()) {
133
960
            self.errors
134
960
                .push(whole_form(format!("duplicate field {name}")));
135
960
            return;
136
764736
        }
137
764736
        match address {
138
346176
            Address::Flat(field) if matches!(field.kind, Kind::Rows { .. }) => {
139
97152
                self.mark(field.key, name, value);
140
            }
141
            Address::Row(field, index) => {
142
1344
                if self.mark_row(name, value) {
143
1152
                    self.cells
144
1152
                        .entry(field.key)
145
1152
                        .or_default()
146
1152
                        .entry(index)
147
1152
                        .or_default();
148
192
                }
149
            }
150
249024
            Address::Flat(field) => self.values.set(field.key, &value),
151
            Address::Cell(field, index, cell) => {
152
417216
                let row = self.cells.entry(field.key).or_default().entry(index);
153
417216
                row.or_default().insert(cell.key.to_string(), value);
154
            }
155
        }
156
815040
    }
157

            
158
97152
    fn mark(&mut self, key: &'a str, name: &str, value: String) {
159
97152
        if self.mark_row(name, value) {
160
96960
            self.marked.insert(key);
161
192
        }
162
97152
    }
163

            
164
98496
    fn mark_row(&mut self, name: &str, value: String) -> bool {
165
98496
        let empty = value.is_empty();
166
98496
        if !empty {
167
384
            self.errors.push(FieldError {
168
384
                field: name.into(),
169
384
                message: "presence marker must be empty".into(),
170
384
            });
171
98112
        }
172
98496
        empty
173
98496
    }
174

            
175
116928
    fn finish(mut self) -> Result<FormValues, Vec<FieldError>> {
176
116928
        for key in std::mem::take(&mut self.marked) {
177
96960
            self.values.set_rows(key);
178
        }
179
116928
        for (key, rows) in std::mem::take(&mut self.cells) {
180
75456
            self.push_rows(key, rows);
181
        }
182
116928
        if self.errors.is_empty() {
183
111168
            Ok(self.values)
184
        } else {
185
5760
            Err(self.errors)
186
        }
187
116928
    }
188

            
189
75456
    fn push_rows(&mut self, key: &str, rows: BTreeMap<usize, Row>) {
190
75456
        for (expected, (index, row)) in rows.into_iter().enumerate() {
191
91392
            if index != expected {
192
960
                self.errors
193
960
                    .push(whole_form(format!("{key}: row {expected} is missing")));
194
960
                return;
195
90432
            }
196
90432
            self.values.push_row(key, row);
197
        }
198
75456
    }
199
}