Lines
70.27 %
Functions
5.56 %
Branches
100 %
use std::sync::Arc;
use askama::Template;
use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
use serde::Deserialize;
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate};
#[derive(Template)]
#[template(path = "pages/commodity/create.html")]
struct CommodityCreatePage;
pub async fn commodity_create_page() -> impl IntoResponse {
let template = CommodityCreatePage {};
HtmlTemplate(template)
}
#[template(path = "components/commodity/create.html")]
struct CommodityFormTemplate;
pub async fn commodity_form() -> impl IntoResponse {
let template = CommodityFormTemplate {};
#[derive(Deserialize)]
pub struct CommodityForm {
fraction: String,
symbol: String,
name: String,
pub async fn commodity_submit(
State(_data): State<Arc<AppState>>,
Extension(jwt_auth): Extension<JWTAuthMiddleware>,
Json(form): Json<CommodityForm>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
let user = &jwt_auth.user;
// Parse the fraction with proper error handling
let fraction_value = if let Ok(val) = form.fraction.parse::<i64>() {
val
} else {
let error_response = serde_json::json!({
"status": "fail",
"message": t!("Provide the correct fraction value"),
});
return Err((StatusCode::BAD_REQUEST, Json(error_response)));
};
// Execute command
match server::command::commodity::CreateCommodity::new()
.fraction(fraction_value.into())
.symbol(form.symbol)
.name(form.name)
.user_id(user.id)
.run()
.await
{
Ok(result) => match result {
Some(id) => Ok(format!("{}: {}", t!("New commodity id"), id)),
None => Ok("New commodity created".to_string()),
},
Err(e) => {
"message": t!("Failed to create commodity"),
log::error!("Failed to create commodity: {e:?}");
Err((StatusCode::INTERNAL_SERVER_ERROR, Json(error_response)))