Skip to main content

web/pages/commodity/
edit.rs

1//! The commodity edit page over the shared forms: `COMMODITY_EDIT` loaded by
2//! `rpc::forms::load` and submitted through `rpc::forms::submit`.
3
4use askama::Template;
5use axum::{
6    Extension, Form,
7    extract::Path,
8    response::{IntoResponse, Response},
9};
10use forms::COMMODITY_EDIT;
11use uuid::Uuid;
12
13use crate::pages::{
14    HtmlTemplate,
15    forms::edit::{Edit, Edited},
16};
17use crate::{jwt_auth::JWTAuthMiddleware, response::WebError};
18
19pub const SUBMIT_PATH: &str = "/api/commodity/edit";
20
21const 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")]
31struct EditPage {
32    form: String,
33}
34
35/// The message of a successful edit, shown in the form's result box.
36#[must_use]
37pub fn updated_message(id: Uuid) -> String {
38    format!("{}: {id}", t!("Commodity updated with ID"))
39}
40
41pub async fn commodity_edit_page(
42    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
43    Path(id): Path<String>,
44) -> Result<impl IntoResponse, WebError> {
45    let form = EDIT.loaded_form(jwt_auth.user.id, &id).await?;
46    Ok(HtmlTemplate(EditPage { form }))
47}
48
49pub async fn commodity_edit_submit(
50    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
51    Form(pairs): Form<Vec<(String, String)>>,
52) -> Result<Response, WebError> {
53    let edited = EDIT.submit(jwt_auth.user.id, pairs).await?;
54    Ok(match edited {
55        Edited::Saved { id, .. } => {
56            EDIT.saved_response(jwt_auth.user.id, id, updated_message(id))
57                .await?
58        }
59        Edited::Invalid(response) => response,
60    })
61}