Skip to main content

web/pages/account/
manage.rs

1use std::{collections::HashMap, sync::Arc};
2
3use askama::Template;
4use axum::{
5    Extension, Form,
6    extract::{Query, State},
7    http::{HeaderValue, header::HeaderName},
8    response::{AppendHeaders, IntoResponse, Response},
9};
10use forms::ACCOUNT_EDIT;
11use serde::Deserialize;
12use server::command::{CmdResult, FinanceEntity, account::ListAccountsForManage};
13use sqlx::types::Uuid;
14
15use crate::pages::forms::edit::{Edit, Edited, Loaded};
16use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
17
18pub const SUBMIT_PATH: &str = "/api/account/manage/submit";
19
20const EDIT: Edit = Edit {
21    form: &ACCOUNT_EDIT,
22    noun: "Account",
23    action: SUBMIT_PATH,
24    page: "/account/manage?account={id}",
25    remedy: "fix its tags with the set-account-tag and clear-account-tag natives, for example from Emacs",
26};
27
28#[derive(Template)]
29#[template(path = "pages/account/manage.html")]
30struct AccountManagePage {
31    view_url: String,
32}
33
34#[derive(Clone)]
35struct AccountTreeEntry {
36    id: Uuid,
37    parent_id: Option<Uuid>,
38    name: String,
39}
40
41#[derive(Clone, Template)]
42#[template(path = "components/account/tree_node.html")]
43struct AccountTreeNodeView {
44    id: Uuid,
45    name: String,
46    selected: bool,
47    children: Vec<AccountTreeNodeView>,
48}
49
50#[derive(Template)]
51#[template(path = "components/account/manage_content.html")]
52struct AccountManageContentTemplate {
53    tree: Vec<AccountTreeNodeView>,
54    form: Option<String>,
55    refusal: Option<String>,
56    flash_success: Option<String>,
57    flash_notice: Option<String>,
58}
59
60#[derive(Deserialize)]
61pub struct AccountManageViewQuery {
62    account: Option<Uuid>,
63}
64
65fn view_url(account: Option<Uuid>) -> String {
66    match account {
67        Some(id) => format!("/api/account/manage/view?account={id}"),
68        None => "/api/account/manage/view".to_string(),
69    }
70}
71
72pub async fn account_manage_page(Query(query): Query<AccountManageViewQuery>) -> impl IntoResponse {
73    HtmlTemplate(AccountManagePage {
74        view_url: view_url(query.account),
75    })
76}
77
78pub async fn account_manage_view(
79    Query(query): Query<AccountManageViewQuery>,
80    State(_data): State<Arc<AppState>>,
81    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
82) -> Result<impl IntoResponse, WebError> {
83    let template = build_manage_content(jwt_auth.user.id, query.account, None).await?;
84    Ok(HtmlTemplate(template))
85}
86
87pub async fn account_manage_submit(
88    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
89    Form(pairs): Form<Vec<(String, String)>>,
90) -> Result<Response, WebError> {
91    let user_id = jwt_auth.user.id;
92    match EDIT.submit(user_id, pairs).await? {
93        Edited::Invalid(response) => Ok(response),
94        Edited::Saved { id, notice } => {
95            let mut content =
96                build_manage_content(user_id, Some(id), Some("Account saved")).await?;
97            content.flash_notice = notice;
98            let swap = [
99                (
100                    HeaderName::from_static("hx-retarget"),
101                    "#account-manage-content",
102                ),
103                (HeaderName::from_static("hx-reswap"), "outerHTML"),
104            ]
105            .map(|(name, value)| (name, HeaderValue::from_static(value)));
106            Ok((AppendHeaders(swap), HtmlTemplate(content)).into_response())
107        }
108    }
109}
110
111async fn build_manage_content(
112    user_id: Uuid,
113    selected_account_id: Option<Uuid>,
114    flash_success: Option<&str>,
115) -> Result<AccountManageContentTemplate, WebError> {
116    let flash_success = flash_success.map(str::to_string);
117    let accounts = list_account_entries(user_id).await?;
118    if accounts.is_empty() {
119        return Ok(AccountManageContentTemplate {
120            tree: Vec::new(),
121            form: None,
122            refusal: None,
123            flash_success,
124            flash_notice: None,
125        });
126    }
127
128    let account_ids: std::collections::HashSet<Uuid> = accounts.iter().map(|a| a.id).collect();
129    let selected_account_id = selected_account_id
130        .filter(|id| account_ids.contains(id))
131        .unwrap_or(accounts[0].id);
132
133    let tree = build_tree(&accounts, selected_account_id);
134    let loaded = EDIT.load(user_id, &selected_account_id.to_string()).await?;
135    let (form, refusal) = match loaded {
136        Loaded::Form { form, .. } => (Some(form), None),
137        Loaded::Refused(message) => (None, Some(message)),
138    };
139
140    Ok(AccountManageContentTemplate {
141        tree,
142        form,
143        refusal,
144        flash_success,
145        flash_notice: None,
146    })
147}
148
149async fn list_account_entries(user_id: Uuid) -> Result<Vec<AccountTreeEntry>, WebError> {
150    let result = ListAccountsForManage::new().user_id(user_id).run().await?;
151
152    let Some(CmdResult::TaggedEntities { entities, .. }) = result else {
153        return Err(WebError::internal("Unexpected command response", result));
154    };
155
156    let mut accounts: Vec<AccountTreeEntry> = entities
157        .into_iter()
158        .filter_map(|(entity, tags)| match entity {
159            FinanceEntity::Account(account) => {
160                let name = extract_name(&tags).unwrap_or_else(|| account.id.to_string());
161                Some(AccountTreeEntry {
162                    id: account.id,
163                    parent_id: account.parent,
164                    name,
165                })
166            }
167            _ => None,
168        })
169        .collect();
170
171    accounts.sort_by(|a, b| {
172        a.name
173            .to_lowercase()
174            .cmp(&b.name.to_lowercase())
175            .then(a.id.cmp(&b.id))
176    });
177
178    Ok(accounts)
179}
180
181fn build_tree(
182    accounts: &[AccountTreeEntry],
183    selected_account_id: Uuid,
184) -> Vec<AccountTreeNodeView> {
185    let mut by_parent: HashMap<Option<Uuid>, Vec<&AccountTreeEntry>> = HashMap::new();
186    let all_ids: std::collections::HashSet<Uuid> = accounts.iter().map(|a| a.id).collect();
187
188    for account in accounts {
189        by_parent
190            .entry(account.parent_id)
191            .or_default()
192            .push(account);
193    }
194
195    for children in by_parent.values_mut() {
196        children.sort_by(|a, b| {
197            a.name
198                .to_lowercase()
199                .cmp(&b.name.to_lowercase())
200                .then(a.id.cmp(&b.id))
201        });
202    }
203
204    let mut roots: Vec<&AccountTreeEntry> = by_parent.remove(&None).unwrap_or_default();
205
206    let mut orphan_parents: Vec<Uuid> = by_parent
207        .keys()
208        .filter_map(|id| *id)
209        .filter(|id| !all_ids.contains(id))
210        .collect();
211    orphan_parents.sort();
212
213    for orphan_parent in orphan_parents {
214        if let Some(children) = by_parent.remove(&Some(orphan_parent)) {
215            roots.extend(children);
216        }
217    }
218
219    roots
220        .into_iter()
221        .map(|account| build_tree_node(account, selected_account_id, &by_parent))
222        .collect()
223}
224
225fn build_tree_node(
226    account: &AccountTreeEntry,
227    selected_account_id: Uuid,
228    by_parent: &HashMap<Option<Uuid>, Vec<&AccountTreeEntry>>,
229) -> AccountTreeNodeView {
230    let children = by_parent
231        .get(&Some(account.id))
232        .map(|children| {
233            children
234                .iter()
235                .map(|child| build_tree_node(child, selected_account_id, by_parent))
236                .collect()
237        })
238        .unwrap_or_default();
239
240    AccountTreeNodeView {
241        id: account.id,
242        name: account.name.clone(),
243        selected: account.id == selected_account_id,
244        children,
245    }
246}
247
248fn extract_name(tags: &HashMap<String, FinanceEntity>) -> Option<String> {
249    tags.get("name").and_then(|entity| match entity {
250        FinanceEntity::Tag(tag) => Some(tag.tag_value.clone()),
251        _ => None,
252    })
253}
254
255#[cfg(test)]
256#[path = "manage_tests.rs"]
257mod tests;