Skip to main content

web/pages/report/
invalid.rs

1//! The 422 of a report whose query is invalid.
2
3use askama::Template;
4use axum::http::{HeaderMap, StatusCode};
5use axum::response::{Html, IntoResponse, Response};
6use forms::Form;
7
8use crate::form_invalid::form_invalid;
9use crate::response::WebError;
10
11/// The id of the element a report page loads its content into.
12pub const SHELL_ID: &str = "report-shell";
13
14#[derive(Template)]
15#[template(path = "components/report/filters.html")]
16struct Filters<'a> {
17    form: String,
18    form_id: String,
19    shown: &'a [(String, String)],
20    editor: String,
21}
22
23/// Renders the rows editor beside the form; `true` swaps it in out of band.
24pub type Editor<'a> = Option<&'a dyn Fn(bool) -> Result<String, WebError>>;
25
26fn editor_html(editor: Editor, oob: bool) -> Result<String, WebError> {
27    editor.map_or_else(|| Ok(String::new()), |render| render(oob))
28}
29
30fn loads_shell(headers: &HeaderMap) -> bool {
31    headers
32        .get("hx-trigger")
33        .and_then(|value| value.to_str().ok())
34        == Some(SHELL_ID)
35}
36
37/// The refused report: the form replaces itself on a loaded table, but a
38/// page that loads the table has no form yet, so it gets the form inside its
39/// own filters wrapper, which also carries the `shown` table and chart
40/// controls the corrected submit must not lose.
41pub fn report_invalid(
42    headers: &HeaderMap,
43    form: &Form,
44    form_html: String,
45    shown: &[(String, String)],
46    editor: Editor,
47) -> Result<Response, WebError> {
48    if !loads_shell(headers) {
49        return Ok(form_invalid(form, form_html + &editor_html(editor, true)?));
50    }
51    let html = Filters {
52        form: form_html,
53        form_id: format!("nf-{}", form.name),
54        shown,
55        editor: editor_html(editor, false)?,
56    }
57    .render()
58    .map_err(|e| WebError::internal("Report filters render failed", e))?;
59    Ok((StatusCode::UNPROCESSABLE_ENTITY, Html(html)).into_response())
60}
61
62#[cfg(test)]
63#[path = "invalid_tests.rs"]
64mod tests;