From 29fabb04b06f10518652b349afe87c221ddb58ff Mon Sep 17 00:00:00 2001 From: philipp Date: Tue, 21 May 2024 18:57:24 +0200 Subject: [PATCH] allow for sending notifications to single users --- src/tera/admin/notification.rs | 56 +++++++++++++++++++++++--- templates/admin/notification.html.tera | 16 ++++++-- 2 files changed, 63 insertions(+), 9 deletions(-) diff --git a/src/tera/admin/notification.rs b/src/tera/admin/notification.rs index bba3488..a777a32 100644 --- a/src/tera/admin/notification.rs +++ b/src/tera/admin/notification.rs @@ -4,6 +4,7 @@ use crate::model::{ role::Role, user::{AdminUser, User, UserWithDetails}, }; +use itertools::Itertools; use rocket::{ form::Form, get, post, @@ -28,22 +29,39 @@ async fn index( "loggedin_user", &UserWithDetails::from_user(user.user, db).await, ); + + let users: Vec = User::all(db) + .await + .into_iter() + .filter(|u| u.last_access.is_some()) // Not useful to send notifications to people who are + // not logging in + .sorted_by_key(|u| u.name.clone()) + .collect(); + context.insert("roles", &Role::all(db).await); + context.insert("users", &users); Template::render("admin/notification", context.into_json()) } #[derive(FromForm, Debug)] -pub struct NotificationToSend { +pub struct NotificationToSendGroup { pub(crate) role_id: i32, pub(crate) category: String, pub(crate) message: String, } -#[post("/notification", data = "")] -async fn send( +#[derive(FromForm, Debug)] +pub struct NotificationToSendUser { + pub(crate) user_id: i32, + pub(crate) category: String, + pub(crate) message: String, +} + +#[post("/notification/group", data = "")] +async fn send_group( db: &State, - data: Form, + data: Form, admin: AdminUser, ) -> Flash { let d = data.into_inner(); @@ -67,6 +85,32 @@ async fn send( ) } -pub fn routes() -> Vec { - routes![index, send] +#[post("/notification/user", data = "")] +async fn send_user( + db: &State, + data: Form, + admin: AdminUser, +) -> Flash { + let d = data.into_inner(); + Log::create( + db, + format!("{admin:?} trying to send this notification: {d:?}"), + ) + .await; + + let Some(user) = User::find_by_id(db, d.user_id).await else { + return Flash::error(Redirect::to("/admin/notification"), "User gibt's ned"); + }; + + Notification::create(db, &user, &d.message, &d.category, None).await; + + Log::create(db, "Notification successfully sent".into()).await; + Flash::success( + Redirect::to("/admin/notification"), + "Nachricht ausgeschickt", + ) +} + +pub fn routes() -> Vec { + routes![index, send_user, send_group] } diff --git a/templates/admin/notification.html.tera b/templates/admin/notification.html.tera index 396ee0b..ecc0531 100644 --- a/templates/admin/notification.html.tera +++ b/templates/admin/notification.html.tera @@ -3,18 +3,28 @@ {% extends "base" %} {% block content %}
-

Nachricht

+

Nachricht senden

+
{% endblock content %} -- 2.45.2