1
use std::sync::Arc;
2

            
3
use askama::Template;
4
use axum::extract::{Query, State};
5
use axum::http::{HeaderMap, header};
6
use axum::response::IntoResponse;
7
use axum::{Extension, Json};
8
use num_rational::Rational64;
9
use serde::{Deserialize, Serialize};
10
use server::command::{
11
    CmdResult, FinanceEntity, account::GetAccount, account::GetAccountCommodities,
12
    account::GetBalance, account::ListAccounts,
13
};
14
use sqlx::types::Uuid;
15

            
16
use crate::pages::HtmlTemplate;
17
use crate::response::WebError;
18
use crate::{AppState, jwt_auth::JWTAuthMiddleware};
19

            
20
#[derive(Template)]
21
#[template(path = "pages/account/list.html")]
22
struct AccountListPage;
23

            
24
pub async fn account_list_page() -> impl IntoResponse {
25
    let template = AccountListPage {};
26
    HtmlTemplate(template)
27
}
28

            
29
#[derive(Serialize, Clone)]
30
pub struct BalanceView {
31
    balance: Rational64,
32
    commodity: String,
33
}
34

            
35
#[derive(Serialize)]
36
struct AccountView {
37
    id: Uuid,
38
    name: String,
39
    currency: Option<Uuid>,
40
    balance: Option<Vec<BalanceView>>,
41
}
42

            
43
#[derive(Template)]
44
#[template(path = "components/account/table.html")]
45
struct AccountTableTemplate {
46
    accounts: Vec<AccountView>,
47
}
48

            
49
#[derive(Serialize)]
50
struct AccountJson {
51
    id: String,
52
    name: String,
53
    currency: Option<String>,
54
    balance: Option<Vec<BalanceView>>,
55
}
56

            
57
async fn get_balance_display(
58
    account_id: Uuid,
59
    user_id: Uuid,
60
    commodities: &[server::command::CommodityInfo],
61
) -> Result<Option<Vec<BalanceView>>, WebError> {
62
    let balance_result = GetBalance::new()
63
        .user_id(user_id)
64
        .account_id(account_id)
65
        .run()
66
        .await?;
67

            
68
    match balance_result {
69
        Some(CmdResult::MultiCurrencyBalance(balances)) => {
70
            if balances.is_empty() {
71
                Ok(None)
72
            } else if balances.len() == 1 {
73
                // Single currency
74
                let (commodity, balance) = &balances[0];
75
                let commodity_info = commodities
76
                    .iter()
77
                    .find(|c| c.commodity_id == commodity.id)
78
                    .map_or_else(|| "?".to_string(), |c| c.symbol.clone());
79
                Ok(Some(vec![BalanceView {
80
                    balance: *balance,
81
                    commodity: commodity_info,
82
                }]))
83
            } else {
84
                // Multiple currencies - show all balances comma-separated
85
                // TODO: rework for arrays?
86
                let balance_strings: Vec<BalanceView> = balances
87
                    .iter()
88
                    .map(|(commodity, balance)| {
89
                        let symbol = commodities
90
                            .iter()
91
                            .find(|c| c.commodity_id == commodity.id)
92
                            .map_or_else(|| "?".to_string(), |c| c.symbol.clone());
93
                        BalanceView {
94
                            balance: *balance,
95
                            commodity: symbol,
96
                        }
97
                    })
98
                    .collect();
99
                Ok(Some(balance_strings))
100
            }
101
        }
102
        Some(CmdResult::Rational(balance)) => {
103
            // Single currency result (when commodity_id was specified)
104
            if balance == Rational64::new(0, 1) {
105
                Ok(None)
106
            } else if commodities.is_empty() {
107
                Ok(Some(vec![BalanceView {
108
                    balance,
109
                    commodity: "?".to_string(),
110
                }]))
111
            } else {
112
                let symbol = &commodities[0].symbol;
113
                Ok(Some(vec![BalanceView {
114
                    balance,
115
                    commodity: symbol.clone(),
116
                }]))
117
            }
118
        }
119
        None => Ok(None),
120
        other => Err(WebError::internal("Unexpected GetBalance result", other)),
121
    }
122
}
123

            
124
10
pub async fn account_table(
125
10
    State(_data): State<Arc<AppState>>,
126
10
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
127
10
    headers: HeaderMap,
128
10
) -> Result<impl IntoResponse, WebError> {
129
10
    let result = ListAccounts::new().user_id(jwt_auth.user.id).run().await?;
130

            
131
    let mut accounts = Vec::new();
132
    if let Some(CmdResult::TaggedEntities { entities, .. }) = result {
133
        for (entity, tags) in entities {
134
            if let FinanceEntity::Account(account) = entity {
135
                // Find name tag. A nameless account is listed under its id
136
                // rather than failing the whole page, so it can be fixed.
137
                let name = match tags.get("name") {
138
                    Some(FinanceEntity::Tag(n)) => n.tag_value.clone(),
139
                    Some(other) => {
140
                        return Err(WebError::internal("Account name is not a tag", other));
141
                    }
142
                    None => {
143
                        tracing::warn!("Account {} has no name tag", account.id);
144
                        account.id.to_string()
145
                    }
146
                };
147

            
148
                // Get all commodities for this account
149
                let commodities_result = GetAccountCommodities::new()
150
                    .user_id(jwt_auth.user.id)
151
                    .account_id(account.id)
152
                    .run()
153
                    .await?;
154

            
155
                let commodities =
156
                    if let Some(CmdResult::CommodityInfoList(commodities)) = commodities_result {
157
                        commodities
158
                    } else {
159
                        Vec::new()
160
                    };
161

            
162
                let balance_display =
163
                    get_balance_display(account.id, jwt_auth.user.id, &commodities).await?;
164

            
165
                let currency = commodities.first().map(|c| c.commodity_id);
166

            
167
                accounts.push(AccountView {
168
                    id: account.id,
169
                    name,
170
                    currency,
171
                    balance: balance_display,
172
                });
173
            }
174
        }
175
    }
176

            
177
    // Check if the client is requesting JSON by examining the Accept header
178
    let wants_json = headers
179
        .get(header::ACCEPT)
180
        .and_then(|value| value.to_str().ok())
181
        .is_some_and(|value| value.contains("application/json"));
182

            
183
    if wants_json {
184
        // Return JSON response
185
        let accounts_json: Vec<AccountJson> = accounts
186
            .iter()
187
            .map(|a| AccountJson {
188
                id: a.id.to_string(),
189
                name: a.name.clone(),
190
                currency: a.currency.map(|c| c.to_string()),
191
                balance: a.balance.clone(),
192
            })
193
            .collect();
194

            
195
        return Ok(Json(accounts_json).into_response());
196
    }
197

            
198
    // Default to HTML response
199
    Ok(HtmlTemplate(AccountTableTemplate { accounts }).into_response())
200
10
}
201

            
202
#[derive(Deserialize)]
203
pub struct AccountInfoParam {
204
    account: Uuid,
205
}
206

            
207
#[derive(Template)]
208
#[template(path = "components/account/info.html")]
209
struct AccountInfoTemplate {
210
    account_id: Uuid,
211
    name: String,
212
    balance: Option<Vec<BalanceView>>,
213
}
214

            
215
2
pub async fn account_info(
216
2
    Query(params): Query<AccountInfoParam>,
217
2
    State(_data): State<Arc<AppState>>,
218
2
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
219
2
) -> Result<impl IntoResponse, WebError> {
220
2
    let account_result = GetAccount::new()
221
2
        .user_id(jwt_auth.user.id)
222
2
        .account_id(params.account)
223
2
        .run()
224
2
        .await?;
225

            
226
1
    let name = if let Some(CmdResult::TaggedEntities { entities, .. }) = account_result
227
1
        && let Some((FinanceEntity::Account(_account), tags)) = entities.first()
228
        && let Some(FinanceEntity::Tag(name_tag)) = tags.get("name")
229
    {
230
        name_tag.tag_value.clone()
231
    } else {
232
1
        return Err(WebError::not_found("Account not found"));
233
    };
234

            
235
    let commodities_result = GetAccountCommodities::new()
236
        .user_id(jwt_auth.user.id)
237
        .account_id(params.account)
238
        .run()
239
        .await?;
240

            
241
    let commodities = if let Some(CmdResult::CommodityInfoList(commodities)) = commodities_result {
242
        commodities
243
    } else {
244
        Vec::new()
245
    };
246

            
247
    let balance = get_balance_display(params.account, jwt_auth.user.id, &commodities).await?;
248

            
249
    Ok(HtmlTemplate(AccountInfoTemplate {
250
        account_id: params.account,
251
        name,
252
        balance,
253
    }))
254
2
}
255

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