1
//! The 422 of a report whose query is invalid.
2

            
3
use askama::Template;
4
use axum::http::{HeaderMap, StatusCode};
5
use axum::response::{Html, IntoResponse, Response};
6
use forms::Form;
7

            
8
use crate::form_invalid::form_invalid;
9
use crate::response::WebError;
10

            
11
/// The id of the element a report page loads its content into.
12
pub const SHELL_ID: &str = "report-shell";
13

            
14
#[derive(Template)]
15
#[template(path = "components/report/filters.html")]
16
struct 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.
24
pub type Editor<'a> = Option<&'a dyn Fn(bool) -> Result<String, WebError>>;
25

            
26
21
fn editor_html(editor: Editor, oob: bool) -> Result<String, WebError> {
27
21
    editor.map_or_else(|| Ok(String::new()), |render| render(oob))
28
21
}
29

            
30
21
fn loads_shell(headers: &HeaderMap) -> bool {
31
21
    headers
32
21
        .get("hx-trigger")
33
4
        .and_then(|value| value.to_str().ok())
34
21
        == Some(SHELL_ID)
35
21
}
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.
41
21
pub fn report_invalid(
42
21
    headers: &HeaderMap,
43
21
    form: &Form,
44
21
    form_html: String,
45
21
    shown: &[(String, String)],
46
21
    editor: Editor,
47
21
) -> Result<Response, WebError> {
48
21
    if !loads_shell(headers) {
49
19
        return Ok(form_invalid(form, form_html + &editor_html(editor, true)?));
50
2
    }
51
    let html = Filters {
52
2
        form: form_html,
53
2
        form_id: format!("nf-{}", form.name),
54
2
        shown,
55
2
        editor: editor_html(editor, false)?,
56
    }
57
    .render()
58
    .map_err(|e| WebError::internal("Report filters render failed", e))?;
59
2
    Ok((StatusCode::UNPROCESSABLE_ENTITY, Html(html)).into_response())
60
21
}
61

            
62
#[cfg(test)]
63
#[path = "invalid_tests.rs"]
64
mod tests;