Skip to main content

web/pages/template/
edit.rs

1//! The template edit page over the `template-edit` form, and the template delete.
2
3use askama::Template;
4use axum::{
5    Extension, Form,
6    extract::Path,
7    response::{IntoResponse, Response},
8};
9use forms::TEMPLATE_EDIT;
10use server::command::template::DeleteTemplate;
11use uuid::Uuid;
12
13use super::draft::TEST_PATH;
14use crate::pages::{
15    HtmlTemplate,
16    forms::edit::{Edit, Edited},
17};
18use crate::{jwt_auth::JWTAuthMiddleware, parse::parse_uuid, response::WebError};
19
20pub const SUBMIT_PATH: &str = "/api/template/edit/submit";
21
22const 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")]
32struct TemplateEditPage {
33    id: Uuid,
34    form: String,
35    test_path: &'static str,
36}
37
38fn parse_template_id(raw: &str) -> Result<Uuid, WebError> {
39    parse_uuid(raw, "template ID")
40}
41
42/// The message of a successful edit, shown in the form's result box.
43#[must_use]
44pub fn updated_message(id: Uuid) -> String {
45    format!("{}: {id}", t!("Template updated"))
46}
47
48pub async fn template_edit_page(
49    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
50    Path(id): Path<String>,
51) -> Result<impl IntoResponse, WebError> {
52    let id = parse_template_id(&id)?;
53    let form = EDIT.loaded_form(jwt_auth.user.id, &id.to_string()).await?;
54    Ok(HtmlTemplate(TemplateEditPage {
55        id,
56        form,
57        test_path: TEST_PATH,
58    }))
59}
60
61pub async fn template_edit_submit(
62    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
63    Form(pairs): Form<Vec<(String, String)>>,
64) -> Result<Response, WebError> {
65    Ok(match EDIT.submit(jwt_auth.user.id, pairs).await? {
66        Edited::Saved { id, .. } => {
67            EDIT.saved_response(jwt_auth.user.id, id, updated_message(id))
68                .await?
69        }
70        Edited::Invalid(response) => response,
71    })
72}
73
74pub async fn delete_template(
75    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
76    Path(id): Path<String>,
77) -> Result<impl IntoResponse, WebError> {
78    let id = parse_template_id(&id)?;
79    DeleteTemplate::new()
80        .user_id(jwt_auth.user.id)
81        .template_id(id)
82        .run()
83        .await?;
84    Ok(format!("{}: {id}", t!("Template deleted")))
85}
86
87#[cfg(test)]
88#[path = "edit_tests.rs"]
89mod tests;