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

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

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

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

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

            
29
#[derive(Template)]
30
#[template(path = "pages/script/edit.html")]
31
struct ScriptEditPage {
32
    id: Uuid,
33
    form: String,
34
    notice: Option<String>,
35
}
36

            
37
20
fn parse_script_id(raw: &str) -> Result<Uuid, WebError> {
38
20
    parse_uuid(raw, "script ID")
39
20
}
40

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

            
47
9
pub async fn script_edit_page(
48
9
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
49
9
    Path(id): Path<String>,
50
9
) -> Result<impl IntoResponse, WebError> {
51
9
    let id = parse_script_id(&id)?;
52
8
    let (form, notice) = EDIT
53
8
        .loaded_noticed(jwt_auth.user.id, &id.to_string())
54
8
        .await?;
55
5
    Ok(HtmlTemplate(ScriptEditPage { id, form, notice }))
56
9
}
57

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

            
71
7
pub async fn delete_script(
72
7
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
73
7
    Path(id): Path<String>,
74
7
) -> Result<impl IntoResponse, WebError> {
75
7
    let id = parse_script_id(&id)?;
76
6
    DeleteScript::new()
77
6
        .user_id(jwt_auth.user.id)
78
6
        .script_id(id)
79
6
        .run()
80
6
        .await?;
81
2
    Ok(format!("{}: {id}", t!("Script deleted")))
82
7
}
83

            
84
#[cfg(test)]
85
#[path = "edit_tests.rs"]
86
mod tests;