web/pages/account/
list.rs1use std::sync::Arc;
2
3use askama::Template;
4use axum::extract::{Query, State};
5use axum::http::{HeaderMap, header};
6use axum::response::IntoResponse;
7use axum::{Extension, Json};
8use num_rational::Rational64;
9use serde::{Deserialize, Serialize};
10use server::command::{
11 CmdResult, FinanceEntity, account::GetAccount, account::GetAccountCommodities,
12 account::GetBalance, account::ListAccounts,
13};
14use sqlx::types::Uuid;
15
16use crate::pages::HtmlTemplate;
17use crate::response::WebError;
18use crate::{AppState, jwt_auth::JWTAuthMiddleware};
19
20#[derive(Template)]
21#[template(path = "pages/account/list.html")]
22struct AccountListPage;
23
24pub async fn account_list_page() -> impl IntoResponse {
25 let template = AccountListPage {};
26 HtmlTemplate(template)
27}
28
29#[derive(Serialize, Clone)]
30pub struct BalanceView {
31 balance: Rational64,
32 commodity: String,
33}
34
35#[derive(Serialize)]
36struct 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")]
45struct AccountTableTemplate {
46 accounts: Vec<AccountView>,
47}
48
49#[derive(Serialize)]
50struct AccountJson {
51 id: String,
52 name: String,
53 currency: Option<String>,
54 balance: Option<Vec<BalanceView>>,
55}
56
57async 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 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 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 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
124pub async fn account_table(
125 State(_data): State<Arc<AppState>>,
126 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
127 headers: HeaderMap,
128) -> Result<impl IntoResponse, WebError> {
129 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 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 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 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 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 Ok(HtmlTemplate(AccountTableTemplate { accounts }).into_response())
200}
201
202#[derive(Deserialize)]
203pub struct AccountInfoParam {
204 account: Uuid,
205}
206
207#[derive(Template)]
208#[template(path = "components/account/info.html")]
209struct AccountInfoTemplate {
210 account_id: Uuid,
211 name: String,
212 balance: Option<Vec<BalanceView>>,
213}
214
215pub async fn account_info(
216 Query(params): Query<AccountInfoParam>,
217 State(_data): State<Arc<AppState>>,
218 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
219) -> Result<impl IntoResponse, WebError> {
220 let account_result = GetAccount::new()
221 .user_id(jwt_auth.user.id)
222 .account_id(params.account)
223 .run()
224 .await?;
225
226 let name = if let Some(CmdResult::TaggedEntities { entities, .. }) = account_result
227 && 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 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}
255
256#[cfg(test)]
257#[path = "list_tests.rs"]
258mod tests;