Lines
99.09 %
Functions
25 %
Branches
100 %
//! Web adapters of the shared forms.
use std::collections::BTreeMap;
use axum::http::StatusCode;
use forms::{FieldError, Form, FormValues, Source};
use rpc::forms::{Failure, FormAction, FormOption, FormOutcome, record_form_request};
use uuid::Uuid;
use crate::form_render::References;
use crate::response::{UNAVAILABLE_MESSAGE, WebError};
pub mod attempt;
pub mod create;
pub mod edit;
pub mod message;
pub mod options;
pub mod request;
pub mod suggestions;
/// The error page for a form failure: a native's condition keeps its message and status; any
/// other internal cause is logged under `context` and never shown.
pub fn failure_error(context: &str, failure: Failure) -> WebError {
let status =
StatusCode::from_u16(failure.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
match failure {
Failure::Internal(_) if status == StatusCode::SERVICE_UNAVAILABLE => {
WebError::unavailable(UNAVAILABLE_MESSAGE)
}
Failure::Internal(error) if status == StatusCode::INTERNAL_SERVER_ERROR => {
WebError::internal(context, error)
Failure::Internal(error) => {
let message = rpc::host_failure::condition_text(&error);
WebError::new(status, message.unwrap_or_else(|| error.to_string()))
other => WebError::new(status, other.to_string()),
async fn try_options(user_id: Uuid, source: Source) -> Result<Vec<FormOption>, Failure> {
rpc::forms::options(user_id, source).await
async fn try_references(
user_id: Uuid,
typed: BTreeMap<String, String>,
filled: BTreeMap<String, bool>,
with_templates: bool,
) -> Result<References, Failure> {
let templates = match with_templates {
true => try_options(user_id, Source::Templates).await?,
false => Vec::new(),
};
Ok(References {
accounts: try_options(user_id, Source::Accounts).await?,
commodities: try_options(user_id, Source::Commodities).await?,
templates,
typed,
filled,
})
/// The options of the sources `form` selects from, which give each select
/// control its label, with the text `typed` into the controls of a submit.
pub async fn references(
form: &Form,
) -> Result<References, WebError> {
try_references(
user_id,
BTreeMap::new(),
form.has_source(Source::Templates),
)
.await
.map_err(|failure| failure_error("Form options failed", failure))
/// [`references`] for a request of `form`: a failure counts as that request's outcome.
async fn request_references(
action: FormAction,
if !form.has_select() {
return Ok(References {
..References::default()
});
count_failure(
form.name,
action,
try_references(user_id, typed, filled, form.has_source(Source::Templates)).await,
/// Counts only a failure; a success is counted later with the request.
fn count_failure<T>(
form: &str,
result: Result<T, Failure>,
) -> Result<T, Failure> {
if let Err(failure) = &result {
record_form_request(form, action, FormOutcome::from(failure));
result
/// A submit whose select texts pick no entity, or show another entity than
/// the id they carry, is refused before anything resolves: those errors and
/// the syntax errors of the other fields. Empty when every text was picked.
#[must_use]
fn unpicked_errors(form: &Form, values: &FormValues, references: &References) -> Vec<FieldError> {
let typed = &references.typed;
let mut errors = forms::labels::unpicked(form, typed, values);
errors.extend(forms::labels::mismatched(
form,
values,
|source, value| references.label_of(source, value),
));
if errors.is_empty() {
return errors;
let others: Vec<FieldError> = values
.check(form)
.into_iter()
.filter(|error| errors.iter().all(|unpicked| unpicked.field != error.field))
.collect();
errors.extend(others);
errors
/// The values of a posted or queried body; one that does not decode counts as malformed.
pub fn decode(
pairs: Vec<(String, String)>,
) -> Result<FormValues, WebError> {
FormValues::from_pairs(form, pairs).map_err(|errors| {
record_form_request(form.name, action, FormOutcome::Malformed);
unprocessable_fields(errors)
/// The 422 page naming each field error, for a request with no form to re-render.
pub fn unprocessable_fields(errors: Vec<FieldError>) -> WebError {
let messages: Vec<String> = errors
.map(|error| match error.field.as_str() {
"" => error.message,
field => format!("{field}: {}", error.message),
WebError::unprocessable(messages.join("; "))
#[cfg(test)]
#[path = "forms_tests.rs"]
mod tests;