1
use std::{collections::HashMap, sync::Arc};
2

            
3
use askama::Template;
4
use axum::{
5
    Extension, Form,
6
    extract::{Query, State},
7
    http::{HeaderValue, header::HeaderName},
8
    response::{AppendHeaders, IntoResponse, Response},
9
};
10
use forms::ACCOUNT_EDIT;
11
use serde::Deserialize;
12
use server::command::{CmdResult, FinanceEntity, account::ListAccountsForManage};
13
use sqlx::types::Uuid;
14

            
15
use crate::pages::forms::edit::{Edit, Edited, Loaded};
16
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
17

            
18
pub const SUBMIT_PATH: &str = "/api/account/manage/submit";
19

            
20
const 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")]
30
struct AccountManagePage {
31
    view_url: String,
32
}
33

            
34
#[derive(Clone)]
35
struct 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")]
43
struct 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")]
52
struct 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)]
61
pub struct AccountManageViewQuery {
62
    account: Option<Uuid>,
63
}
64

            
65
4
fn view_url(account: Option<Uuid>) -> String {
66
4
    match account {
67
2
        Some(id) => format!("/api/account/manage/view?account={id}"),
68
2
        None => "/api/account/manage/view".to_string(),
69
    }
70
4
}
71

            
72
pub async fn account_manage_page(Query(query): Query<AccountManageViewQuery>) -> impl IntoResponse {
73
    HtmlTemplate(AccountManagePage {
74
        view_url: view_url(query.account),
75
    })
76
}
77

            
78
8
pub async fn account_manage_view(
79
8
    Query(query): Query<AccountManageViewQuery>,
80
8
    State(_data): State<Arc<AppState>>,
81
8
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
82
8
) -> Result<impl IntoResponse, WebError> {
83
8
    let template = build_manage_content(jwt_auth.user.id, query.account, None).await?;
84
8
    Ok(HtmlTemplate(template))
85
8
}
86

            
87
5
pub async fn account_manage_submit(
88
5
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
89
5
    Form(pairs): Form<Vec<(String, String)>>,
90
5
) -> Result<Response, WebError> {
91
5
    let user_id = jwt_auth.user.id;
92
5
    match EDIT.submit(user_id, pairs).await? {
93
2
        Edited::Invalid(response) => Ok(response),
94
        Edited::Saved { id, notice } => {
95
            let mut content =
96
3
                build_manage_content(user_id, Some(id), Some("Account saved")).await?;
97
3
            content.flash_notice = notice;
98
3
            let swap = [
99
3
                (
100
3
                    HeaderName::from_static("hx-retarget"),
101
3
                    "#account-manage-content",
102
3
                ),
103
3
                (HeaderName::from_static("hx-reswap"), "outerHTML"),
104
3
            ]
105
6
            .map(|(name, value)| (name, HeaderValue::from_static(value)));
106
3
            Ok((AppendHeaders(swap), HtmlTemplate(content)).into_response())
107
        }
108
    }
109
5
}
110

            
111
11
async fn build_manage_content(
112
11
    user_id: Uuid,
113
11
    selected_account_id: Option<Uuid>,
114
11
    flash_success: Option<&str>,
115
11
) -> Result<AccountManageContentTemplate, WebError> {
116
11
    let flash_success = flash_success.map(str::to_string);
117
11
    let accounts = list_account_entries(user_id).await?;
118
11
    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
11
    }
127

            
128
19
    let account_ids: std::collections::HashSet<Uuid> = accounts.iter().map(|a| a.id).collect();
129
11
    let selected_account_id = selected_account_id
130
11
        .filter(|id| account_ids.contains(id))
131
11
        .unwrap_or(accounts[0].id);
132

            
133
11
    let tree = build_tree(&accounts, selected_account_id);
134
11
    let loaded = EDIT.load(user_id, &selected_account_id.to_string()).await?;
135
11
    let (form, refusal) = match loaded {
136
10
        Loaded::Form { form, .. } => (Some(form), None),
137
1
        Loaded::Refused(message) => (None, Some(message)),
138
    };
139

            
140
11
    Ok(AccountManageContentTemplate {
141
11
        tree,
142
11
        form,
143
11
        refusal,
144
11
        flash_success,
145
11
        flash_notice: None,
146
11
    })
