web/pages/commodity/create/
submit.rs1use std::sync::Arc;
2
3use askama::Template;
4use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
5use serde::Deserialize;
6
7use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate};
8
9#[derive(Template)]
10#[template(path = "pages/commodity/create.html")]
11struct CommodityCreatePage;
12
13pub async fn commodity_create_page() -> impl IntoResponse {
14 let template = CommodityCreatePage {};
15 HtmlTemplate(template)
16}
17
18#[derive(Template)]
19#[template(path = "components/commodity/create.html")]
20struct CommodityFormTemplate;
21
22pub async fn commodity_form() -> impl IntoResponse {
23 let template = CommodityFormTemplate {};
24 HtmlTemplate(template)
25}
26
27#[derive(Deserialize)]
28pub struct CommodityForm {
29 symbol: String,
30 name: String,
31}
32
33pub async fn commodity_submit(
34 State(_data): State<Arc<AppState>>,
35 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
36 Json(form): Json<CommodityForm>,
37) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
38 let user = &jwt_auth.user;
39
40 match server::command::commodity::CreateCommodity::new()
42 .symbol(form.symbol)
43 .name(form.name)
44 .user_id(user.id)
45 .run()
46 .await
47 {
48 Ok(result) => match result {
49 Some(id) => Ok(format!("{}: {}", t!("New commodity id"), id)),
50 None => Ok("New commodity created".to_string()),
51 },
52 Err(e) => {
53 let error_response = serde_json::json!({
54 "status": "fail",
55 "message": t!("Failed to create commodity"),
56 });
57
58 log::error!("Failed to create commodity: {e:?}");
59 Err((StatusCode::INTERNAL_SERVER_ERROR, Json(error_response)))
60 }
61 }
62}