1
use std::sync::Arc;
2

            
3
use askama::Template;
4
use axum::{
5
    Extension, Json,
6
    extract::State,
7
    http::{HeaderMap, header},
8
    response::IntoResponse,
9
};
10
use serde::Serialize;
11
use server::command::{CmdResult, FinanceEntity, commodity::ListCommodities};
12
use sqlx::types::Uuid;
13

            
14
use crate::pages::commodity::label::commodity_labels;
15
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
16

            
17
#[derive(Template)]
18
#[template(path = "pages/commodity/list.html")]
19
struct CommodityListPage;
20

            
21
pub async fn commodity_list_page() -> impl IntoResponse {
22
    let template = CommodityListPage {};
23
    HtmlTemplate(template)
24
}
25

            
26
struct CommodityView {
27
    id: Uuid,
28
    symbol: String,
29
    name: String,
30
}
31

            
32
#[derive(Serialize)]
33
struct CommodityJson {
34
    id: String,
35
    symbol: String,
36
    name: String,
37
}
38

            
39
#[derive(Template)]
40
#[template(path = "components/commodity/table.html")]
41
struct CommodityTableTemplate {
42
    commodities: Vec<CommodityView>,
43
}
44

            
45
4
pub async fn commodity_table(
46
4
    State(_data): State<Arc<AppState>>,
47
4
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
48
4
    headers: HeaderMap,
49
4
) -> Result<impl IntoResponse, WebError> {
50
4
    let result = ListCommodities::new()
51
4
        .user_id(jwt_auth.user.id)
52
4
        .run()
53
4
        .await?;
54
1
    let mut commodities = Vec::new();
55
1
    if let Some(CmdResult::TaggedEntities { entities, .. }) = result {
56
1
        for (entity, tags) in entities {
57
3
            if let FinanceEntity::Commodity(commodity) = entity {
58
3
                let (symbol, name) = commodity_labels(commodity.id, &tags);
59

            
60
3
                commodities.push(CommodityView {
61
3
                    id: commodity.id,
62
3
                    symbol,
63
3
                    name,
64
3
                });
65
            }
66
        }
67
    }
68

            
69
1
    let wants_json = headers
70
1
        .get(header::ACCEPT)
71
1
        .and_then(|value| value.to_str().ok())
72
1
        .is_some_and(|value| value.contains("application/json"));
73

            
74
1
    if wants_json {
75
1
        let commodities_json: Vec<CommodityJson> = commodities
76
1
            .iter()
77
            .map(|c| CommodityJson {
78
3
                id: c.id.to_string(),
79
3
                symbol: c.symbol.clone(),
80
3
                name: c.name.clone(),
81
3
            })
82
            .collect();
83
1
        return Ok(Json(commodities_json).into_response());
84
    }
85

            
86
    Ok(HtmlTemplate(CommodityTableTemplate { commodities }).into_response())
87
4
}