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
22pub async fn account_form() -> impl IntoResponse {
23    HtmlTemplate(AccountFormTemplate)
24}
25
26#[derive(Deserialize)]
27pub struct AccountForm {
28    name: String,
29    parent_id: Option<String>,
30}
31
32pub async fn create_account(
33    State(_data): State<Arc<AppState>>,
34    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
35    Json(form): Json<AccountForm>,
36) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
37    let user = &jwt_auth.user;
38
39    // Parse parent UUID with proper error handling
40
41    let parent_id = if let Some(parent) = form.parent_id {
42        if parent.is_empty() {
43            None
44        } else if let Ok(id) = Uuid::parse_str(&parent) {
45            Some(id)
46        } else {
47            let error_response = serde_json::json!({
48                "status": "fail",
49                "message": t!("Invalid parent account ID format"),
50            });
51            return Err((StatusCode::BAD_REQUEST, Json(error_response)));
52        }
53    } else {
54        None
55    };
56
57    // Create the account using the new macro API
58    let mut builder = CreateAccount::new().name(form.name).user_id(user.id);
59
60    // Add parent if provided
61    if let Some(parent) = parent_id {
62        builder = builder.parent(parent);
63    }
64
65    match builder.run().await {
66        Ok(result) => match result {
67            Some(id) => Ok(format!("{}: {}", t!("New account id"), id)),
68            None => Ok("New account created".to_string()),
69        },
70        Err(e) => {
71            let error_response = serde_json::json!({
72                "status": "fail",
73                "message": t!("Failed to create account"),
74            });
75
76            log::error!("Failed to create account: {e:?}");
77            Err((StatusCode::INTERNAL_SERVER_ERROR, Json(error_response)))
78        }
79    }
80}