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

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

            
13
use crate::pages::{
14
    HtmlTemplate,
15
    forms::edit::{Edit, Edited},
16
};
17
use crate::{jwt_auth::JWTAuthMiddleware, response::WebError};
18

            
19
pub const SUBMIT_PATH: &str = "/api/tag/edit/submit";
20

            
21
const EDIT: Edit = Edit {
22
    form: &TAG_EDIT,
23
    noun: "Tag",
24
    action: SUBMIT_PATH,
25
    page: "/tag/edit/{id}",
26
    remedy: "",
27
};
28

            
29
#[derive(Template)]
30
#[template(path = "pages/tag/edit.html")]
31
struct TagEditPage {
32
    id: Uuid,
33
    form: String,
34
}
35

            
36
/// The message of a successful edit, shown in the form's result box.
37
#[must_use]
38
5
pub fn updated_message(id: Uuid) -> String {
39
5
    format!("{}: {id}", t!("Tag updated"))
40
5
}
41

            
42
8
pub async fn tag_edit_page(
43
8
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
44
8
    Path(id): Path<Uuid>,
45
8
) -> Result<impl IntoResponse, WebError> {
46
8
    let form = EDIT.loaded_form(jwt_auth.user.id, &id.to_string()).await?;
47
5
    Ok(HtmlTemplate(TagEditPage { id, form }))
48
8
}
49

            
50
7
pub async fn tag_edit_submit(
51
7
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
52
7
    Form(pairs): Form<Vec<(String, String)>>,
53
7
) -> Result<Response, WebError> {
54
7
    Ok(match EDIT.submit(jwt_auth.user.id, pairs).await? {
55
        Edited::Saved { id, .. } => {
56
2
            EDIT.saved_response(jwt_auth.user.id, id, updated_message(id))
57
2
                .await?
58
        }
59
2
        Edited::Invalid(response) => response,
60
    })
61
7
}
62

            
63
2
pub async fn delete_tag(
64
2
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
65
2
    Path(id): Path<Uuid>,
66
2
) -> Result<impl IntoResponse, WebError> {
67
2
    DeleteTag::new()
68
2
        .user_id(jwt_auth.user.id)
69
2
        .tag_id(id)
70
2
        .run()
71
2
        .await?;
72
1
    Ok(t!("Tag deleted"))
73
2
}
74

            
75
#[cfg(test)]
76
#[path = "edit_tests.rs"]
77
mod tests;