Skip to main content

web/pages/forms/
mod.rs

1//! Web adapters of the shared forms.
2
3use std::collections::BTreeMap;
4
5use axum::http::StatusCode;
6use forms::{FieldError, Form, FormValues, Source};
7use rpc::forms::{Failure, FormAction, FormOption, FormOutcome, record_form_request};
8use uuid::Uuid;
9
10use crate::form_render::References;
11use crate::response::{UNAVAILABLE_MESSAGE, WebError};
12
13pub mod attempt;
14pub mod create;
15pub mod edit;
16pub mod message;
17pub mod options;
18pub mod request;
19pub 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.
23pub fn failure_error(context: &str, failure: Failure) -> WebError {
24    let status =
25        StatusCode::from_u16(failure.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
26    match failure {
27        Failure::Internal(_) if status == StatusCode::SERVICE_UNAVAILABLE => {
28            WebError::unavailable(UNAVAILABLE_MESSAGE)
29        }
30        Failure::Internal(error) if status == StatusCode::INTERNAL_SERVER_ERROR => {
31            WebError::internal(context, error)
32        }
33        Failure::Internal(error) => {
34            let message = rpc::host_failure::condition_text(&error);
35            WebError::new(status, message.unwrap_or_else(|| error.to_string()))
36        }
37        other => WebError::new(status, other.to_string()),
38    }
39}
40
41async fn try_options(user_id: Uuid, source: Source) -> Result<Vec<FormOption>, Failure> {
42    rpc::forms::options(user_id, source).await
43}
44
45async fn try_references(
46    user_id: Uuid,
47    typed: BTreeMap<String, String>,
48    filled: BTreeMap<String, bool>,
49    with_templates: bool,
50) -> Result<References, Failure> {
51    let templates = match with_templates {
52        true => try_options(user_id, Source::Templates).await?,
53        false => Vec::new(),
54    };
55    Ok(References {
56        accounts: try_options(user_id, Source::Accounts).await?,
57        commodities: try_options(user_id, Source::Commodities).await?,
58        templates,
59        typed,
60        filled,
61    })
62}
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.
66pub async fn references(
67    form: &Form,
68    user_id: Uuid,
69    typed: BTreeMap<String, String>,
70) -> Result<References, WebError> {
71    try_references(
72        user_id,
73        typed,
74        BTreeMap::new(),
75        form.has_source(Source::Templates),
76    )
77    .await
78    .map_err(|failure| failure_error("Form options failed", failure))
79}
80
81/// [`references`] for a request of `form`: a failure counts as that request's outcome.
82async fn request_references(
83    form: &Form,
84    action: FormAction,
85    user_id: Uuid,
86    typed: BTreeMap<String, String>,
87    filled: BTreeMap<String, bool>,
88) -> Result<References, WebError> {
89    if !form.has_select() {
90        return Ok(References {
91            typed,
92            filled,
93            ..References::default()
94        });
95    }
96    count_failure(
97        form.name,
98        action,
99        try_references(user_id, typed, filled, form.has_source(Source::Templates)).await,
100    )
101    .map_err(|failure| failure_error("Form options failed", failure))
102}
103
104/// Counts only a failure; a success is counted later with the request.
105fn count_failure<T>(
106    form: &str,
107    action: FormAction,
108    result: Result<T, Failure>,
109) -> Result<T, Failure> {
110    if let Err(failure) = &result {
111        record_form_request(form, action, FormOutcome::from(failure));
112    }
113    result
114}
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]
120fn unpicked_errors(form: &Form, values: &FormValues, references: &References) -> Vec<FieldError> {
121    let typed = &references.typed;
122    let mut errors = forms::labels::unpicked(form, typed, values);
123    errors.extend(forms::labels::mismatched(
124        form,
125        typed,
126        values,
127        |source, value| references.label_of(source, value),
128    ));
129    if errors.is_empty() {
130        return errors;
131    }
132    let others: Vec<FieldError> = values
133        .check(form)
134        .into_iter()
135        .filter(|error| errors.iter().all(|unpicked| unpicked.field != error.field))
136        .collect();
137    errors.extend(others);
138    errors
139}
140
141/// The values of a posted or queried body; one that does not decode counts as malformed.
142pub fn decode(
143    form: &Form,
144    action: FormAction,
145    pairs: Vec<(String, String)>,
146) -> Result<FormValues, WebError> {
147    FormValues::from_pairs(form, pairs).map_err(|errors| {
148        record_form_request(form.name, action, FormOutcome::Malformed);
149        unprocessable_fields(errors)
150    })
151}
152
153/// The 422 page naming each field error, for a request with no form to re-render.
154pub fn unprocessable_fields(errors: Vec<FieldError>) -> WebError {
155    let messages: Vec<String> = errors
156        .into_iter()
157        .map(|error| match error.field.as_str() {
158            "" => error.message,
159            field => format!("{field}: {}", error.message),
160        })
161        .collect();
162    WebError::unprocessable(messages.join("; "))
163}
164
165#[cfg(test)]
166#[path = "forms_tests.rs"]
167mod tests;