Skip to main content

web/pages/commodity/
list.rs

1use std::sync::Arc;
2
3use askama::Template;
4use axum::{
5    Extension, Json,
6    extract::State,
7    http::{HeaderMap, header},
8    response::IntoResponse,
9};
10use serde::Serialize;
11use server::command::{CmdResult, FinanceEntity, commodity::ListCommodities};
12use sqlx::types::Uuid;
13
14use crate::pages::commodity::label::commodity_labels;
15use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
16
17#[derive(Template)]
18#[template(path = "pages/commodity/list.html")]
19struct CommodityListPage;
20
21pub async fn commodity_list_page() -> impl IntoResponse {
22    let template = CommodityListPage {};
23    HtmlTemplate(template)
24}
25
26struct CommodityView {
27    id: Uuid,
28    symbol: String,
29    name: String,
30}
31
32#[derive(Serialize)]
33struct CommodityJson {
34    id: String,
35    symbol: String,
36    name: String,
37}
38
39#[derive(Template)]
40#[template(path = "components/commodity/table.html")]
41struct CommodityTableTemplate {
42    commodities: Vec<CommodityView>,
43}
44
45pub async fn commodity_table(
46    State(_data): State<Arc<AppState>>,
47    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
48    headers: HeaderMap,
49) -> Result<impl IntoResponse, WebError> {
50    let result = ListCommodities::new()
51        .user_id(jwt_auth.user.id)
52        .run()
53        .await?;
54    let mut commodities = Vec::new();
55    if let Some(CmdResult::TaggedEntities { entities, .. }) = result {
56        for (entity, tags) in entities {
57            if let FinanceEntity::Commodity(commodity) = entity {
58                let (symbol, name) = commodity_labels(commodity.id, &tags);
59
60                commodities.push(CommodityView {
61                    id: commodity.id,
62                    symbol,
63                    name,
64                });
65            }
66        }
67    }
68
69    let wants_json = headers
70        .get(header::ACCEPT)
71        .and_then(|value| value.to_str().ok())
72        .is_some_and(|value| value.contains("application/json"));
73
74    if wants_json {
75        let commodities_json: Vec<CommodityJson> = commodities
76            .iter()
77            .map(|c| CommodityJson {
78                id: c.id.to_string(),
79                symbol: c.symbol.clone(),
80                name: c.name.clone(),
81            })
82            .collect();
83        return Ok(Json(commodities_json).into_response());
84    }
85
86    Ok(HtmlTemplate(CommodityTableTemplate { commodities }).into_response())
87}