147
11
}
148

            
149
11
async fn list_account_entries(user_id: Uuid) -> Result<Vec<AccountTreeEntry>, WebError> {
150
11
    let result = ListAccountsForManage::new().user_id(user_id).run().await?;
151

            
152
11
    let Some(CmdResult::TaggedEntities { entities, .. }) = result else {
153
        return Err(WebError::internal("Unexpected command response", result));
154
    };
155

            
156
11
    let mut accounts: Vec<AccountTreeEntry> = entities
157
11
        .into_iter()
158
19
        .filter_map(|(entity, tags)| match entity {
159
            FinanceEntity::Account(account) => {
160
19
                let name = extract_name(&tags).unwrap_or_else(|| account.id.to_string());
161
19
                Some(AccountTreeEntry {
162
19
                    id: account.id,
163
19
                    parent_id: account.parent,
164
19
                    name,
165
19
                })
166
            }
167
            _ => None,
168
19
        })
169
        .collect();
170

            
171
11
    accounts.sort_by(|a, b| {
172
8
        a.name
173
8
            .to_lowercase()
174
8
            .cmp(&b.name.to_lowercase())
175
8
            .then(a.id.cmp(&b.id))
176
8
    });
177

            
178
11
    Ok(accounts)
179
11
}
180

            
181
13
fn build_tree(
182
13
    accounts: &[AccountTreeEntry],
183
13
    selected_account_id: Uuid,
184
13
) -> Vec<AccountTreeNodeView> {
185
13
    let mut by_parent: HashMap<Option<Uuid>, Vec<&AccountTreeEntry>> = HashMap::new();
186
23
    let all_ids: std::collections::HashSet<Uuid> = accounts.iter().map(|a| a.id).collect();
187

            
188
13
    for account in accounts {
189
23
        by_parent
190
23
            .entry(account.parent_id)
191
23
            .or_default()
192
23
            .push(account);
193
    }
194

            
195
13
    for children in by_parent.values_mut() {
196
16
        children.sort_by(|a, b| {
197
7
            a.name
198
7
                .to_lowercase()
199
7
                .cmp(&b.name.to_lowercase())
200
7
                .then(a.id.cmp(&b.id))
201
7
        });
202
    }
203

            
204
13
    let mut roots: Vec<&AccountTreeEntry> = by_parent.remove(&None).unwrap_or_default();
205

            
206
13
    let mut orphan_parents: Vec<Uuid> = by_parent
207
13
        .keys()
208
3
        .filter_map(|id| *id)
209
3
        .filter(|id| !all_ids.contains(id))
210
        .collect();
211
13
    orphan_parents.sort();
212

            
213
13
    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
13
    roots
220
13
        .into_iter()
221
20
        .map(|account| build_tree_node(account, selected_account_id, &by_parent))
222
        .collect()
223
13
}
224

            
225
23
fn build_tree_node(
226
23
    account: &AccountTreeEntry,
227
23
    selected_account_id: Uuid,
228
23
    by_parent: &HashMap<Option<Uuid>, Vec<&AccountTreeEntry>>,
229
23
) -> AccountTreeNodeView {
230
23
    let children = by_parent
231
23
        .get(&Some(account.id))
232
3
        .map(|children| {
233
3
            children
234
3
                .iter()
235
3
                .map(|child| build_tree_node(child, selected_account_id, by_parent))
236
                .collect()
237
3
        })
238
        .unwrap_or_default();
239

            
240
23
    AccountTreeNodeView {
241
23
        id: account.id,
242
23
        name: account.name.clone(),
243
23
        selected: account.id == selected_account_id,
244
23
        children,
245
23
    }
246
23
}
247

            
248
19
fn extract_name(tags: &HashMap<String, FinanceEntity>) -> Option<String> {
249
19
    tags.get("name").and_then(|entity| match entity {
250
19
        FinanceEntity::Tag(tag) => Some(tag.tag_value.clone()),
251
        _ => None,
252
19
    })
253
19
}
254

            
255
#[cfg(test)]
256
#[path = "manage_tests.rs"]
257
mod tests;