Lines
88 %
Functions
37.5 %
Branches
100 %
use std::{collections::HashMap, sync::Arc};
use askama::Template;
use axum::{
Extension, Form,
extract::{Query, State},
http::{HeaderValue, header::HeaderName},
response::{AppendHeaders, IntoResponse, Response},
};
use forms::ACCOUNT_EDIT;
use serde::Deserialize;
use server::command::{CmdResult, FinanceEntity, account::ListAccountsForManage};
use sqlx::types::Uuid;
use crate::pages::forms::edit::{Edit, Edited, Loaded};
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
pub const SUBMIT_PATH: &str = "/api/account/manage/submit";
const EDIT: Edit = Edit {
form: &ACCOUNT_EDIT,
noun: "Account",
action: SUBMIT_PATH,
page: "/account/manage?account={id}",
remedy: "fix its tags with the set-account-tag and clear-account-tag natives, for example from Emacs",
#[derive(Template)]
#[template(path = "pages/account/manage.html")]
struct AccountManagePage {
view_url: String,
}
#[derive(Clone)]
struct AccountTreeEntry {
id: Uuid,
parent_id: Option<Uuid>,
name: String,
#[derive(Clone, Template)]
#[template(path = "components/account/tree_node.html")]
struct AccountTreeNodeView {
selected: bool,
children: Vec<AccountTreeNodeView>,
#[template(path = "components/account/manage_content.html")]
struct AccountManageContentTemplate {
tree: Vec<AccountTreeNodeView>,
form: Option<String>,
refusal: Option<String>,
flash_success: Option<String>,
flash_notice: Option<String>,
#[derive(Deserialize)]
pub struct AccountManageViewQuery {
account: Option<Uuid>,
fn view_url(account: Option<Uuid>) -> String {
match account {
Some(id) => format!("/api/account/manage/view?account={id}"),
None => "/api/account/manage/view".to_string(),
pub async fn account_manage_page(Query(query): Query<AccountManageViewQuery>) -> impl IntoResponse {
HtmlTemplate(AccountManagePage {
view_url: view_url(query.account),
})
pub async fn account_manage_view(
Query(query): Query<AccountManageViewQuery>,
State(_data): State<Arc<AppState>>,
Extension(jwt_auth): Extension<JWTAuthMiddleware>,
) -> Result<impl IntoResponse, WebError> {
let template = build_manage_content(jwt_auth.user.id, query.account, None).await?;
Ok(HtmlTemplate(template))
pub async fn account_manage_submit(
Form(pairs): Form<Vec<(String, String)>>,
) -> Result<Response, WebError> {
let user_id = jwt_auth.user.id;
match EDIT.submit(user_id, pairs).await? {
Edited::Invalid(response) => Ok(response),
Edited::Saved { id, notice } => {
let mut content =
build_manage_content(user_id, Some(id), Some("Account saved")).await?;
content.flash_notice = notice;
let swap = [
(
HeaderName::from_static("hx-retarget"),
"#account-manage-content",
),
(HeaderName::from_static("hx-reswap"), "outerHTML"),
]
.map(|(name, value)| (name, HeaderValue::from_static(value)));
Ok((AppendHeaders(swap), HtmlTemplate(content)).into_response())
async fn build_manage_content(
user_id: Uuid,
selected_account_id: Option<Uuid>,
flash_success: Option<&str>,
) -> Result<AccountManageContentTemplate, WebError> {
let flash_success = flash_success.map(str::to_string);
let accounts = list_account_entries(user_id).await?;
if accounts.is_empty() {
return Ok(AccountManageContentTemplate {
tree: Vec::new(),
form: None,
refusal: None,
flash_success,
flash_notice: None,
});
let account_ids: std::collections::HashSet<Uuid> = accounts.iter().map(|a| a.id).collect();
let selected_account_id = selected_account_id
.filter(|id| account_ids.contains(id))
.unwrap_or(accounts[0].id);
let tree = build_tree(&accounts, selected_account_id);
let loaded = EDIT.load(user_id, &selected_account_id.to_string()).await?;
let (form, refusal) = match loaded {
Loaded::Form { form, .. } => (Some(form), None),
Loaded::Refused(message) => (None, Some(message)),
Ok(AccountManageContentTemplate {
tree,
form,
refusal,
async fn list_account_entries(user_id: Uuid) -> Result<Vec<AccountTreeEntry>, WebError> {
let result = ListAccountsForManage::new().user_id(user_id).run().await?;
let Some(CmdResult::TaggedEntities { entities, .. }) = result else {
return Err(WebError::internal("Unexpected command response", result));
let mut accounts: Vec<AccountTreeEntry> = entities
.into_iter()
.filter_map(|(entity, tags)| match entity {
FinanceEntity::Account(account) => {
let name = extract_name(&tags).unwrap_or_else(|| account.id.to_string());
Some(AccountTreeEntry {
id: account.id,
parent_id: account.parent,
name,
_ => None,
.collect();
accounts.sort_by(|a, b| {
a.name
.to_lowercase()
.cmp(&b.name.to_lowercase())
.then(a.id.cmp(&b.id))
Ok(accounts)
fn build_tree(
accounts: &[AccountTreeEntry],
selected_account_id: Uuid,
) -> Vec<AccountTreeNodeView> {
let mut by_parent: HashMap<Option<Uuid>, Vec<&AccountTreeEntry>> = HashMap::new();
let all_ids: std::collections::HashSet<Uuid> = accounts.iter().map(|a| a.id).collect();
for account in accounts {
by_parent
.entry(account.parent_id)
.or_default()
.push(account);
for children in by_parent.values_mut() {
children.sort_by(|a, b| {
let mut roots: Vec<&AccountTreeEntry> = by_parent.remove(&None).unwrap_or_default();
let mut orphan_parents: Vec<Uuid> = by_parent
.keys()
.filter_map(|id| *id)
.filter(|id| !all_ids.contains(id))
orphan_parents.sort();
for orphan_parent in orphan_parents {
if let Some(children) = by_parent.remove(&Some(orphan_parent)) {
roots.extend(children);
roots
.map(|account| build_tree_node(account, selected_account_id, &by_parent))
.collect()
fn build_tree_node(
account: &AccountTreeEntry,
by_parent: &HashMap<Option<Uuid>, Vec<&AccountTreeEntry>>,
) -> AccountTreeNodeView {
let children = by_parent
.get(&Some(account.id))
.map(|children| {
children
.iter()
.map(|child| build_tree_node(child, selected_account_id, by_parent))
.unwrap_or_default();
AccountTreeNodeView {
name: account.name.clone(),
selected: account.id == selected_account_id,
children,
fn extract_name(tags: &HashMap<String, FinanceEntity>) -> Option<String> {
tags.get("name").and_then(|entity| match entity {
FinanceEntity::Tag(tag) => Some(tag.tag_value.clone()),
#[cfg(test)]
#[path = "manage_tests.rs"]
mod tests;