Lines
80 %
Functions
17.86 %
Branches
100 %
use std::sync::Arc;
use askama::Template;
use axum::{
Extension, Json,
extract::State,
http::{HeaderMap, header},
response::IntoResponse,
};
use serde::Serialize;
use server::command::{CmdResult, FinanceEntity, commodity::ListCommodities};
use sqlx::types::Uuid;
use crate::pages::commodity::label::commodity_labels;
use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate, response::WebError};
#[derive(Template)]
#[template(path = "pages/commodity/list.html")]
struct CommodityListPage;
pub async fn commodity_list_page() -> impl IntoResponse {
let template = CommodityListPage {};
HtmlTemplate(template)
}
struct CommodityView {
id: Uuid,
symbol: String,
name: String,
#[derive(Serialize)]
struct CommodityJson {
id: String,
#[template(path = "components/commodity/table.html")]
struct CommodityTableTemplate {
commodities: Vec<CommodityView>,
pub async fn commodity_table(
State(_data): State<Arc<AppState>>,
Extension(jwt_auth): Extension<JWTAuthMiddleware>,
headers: HeaderMap,
) -> Result<impl IntoResponse, WebError> {
let result = ListCommodities::new()
.user_id(jwt_auth.user.id)
.run()
.await?;
let mut commodities = Vec::new();
if let Some(CmdResult::TaggedEntities { entities, .. }) = result {
for (entity, tags) in entities {
if let FinanceEntity::Commodity(commodity) = entity {
let (symbol, name) = commodity_labels(commodity.id, &tags);
commodities.push(CommodityView {
id: commodity.id,
symbol,
name,
});
let wants_json = headers
.get(header::ACCEPT)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value.contains("application/json"));
if wants_json {
let commodities_json: Vec<CommodityJson> = commodities
.iter()
.map(|c| CommodityJson {
id: c.id.to_string(),
symbol: c.symbol.clone(),
name: c.name.clone(),
})
.collect();
return Ok(Json(commodities_json).into_response());
Ok(HtmlTemplate(CommodityTableTemplate { commodities }).into_response())