1
//! The commodity edit page over the shared forms: `COMMODITY_EDIT` loaded by
2
//! `rpc::forms::load` and submitted through `rpc::forms::submit`.
3

            
4
use askama::Template;
5
use axum::{
6
    Extension, Form,
7
    extract::Path,
8
    response::{IntoResponse, Response},
9
};
10
use forms::COMMODITY_EDIT;
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/commodity/edit";
20

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

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

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

            
41
7
pub async fn commodity_edit_page(
42
7
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
43
7
    Path(id): Path<String>,
44
7
) -> Result<impl IntoResponse, WebError> {
45
7
    let form = EDIT.loaded_form(jwt_auth.user.id, &id).await?;
46
5
    Ok(HtmlTemplate(EditPage { form }))
47
7
}
48

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