From dd850766fd2f2f29ec4b9ed11a0978bcf5161241 Mon Sep 17 00:00:00 2001 From: Tobias Reisinger Date: Wed, 24 Apr 2024 01:29:47 +0200 Subject: [PATCH] Add notification to controllers on schedule change --- Cargo.lock | Bin 68399 -> 68651 bytes emgauwa-core/Cargo.toml | 1 + emgauwa-core/src/handlers/v1/schedules.rs | 32 ++++++++++++++++-- emgauwa-lib/src/db/junction_relay_schedule.rs | 17 ++++++++++ 4 files changed, 48 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8b6ca2aabe0555a9690b8742e879d8d702fc995e..013c284bbebba8d895c056adf247ff5ddd15fb14 100644 GIT binary patch delta 153 zcmZ2Kjb-%=mJR!y1Tsrfi%RnIbBYxV^bC#k3@6`mwwV0LQD`%>^GU7AZ*s&ZKj;i{ zNJ=!aG&C?WN=ZseF}AcwG%+>) -> Result { let mut pool_conn = pool.acquire().await?; @@ -116,6 +123,7 @@ pub async fn add_list( #[put("/schedules/{schedule_id}")] pub async fn update( pool: web::Data>, + app_state: web::Data>, path: web::Path<(String,)>, data: web::Json, ) -> Result { @@ -144,6 +152,26 @@ pub async fn update( schedule.set_tags(&mut pool_conn, tags.as_slice()).await?; } + let controller_ids: Vec = DbJunctionRelaySchedule::get_relays(&mut pool_conn, &schedule) + .await? + .into_iter() + .map(|r| r.controller_id) + .unique() + .collect(); + + for controller_id in controller_ids { + let controller = DbController::get(&mut pool_conn, controller_id) + .await? + .ok_or(DatabaseError::NotFound)?; + app_state + .send(app_state::Action { + controller_uid: controller.uid, + action: ControllerWsAction::Schedules(vec![schedule.clone()]), + }) + .await??; + } + + let return_schedule = Schedule::from_db_model(&mut pool_conn, schedule)?; Ok(HttpResponse::Ok().json(return_schedule)) } diff --git a/emgauwa-lib/src/db/junction_relay_schedule.rs b/emgauwa-lib/src/db/junction_relay_schedule.rs index 128490b..f081a54 100644 --- a/emgauwa-lib/src/db/junction_relay_schedule.rs +++ b/emgauwa-lib/src/db/junction_relay_schedule.rs @@ -45,6 +45,23 @@ impl DbJunctionRelaySchedule { .map_err(DatabaseError::from) } + pub async fn get_relays( + conn: &mut PoolConnection, + schedule: &DbSchedule, + ) -> Result, DatabaseError> { + sqlx::query_as!( + DbRelay, + r#"SELECT relays.* FROM relays INNER JOIN junction_relay_schedule + ON junction_relay_schedule.relay_id = relays.id + WHERE junction_relay_schedule.schedule_id = ? + ORDER BY junction_relay_schedule.weekday"#, + schedule.id + ) + .fetch_all(conn.deref_mut()) + .await + .map_err(DatabaseError::from) + } + pub async fn get_schedule( conn: &mut PoolConnection, relay: &DbRelay,