fix fronted
This commit is contained in:
+138
-3
@@ -1,6 +1,7 @@
|
||||
use crate::db;
|
||||
use crate::types::{
|
||||
Config, LandingDto, LookupDto, MonthlyAggregate, PriceTrend, SpeciesDto, SummaryDto, TopSpecies,
|
||||
Config, LandingDto, LookupDto, MonthlyAggregate, MonthlySpeciesBreakdown, PriceTrend,
|
||||
SpeciesDto, SummaryDto, TopSpecies,
|
||||
};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
@@ -10,7 +11,6 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
use duckdb::params;
|
||||
use rust_embed::Embed;
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
@@ -129,6 +129,7 @@ pub fn build_router(state: AppState) -> Router {
|
||||
.route("/api/gear", get(get_gear))
|
||||
.route("/api/landings", get(get_landings))
|
||||
.route("/api/summary", get(get_summary))
|
||||
.route("/api/summary/monthly-breakdown", get(get_monthly_breakdown))
|
||||
.route("/api/export.parquet", get(export_parquet))
|
||||
.fallback(static_handler)
|
||||
.layer(cors)
|
||||
@@ -308,7 +309,6 @@ async fn get_summary(
|
||||
})?
|
||||
.collect::<std::result::Result<Vec<_>, duckdb::Error>>()?;
|
||||
|
||||
// Filter out "TOTAL" species from top species
|
||||
let top_sql = format!(
|
||||
"SELECT species_code, \
|
||||
COALESCE(MAX(species_label), species_code) AS species_label, \
|
||||
@@ -384,6 +384,77 @@ async fn get_summary(
|
||||
Ok(Json(result))
|
||||
}
|
||||
|
||||
async fn get_monthly_breakdown(
|
||||
State(state): State<AppState>,
|
||||
Query(params): Query<SummaryQuery>,
|
||||
) -> ApiResult<Json<Vec<MonthlySpeciesBreakdown>>> {
|
||||
let conn = state.conn.clone();
|
||||
|
||||
let result =
|
||||
tokio::task::spawn_blocking(move || -> db::Result<Vec<MonthlySpeciesBreakdown>> {
|
||||
let conn = conn.blocking_lock();
|
||||
|
||||
let mut conditions: Vec<String> = Vec::new();
|
||||
let mut args: Vec<Box<dyn duckdb::ToSql>> = Vec::new();
|
||||
|
||||
if let Some(ref month) = params.month {
|
||||
conditions.push("month = ?".to_string());
|
||||
args.push(Box::new(month.clone()));
|
||||
}
|
||||
if let Some(ref month_from) = params.month_from {
|
||||
conditions.push("month >= ?".to_string());
|
||||
args.push(Box::new(month_from.clone()));
|
||||
}
|
||||
if let Some(ref month_to) = params.month_to {
|
||||
conditions.push("month <= ?".to_string());
|
||||
args.push(Box::new(month_to.clone()));
|
||||
}
|
||||
if let Some(ref species) = params.species {
|
||||
conditions.push("species_code = ?".to_string());
|
||||
args.push(Box::new(species.clone()));
|
||||
}
|
||||
|
||||
let where_clause = if conditions.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" WHERE {}", conditions.join(" AND "))
|
||||
};
|
||||
|
||||
let sql = format!(
|
||||
"SELECT month, species_code, MAX(species_label) as species_label, \
|
||||
SUM(CASE WHEN measure_code = 'VALUE' THEN value END) as total_value, \
|
||||
SUM(CASE WHEN measure_code = 'MASS' THEN value END) as total_mass \
|
||||
FROM landings{where_clause} \
|
||||
GROUP BY month, species_code \
|
||||
ORDER BY month ASC, total_value DESC NULLS LAST"
|
||||
);
|
||||
|
||||
let arg_refs: Vec<&dyn duckdb::ToSql> = args.iter().map(|b| b.as_ref()).collect();
|
||||
|
||||
let mut stmt = conn.prepare(&sql)?;
|
||||
let rows = stmt
|
||||
.query_map(arg_refs.as_slice(), |row| {
|
||||
Ok(MonthlySpeciesBreakdown {
|
||||
month: row.get(0)?,
|
||||
species_code: row.get(1)?,
|
||||
species_label: row.get(2)?,
|
||||
total_value: row.get(3)?,
|
||||
total_mass: row.get(4)?,
|
||||
})
|
||||
})?
|
||||
.collect::<std::result::Result<Vec<_>, duckdb::Error>>()?;
|
||||
|
||||
Ok(rows)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ApiError {
|
||||
status: StatusCode::INTERNAL_SERVER_ERROR,
|
||||
message: format!("Task join error: {e}"),
|
||||
})??;
|
||||
|
||||
Ok(Json(result))
|
||||
}
|
||||
|
||||
async fn export_parquet(State(state): State<AppState>) -> ApiResult<Response> {
|
||||
let conn = state.conn.clone();
|
||||
|
||||
@@ -548,6 +619,7 @@ mod tests {
|
||||
use crate::types::Landing;
|
||||
use duckdb::Connection;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
fn test_state() -> AppState {
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
@@ -1053,4 +1125,67 @@ mod tests {
|
||||
|
||||
assert_eq!(count, 6);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_monthly_breakdown_returns_species_by_month() {
|
||||
let state = test_state();
|
||||
let base = spawn_test_server(state).await;
|
||||
|
||||
let resp = reqwest::get(format!("{base}/api/summary/monthly-breakdown"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let body: Vec<MonthlySpeciesBreakdown> = resp.json().await.unwrap();
|
||||
assert!(!body.is_empty(), "Should have breakdown rows");
|
||||
|
||||
let months: HashSet<_> = body.iter().map(|r| r.month.as_str()).collect();
|
||||
let species: HashSet<_> = body.iter().map(|r| r.species_code.as_str()).collect();
|
||||
|
||||
assert!(months.len() >= 1);
|
||||
assert!(species.len() >= 1);
|
||||
|
||||
for row in &body {
|
||||
assert!(!row.species_code.is_empty());
|
||||
assert!(!row.species_label.is_empty());
|
||||
assert!(row.total_value.is_some() || row.total_mass.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_monthly_breakdown_filtered_by_month_range() {
|
||||
let state = test_state();
|
||||
let base = spawn_test_server(state).await;
|
||||
|
||||
let resp = reqwest::get(format!(
|
||||
"{base}/api/summary/monthly-breakdown?month_from=2024M01&month_to=2024M01"
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let body: Vec<MonthlySpeciesBreakdown> = resp.json().await.unwrap();
|
||||
|
||||
for row in &body {
|
||||
assert_eq!(row.month, "2024M01");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_monthly_breakdown_filtered_by_species() {
|
||||
let state = test_state();
|
||||
let base = spawn_test_server(state).await;
|
||||
|
||||
let resp = reqwest::get(format!("{base}/api/summary/monthly-breakdown?species=COD"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let body: Vec<MonthlySpeciesBreakdown> = resp.json().await.unwrap();
|
||||
|
||||
for row in &body {
|
||||
assert_eq!(row.species_code, "COD");
|
||||
assert_eq!(row.species_label, "Toskur");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,6 +241,15 @@ pub struct SummaryDto {
|
||||
pub price_trend: Vec<PriceTrend>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MonthlySpeciesBreakdown {
|
||||
pub month: String,
|
||||
pub species_code: String,
|
||||
pub species_label: String,
|
||||
pub total_value: Option<f64>,
|
||||
pub total_mass: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum IngestError {
|
||||
#[error("HTTP request failed: {0}")]
|
||||
|
||||
Reference in New Issue
Block a user