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
    let template = AccountCreatePage {};
16
    HtmlTemplate(template)
17
}
18

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

            
23
pub async fn account_form() -> impl IntoResponse {
24
    let template = AccountFormTemplate {};
25
    HtmlTemplate(template)
26
}
27

            
28
#[derive(Deserialize)]
29
pub struct AccountForm {
30
    name: String,
31
    parent_id: Option<String>,
32
}
33

            
34
8
pub async fn create_account(
35
8
    State(_data): State<Arc<AppState>>,
36
8
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
37
8
    Json(form): Json<AccountForm>,
38
12
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
39
8
    let user = &jwt_auth.user;
40

            
41
    // Parse parent UUID with proper error handling
42

            
43
8
    let parent_id = if let Some(parent) = form.parent_id {
44
6
        if parent.is_empty() {
45
            None
46
6
        } else if let Ok(id) = Uuid::parse_str(&parent) {
47
2
            Some(id)
48
        } else {
49
4
            let error_response = serde_json::json!({
50
4
                "status": "fail",
51
4
                "message": t!("Invalid parent account ID format"),
52
            });
53
4
            return Err((StatusCode::BAD_REQUEST, Json(error_response)));
54
        }
55
    } else {
56
2
        None
57
    };
58

            
59
    // Create the account using the new macro API
60
4
    let mut builder = CreateAccount::new().name(form.name).user_id(user.id);
61

            
62
    // Add parent if provided
63
4
    if let Some(parent) = parent_id {
64
2
        builder = builder.parent(parent);
65
2
    }
66

            
67
4
    match builder.run().await {
68
        Ok(result) => match result {
69
            Some(id) => Ok(format!("{}: {}", t!("New account id"), id)),
70
            None => Ok("New account created".to_string()),
71
        },
72
4
        Err(e) => {
73
4
            let error_response = serde_json::json!({
74
4
                "status": "fail",
75
4
                "message": t!("Failed to create account"),
76
            });
77

            
78
4
            log::error!("Failed to create account: {e:?}");
79
4
            Err((StatusCode::INTERNAL_SERVER_ERROR, Json(error_response)))
80
        }
81
    }
82
8
}