diff --git a/src/worker/sql.rs b/src/worker/sql.rs index afb5786..0fab301 100644 --- a/src/worker/sql.rs +++ b/src/worker/sql.rs @@ -1607,6 +1607,20 @@ pub const QUERY_HOURLY_PRICE_RECALCULATION: &str = r#" AND tpw.product_id = adj.product_id; "#; +/// Fügt für eine Region Preise in die Historie ein. +/// Berechnet den regionalen Produktpreis als sell_cost * worth_percent / 100. +pub const QUERY_INSERT_PRODUCT_PRICE_HISTORY: &str = r#" + INSERT INTO falukant_log.product_price_history (product_id, region_id, price, recorded_at) + SELECT + tpw.product_id, + tpw.region_id, + ROUND(ftp.sell_cost * tpw.worth_percent / 100.0, 2) AS price, + NOW() AS recorded_at + FROM falukant_data.town_product_worth tpw + JOIN falukant_type.product ftp ON ftp.id = tpw.product_id + WHERE tpw.region_id = $1; +"#; + pub const QUERY_SET_MARRIAGES_BY_PARTY: &str = r#" WITH updated_relations AS ( UPDATE falukant_data.relationship AS rel diff --git a/src/worker/value_recalculation.rs b/src/worker/value_recalculation.rs index 3af3990..ea932c3 100644 --- a/src/worker/value_recalculation.rs +++ b/src/worker/value_recalculation.rs @@ -14,6 +14,7 @@ use crate::worker::sql::{ QUERY_DELETE_REGION_SELL_PRICE, QUERY_GET_SELL_REGIONS, QUERY_HOURLY_PRICE_RECALCULATION, + QUERY_INSERT_PRODUCT_PRICE_HISTORY, QUERY_SET_MARRIAGES_BY_PARTY, QUERY_GET_STUDYINGS_TO_EXECUTE, QUERY_GET_OWN_CHARACTER_ID, @@ -139,11 +140,17 @@ impl ValueRecalculationWorker { conn.prepare("update_region_sell_price", QUERY_UPDATE_REGION_SELL_PRICE)?; conn.execute("update_region_sell_price", &[])?; + // Preis-Historie für betroffene Regionen erfassen + conn.prepare("insert_price_history", QUERY_INSERT_PRODUCT_PRICE_HISTORY)?; + conn.prepare("get_sell_regions", QUERY_GET_SELL_REGIONS)?; let regions = conn.execute("get_sell_regions", &[])?; for row in regions { if let Some(region_id) = row.get("region_id").and_then(|v| v.parse::().ok()) { + // Aktuelle Preise dieser Region in die Historie schreiben + let _ = conn.execute("insert_price_history", &[®ion_id]); + let message = format!(r#"{{"event":"price_update","region_id":{}}}"#, region_id); broker.publish(message); @@ -167,6 +174,9 @@ impl ValueRecalculationWorker { conn.prepare("hourly_price_recalculation", QUERY_HOURLY_PRICE_RECALCULATION)?; let _updated_rows = conn.execute("hourly_price_recalculation", &[])?; + // Prepared Statement für Preis-Historie + conn.prepare("insert_price_history", QUERY_INSERT_PRODUCT_PRICE_HISTORY)?; + // Sammle alle betroffenen Regionen für Event-Benachrichtigungen let mut affected_regions = HashSet::new(); @@ -191,6 +201,9 @@ impl ValueRecalculationWorker { // Benachrichtige alle betroffenen Regionen über Preisänderungen for region_id in affected_regions { + // aktuellen Preisstand in die Historie schreiben + let _ = conn.execute("insert_price_history", &[®ion_id]); + let message = format!(r#"{{"event":"price_update","region_id":{}}}"#, region_id); broker.publish(message);