1
//! Web adapters of the shared forms.
2

            
3
use std::collections::BTreeMap;
4

            
5
use axum::http::StatusCode;
6
use forms::{FieldError, Form, FormValues, Source};
7
use rpc::forms::{Failure, FormAction, FormOption, FormOutcome, record_form_request};
8
use uuid::Uuid;
9

            
10
use crate::form_render::References;
11
use crate::response::{UNAVAILABLE_MESSAGE, WebError};
12

            
13
pub mod attempt;
14
pub mod create;
15
pub mod edit;
16
pub mod message;
17
pub mod options;
18
pub mod request;
19
pub mod suggestions;
20

            
21
/// The error page for a form failure: a native's condition keeps its message and status; any
22
/// other internal cause is logged under `context` and never shown.
23
42
pub fn failure_error(context: &str, failure: Failure) -> WebError {
24
    let status =
25
42
        StatusCode::from_u16(failure.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
26
42
    match failure {
27
20
        Failure::Internal(_) if status == StatusCode::SERVICE_UNAVAILABLE => {
28
10
            WebError::unavailable(UNAVAILABLE_MESSAGE)
29
        }
30
10
        Failure::Internal(error) if status == StatusCode::INTERNAL_SERVER_ERROR => {
31
3
            WebError::internal(context, error)
32
        }
33
        Failure::Internal(error) => {
34
7
            let message = rpc::host_failure::condition_text(&error);
35
7
            WebError::new(status, message.unwrap_or_else(|| error.to_string()))
36
        }
37
22
        other => WebError::new(status, other.to_string()),
38
    }
39
42
}
40

            
41
688
async fn try_options(user_id: Uuid, source: Source) -> Result<Vec<FormOption>, Failure> {
42
688
    rpc::forms::options(user_id, source).await
43
688
}
44

            
45
344
async fn try_references(
46
344
    user_id: Uuid,
47
344
    typed: BTreeMap<String, String>,
48
344
    filled: BTreeMap<String, bool>,
49
344
    with_templates: bool,
50
344
) -> Result<References, Failure> {
51
344
    let templates = match with_templates {
52
2
        true => try_options(user_id, Source::Templates).await?,
53
342
        false => Vec::new(),
54
    };
55
    Ok(References {
56
344
        accounts: try_options(user_id, Source::Accounts).await?,
57
342
        commodities: try_options(user_id, Source::Commodities).await?,
58
342
        templates,
59
342
        typed,
60
342
        filled,
61
    })
62
344
}
63

            
64
/// The options of the sources `form` selects from, which give each select
65
/// control its label, with the text `typed` into the controls of a submit.
66
81
pub async fn references(
67
81
    form: &Form,
68
81
    user_id: Uuid,
69
81
    typed: BTreeMap<String, String>,
70
81
) -> Result<References, WebError> {
71
81
    try_references(
72
81
        user_id,
73
81
        typed,
74
81
        BTreeMap::new(),
75
81
        form.has_source(Source::Templates),
76
81
    )
77
81
    .await
78
    .map_err(|failure| failure_error("Form options failed", failure))
79
81
}
80

            
81
/// [`references`] for a request of `form`: a failure counts as that request's outcome.
82
320
async fn request_references(
83
320
    form: &Form,
84
320
    action: FormAction,
85
320
    user_id: Uuid,
86
320
    typed: BTreeMap<String, String>,
87
320
    filled: BTreeMap<String, bool>,
88
320
) -> Result<References, WebError> {
89
320
    if !form.has_select() {
90
57
        return Ok(References {
91
57
            typed,
92
57
            filled,
93
57
            ..References::default()
94
57
        });
95
263
    }
96
263
    count_failure(
97
263
        form.name,
98
263
        action,
99
263
        try_references(user_id, typed, filled, form.has_source(Source::Templates)).await,
100
    )
101
2
    .map_err(|failure| failure_error("Form options failed", failure))
102
320
}
103

            
104
/// Counts only a failure; a success is counted later with the request.
105
263
fn count_failure<T>(
106
263
    form: &str,
107
263
    action: FormAction,
108
263
    result: Result<T, Failure>,
109
263
) -> Result<T, Failure> {
110
263
    if let Err(failure) = &result {
111
2
        record_form_request(form, action, FormOutcome::from(failure));
112
261
    }
113
263
    result
114
263
}
115

            
116
/// A submit whose select texts pick no entity, or show another entity than
117
/// the id they carry, is refused before anything resolves: those errors and
118
/// the syntax errors of the other fields. Empty when every text was picked.
119
#[must_use]
120
317
fn unpicked_errors(form: &Form, values: &FormValues, references: &References) -> Vec<FieldError> {
121
317
    let typed = &references.typed;
122
317
    let mut errors = forms::labels::unpicked(form, typed, values);
123
317
    errors.extend(forms::labels::mismatched(
124
317
        form,
125
317
        typed,
126
317
        values,
127
94
        |source, value| references.label_of(source, value),
128
    ));
129
317
    if errors.is_empty() {
130
313
        return errors;
131
4
    }
132
4
    let others: Vec<FieldError> = values
133
4
        .check(form)
134
4
        .into_iter()
135
5
        .filter(|error| errors.iter().all(|unpicked| unpicked.field != error.field))
136
        .collect();
137
4
    errors.extend(others);
138
4
    errors
139
317
}
140

            
141
/// The values of a posted or queried body; one that does not decode counts as malformed.
142
324
pub fn decode(
143
324
    form: &Form,
144
324
    action: FormAction,
145
324
    pairs: Vec<(String, String)>,
146
324
) -> Result<FormValues, WebError> {
147
324
    FormValues::from_pairs(form, pairs).map_err(|errors| {
148
4
        record_form_request(form.name, action, FormOutcome::Malformed);
149
4
        unprocessable_fields(errors)
150
4
    })
151
324
}
152

            
153
/// The 422 page naming each field error, for a request with no form to re-render.
154
19
pub fn unprocessable_fields(errors: Vec<FieldError>) -> WebError {
155
19
    let messages: Vec<String> = errors
156
19
        .into_iter()
157
19
        .map(|error| match error.field.as_str() {
158
4
            "" => error.message,
159
15
            field => format!("{field}: {}", error.message),
160
19
        })
161
        .collect();
162
19
    WebError::unprocessable(messages.join("; "))
163
19
}
164

            
165
#[cfg(test)]
166
#[path = "forms_tests.rs"]
167
mod tests;