1
use askama::Template;
2
use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
3
use serde::Deserialize;
4
use server::command::account::CreateAccount;
5
use std::sync::Arc;
6
use uuid::Uuid;
7

            
8
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate};
9

            
10
#[derive(Template)]
11
#[template(path = "pages/account/create.html")]
12
struct AccountCreatePage;
13

            
14
pub async fn account_create_page() -> impl IntoResponse {
15
    HtmlTemplate(AccountCreatePage)
16
}
17

            
18
#[derive(Template)]
19
#[template(path = "components/account/create.html")]
20
struct AccountFormTemplate;
21

            
22
#[derive(Deserialize)]
23
pub struct AccountForm {
24
    name: String,
25
    parent_id: Option<String>,
26
}
27

            
28
4
pub async fn create_account(
29
4
    State(_data): State<Arc<AppState>>,
30
4
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
31
4
    Json(form): Json<AccountForm>,
32
4
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
33
4
    let user = &jwt_auth.user;
34

            
35
    // Parse parent UUID with proper error handling
36

            
37
4
    let parent_id = if let Some(parent) = form.parent_id {
38
3
        if parent.is_empty() {
39
            None
40
3
        } else if let Ok(id) = Uuid::parse_str(&parent) {
41
1
            Some(id)
42
        } else {
43
2
            let error_response = serde_json::json!({
44
2
                "status": "fail",
45
2
                "message": t!("Invalid parent account ID format"),
46
            });
47
2
            return Err((StatusCode::BAD_REQUEST, Json(error_response)));
48
        }
49
    } else {
50
1
        None
51
    };
52

            
53
    // Create the account using the new macro API
54
2
    let mut builder = CreateAccount::new().name(form.name).user_id(user.id);
55

            
56
    // Add parent if provided
57
2
    if let Some(parent) = parent_id {
58
1
        builder = builder.parent(parent);
59
1
    }
60

            
61
2
    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
2
        Err(e) => {
67
2
            let error_response = serde_json::json!({
68
2
                "status": "fail",
69
2
                "message": t!("Failed to create account"),
70
            });
71

            
72
2
            log::error!("Failed to create account: {e:?}");
73
2
            Err((StatusCode::INTERNAL_SERVER_ERROR, Json(error_response)))
74
        }
75
    }
76
4
}