1
//! The template edit page over the `template-edit` form, and the template delete.
2

            
3
use askama::Template;
4
use axum::{
5
    Extension, Form,
6
    extract::Path,
7
    response::{IntoResponse, Response},
8
};
9
use forms::TEMPLATE_EDIT;
10
use server::command::template::DeleteTemplate;
11
use uuid::Uuid;
12

            
13
use super::draft::TEST_PATH;
14
use crate::pages::{
15
    HtmlTemplate,
16
    forms::edit::{Edit, Edited},
17
};
18
use crate::{jwt_auth::JWTAuthMiddleware, parse::parse_uuid, response::WebError};
19

            
20
pub const SUBMIT_PATH: &str = "/api/template/edit/submit";
21

            
22
const EDIT: Edit = Edit {
23
    form: &TEMPLATE_EDIT,
24
    noun: "Template",
25
    action: SUBMIT_PATH,
26
    page: "/template/edit/{id}",
27
    remedy: "",
28
};
29

            
30
#[derive(Template)]
31
#[template(path = "pages/template/edit.html")]
32
struct TemplateEditPage {
33
    id: Uuid,
34
    form: String,
35
    test_path: &'static str,
36
}
37

            
38
15
fn parse_template_id(raw: &str) -> Result<Uuid, WebError> {
39
15
    parse_uuid(raw, "template ID")
40
15
}
41

            
42
/// The message of a successful edit, shown in the form's result box.
43
#[must_use]
44
5
pub fn updated_message(id: Uuid) -> String {
45
5
    format!("{}: {id}", t!("Template updated"))
46
5
}
47

            
48
8
pub async fn template_edit_page(
49
8
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
50
8
    Path(id): Path<String>,
51
8
) -> Result<impl IntoResponse, WebError> {
52
8
    let id = parse_template_id(&id)?;
53
7
    let form = EDIT.loaded_form(jwt_auth.user.id, &id.to_string()).await?;
54
4
    Ok(HtmlTemplate(TemplateEditPage {
55
4
        id,
56
4
        form,
57
4
        test_path: TEST_PATH,
58
4
    }))
59
8
}
60

            
61
4
pub async fn template_edit_submit(
62
4
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
63
4
    Form(pairs): Form<Vec<(String, String)>>,
64
4
) -> Result<Response, WebError> {
65
4
    Ok(match EDIT.submit(jwt_auth.user.id, pairs).await? {
66
        Edited::Saved { id, .. } => {
67
2
            EDIT.saved_response(jwt_auth.user.id, id, updated_message(id))
68
2
                .await?
69
        }
70
2
        Edited::Invalid(response) => response,
71
    })
72
4
}
73

            
74
3
pub async fn delete_template(
75
3
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
76
3
    Path(id): Path<String>,
77
3
) -> Result<impl IntoResponse, WebError> {
78
3
    let id = parse_template_id(&id)?;
79
2
    DeleteTemplate::new()
80
2
        .user_id(jwt_auth.user.id)
81
2
        .template_id(id)
82
2
        .run()
83
2
        .await?;
84
1
    Ok(format!("{}: {id}", t!("Template deleted")))
85
3
}
86

            
87
#[cfg(test)]
88
#[path = "edit_tests.rs"]
89
mod tests;