Lines
69.23 %
Functions
5.56 %
Branches
100 %
use askama::Template;
use axum::{Extension, Json, extract::State, http::StatusCode, response::IntoResponse};
use serde::Deserialize;
use server::command::account::CreateAccount;
use std::sync::Arc;
use uuid::Uuid;
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate};
#[derive(Template)]
#[template(path = "pages/account/create.html")]
struct AccountCreatePage;
pub async fn account_create_page() -> impl IntoResponse {
let template = AccountCreatePage {};
HtmlTemplate(template)
}
#[template(path = "components/account/create.html")]
struct AccountFormTemplate;
pub async fn account_form() -> impl IntoResponse {
let template = AccountFormTemplate {};
#[derive(Deserialize)]
pub struct AccountForm {
name: String,
parent_id: Option<String>,
pub async fn create_account(
State(_data): State<Arc<AppState>>,
Extension(jwt_auth): Extension<JWTAuthMiddleware>,
Json(form): Json<AccountForm>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
let user = &jwt_auth.user;
// Parse parent UUID with proper error handling
let parent_id = if let Some(parent) = form.parent_id {
if parent.is_empty() {
None
} else if let Ok(id) = Uuid::parse_str(&parent) {
Some(id)
} else {
let error_response = serde_json::json!({
"status": "fail",
"message": t!("Invalid parent account ID format"),
});
return Err((StatusCode::BAD_REQUEST, Json(error_response)));
};
// Create the account using the new macro API
let mut builder = CreateAccount::new().name(form.name).user_id(user.id);
// Add parent if provided
if let Some(parent) = parent_id {
builder = builder.parent(parent);
match builder.run().await {
Ok(result) => match result {
Some(id) => Ok(format!("{}: {}", t!("New account id"), id)),
None => Ok("New account created".to_string()),
},
Err(e) => {
"message": t!("Failed to create account"),
log::error!("Failed to create account: {e:?}");
Err((StatusCode::INTERNAL_SERVER_ERROR, Json(error_response)))