Skip to main content

web/pages/account/create/
submit.rs

1use askama::Template;
2use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
3use serde::Deserialize;
4use server::command::account::CreateAccount;
5use std::sync::Arc;
6use uuid::Uuid;
7
8use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate};
9
10#[derive(Template)]
11#[template(path = "pages/account/create.html")]
12struct AccountCreatePage;
13
14pub async fn account_create_page() -> impl IntoResponse {
15    HtmlTemplate(AccountCreatePage)
16}
17
18#[derive(Template)]
19#[template(path = "components/account/create.html")]
20struct AccountFormTemplate;
21
22#[derive(Deserialize)]
23pub struct AccountForm {
24    name: String,
25    parent_id: Option<String>,
26}
27
28pub async fn create_account(
29    State(_data): State<Arc<AppState>>,
30    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
31    Json(form): Json<AccountForm>,
32) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
33    let user = &jwt_auth.user;
34
35    // Parse parent UUID with proper error handling
36
37    let parent_id = if let Some(parent) = form.parent_id {
38        if parent.is_empty() {
39            None
40        } else if let Ok(id) = Uuid::parse_str(&parent) {
41            Some(id)
42        } else {
43            let error_response = serde_json::json!({
44                "status": "fail",
45                "message": t!("Invalid parent account ID format"),
46            });
47            return Err((StatusCode::BAD_REQUEST, Json(error_response)));
48        }
49    } else {
50        None
51    };
52
53    // Create the account using the new macro API
54    let mut builder = CreateAccount::new().name(form.name).user_id(user.id);
55
56    // Add parent if provided
57    if let Some(parent) = parent_id {
58        builder = builder.parent(parent);
59    }
60
61    match builder.run().await {
62        Ok(result) => match result {
63            Some(id) => Ok(format!("{}: {}", t!("New account id"), id)),
64            None => Ok("New account created".to_string()),
65        },
66        Err(e) => {
67            let error_response = serde_json::json!({
68                "status": "fail",
69                "message": t!("Failed to create account"),
70            });
71
72            log::error!("Failed to create account: {e:?}");
73            Err((StatusCode::INTERNAL_SERVER_ERROR, Json(error_response)))
74        }
75    }
76}