Add property listing
This commit is contained in:
parent
51967fa880
commit
85f5770e09
3 changed files with 254 additions and 7 deletions
|
|
@ -1,4 +1,5 @@
|
|||
use std::fmt::Write;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::Query;
|
||||
|
|
@ -459,3 +460,165 @@ pub async fn get_poi_categories(state: Arc<AppState>) -> Json<POICategoriesRespo
|
|||
|
||||
Json(result)
|
||||
}
|
||||
|
||||
// ── /api/hexagon-properties ──
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct HexagonPropertiesParams {
|
||||
pub h3: String,
|
||||
pub resolution: u8,
|
||||
pub filters: Option<String>,
|
||||
pub limit: Option<usize>,
|
||||
pub offset: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Property {
|
||||
// String fields
|
||||
pub address: Option<String>,
|
||||
pub postcode: Option<String>,
|
||||
pub property_type: Option<String>,
|
||||
pub built_form: Option<String>,
|
||||
pub current_energy_rating: Option<String>,
|
||||
pub potential_energy_rating: Option<String>,
|
||||
|
||||
// Numeric fields
|
||||
pub lat: f64,
|
||||
pub lon: f64,
|
||||
|
||||
// All other numeric features stored as dynamic map
|
||||
#[serde(flatten)]
|
||||
pub features: FxHashMap<String, f64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct HexagonPropertiesResponse {
|
||||
pub properties: Vec<Property>,
|
||||
pub total: usize,
|
||||
pub limit: usize,
|
||||
pub offset: usize,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Helper function to check if a row passes all filters
|
||||
fn row_passes_filters(row: usize, filters: &[ParsedFilter], feature_data: &[f64], num_features: usize) -> bool {
|
||||
filters.iter().all(|f| {
|
||||
let v = feature_data[row * num_features + f.feat_idx];
|
||||
v.is_finite() && v >= f.min && v <= f.max
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn get_hexagon_properties(
|
||||
state: Arc<AppState>,
|
||||
Query(params): Query<HexagonPropertiesParams>,
|
||||
) -> Result<Json<HexagonPropertiesResponse>, (StatusCode, String)> {
|
||||
// 1. Parse H3 cell ID
|
||||
let cell = h3o::CellIndex::from_str(¶ms.h3)
|
||||
.map_err(|e| (StatusCode::BAD_REQUEST, format!("Invalid H3 cell: {}", e)))?;
|
||||
let cell_u64: u64 = cell.into();
|
||||
|
||||
// 2. Validate resolution
|
||||
let resolution = params.resolution as usize;
|
||||
if resolution >= state.h3_cells.len() || state.h3_cells[resolution].is_empty() {
|
||||
return Err((StatusCode::BAD_REQUEST, "Invalid or non-precomputed resolution".to_string()));
|
||||
}
|
||||
|
||||
// 3. Parse filters (reuse existing filter parsing logic from get_hexagons)
|
||||
let parsed_filters: Vec<ParsedFilter> = params
|
||||
.filters
|
||||
.as_deref()
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| {
|
||||
s.split(',')
|
||||
.filter_map(|entry| {
|
||||
let parts: Vec<&str> = entry.splitn(3, ':').collect();
|
||||
if parts.len() != 3 {
|
||||
return None;
|
||||
}
|
||||
let name = parts[0].trim();
|
||||
let min = parts[1].trim().parse::<f64>().ok()?;
|
||||
let max = parts[2].trim().parse::<f64>().ok()?;
|
||||
let feat_idx = state.data.feature_names.iter().position(|n| n == name)?;
|
||||
Some(ParsedFilter { feat_idx, min, max })
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
// Move CPU-heavy work off the async executor
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let h3_data = &state.h3_cells[resolution];
|
||||
let num_features = state.data.num_features;
|
||||
let feature_data = &state.data.feature_data;
|
||||
|
||||
// 4. Find all rows with matching H3 cell
|
||||
let matching_rows: Vec<usize> = h3_data
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, &h3_cell)| {
|
||||
if h3_cell == cell_u64 {
|
||||
// Apply feature filters
|
||||
if row_passes_filters(idx, &parsed_filters, feature_data, num_features) {
|
||||
Some(idx)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let total = matching_rows.len();
|
||||
let limit = params.limit.unwrap_or(100).min(500);
|
||||
let offset = params.offset.unwrap_or(0);
|
||||
let truncated = total > offset + limit;
|
||||
|
||||
// 5. Extract properties for paginated subset
|
||||
let properties: Vec<Property> = matching_rows
|
||||
.iter()
|
||||
.skip(offset)
|
||||
.take(limit)
|
||||
.map(|&row| {
|
||||
// Build dynamic features map
|
||||
let mut features = FxHashMap::default();
|
||||
let base = row * num_features;
|
||||
for (feat_idx, feat_name) in state.data.feature_names.iter().enumerate() {
|
||||
let v = feature_data[base + feat_idx];
|
||||
if v.is_finite() {
|
||||
features.insert(feat_name.clone(), v);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to get non-empty string
|
||||
let get_string = |s: &str| -> Option<String> {
|
||||
if s.is_empty() { None } else { Some(s.to_string()) }
|
||||
};
|
||||
|
||||
Property {
|
||||
address: get_string(&state.data.address[row]),
|
||||
postcode: get_string(&state.data.postcode[row]),
|
||||
property_type: get_string(&state.data.property_type[row]),
|
||||
built_form: get_string(&state.data.built_form[row]),
|
||||
current_energy_rating: get_string(&state.data.current_energy_rating[row]),
|
||||
potential_energy_rating: get_string(&state.data.potential_energy_rating[row]),
|
||||
lat: state.data.lat[row],
|
||||
lon: state.data.lon[row],
|
||||
features,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
HexagonPropertiesResponse {
|
||||
properties,
|
||||
total,
|
||||
limit,
|
||||
offset,
|
||||
truncated,
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
Ok(Json(result))
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue