Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: endpoint to get notification by id (#923)

Peter Chinman6f56eae91273
diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-3b9abfc8d69176441d4c08d812c474d988adbd0ea2ba750b7536c069d6296884.json b/rust/cloud-storage/notification_db_client/.sqlx/query-3b9abfc8d69176441d4c08d812c474d988adbd0ea2ba750b7536c069d6296884.json
new file mode 100644
index 0000000000..196eb7a8e4
--- /dev/null
+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-3b9abfc8d69176441d4c08d812c474d988adbd0ea2ba750b7536c069d6296884.json
@@ -0,0 +1,95 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as notification_metadata,\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.notification_id = $2\n AND un.deleted_at IS NULL\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owner_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "notification_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "event_item_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "event_item_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "done",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "viewed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "notification_metadata",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 11,
+ "name": "notification_event_type",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 12,
+ "name": "sender_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ null,
+ null,
+ null,
+ null,
+ true,
+ false,
+ true
+ ]
+ },
+ "hash": "3b9abfc8d69176441d4c08d812c474d988adbd0ea2ba750b7536c069d6296884"
+}
diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_by_id.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/get_by_id.rs
new file mode 100644
index 0000000000..0b38a34576
--- /dev/null
+++ b/rust/cloud-storage/notification_db_client/src/user_notification/get/get_by_id.rs
@@ -0,0 +1,140 @@
+use std::str::FromStr;
+
+use macro_user_id::{cowlike::CowLike, error::ParseErr, user_id::MacroUserIdStr};
+use model_entity::EntityType;
+use model_notifications::RawUserNotification;
+use sqlx::types::Uuid;
+
+/// Gets a single user notification by its notification id.
+#[tracing::instrument(skip(db))]
+pub async fn get_user_notification_by_id(
+ db: &sqlx::PgPool,
+ user_id: &str,
+ notification_id: Uuid,
+) -> anyhow::Result<Option<RawUserNotification>> {
+ let row = sqlx::query!(
+ r#"
+ SELECT
+ un.user_id as owner_id,
+ un.notification_id,
+ n.event_item_id,
+ n.event_item_type,
+ un.sent,
+ un.done,
+ un.created_at::timestamptz,
+ un.seen_at::timestamptz as viewed_at,
+ un.created_at::timestamptz as updated_at,
+ un.deleted_at::timestamptz,
+ n.metadata as notification_metadata,
+ n.notification_event_type as notification_event_type,
+ n.sender_id as sender_id
+ FROM user_notification un
+ JOIN notification n ON n.id = un.notification_id
+ WHERE un.user_id = $1
+ AND un.notification_id = $2
+ AND un.deleted_at IS NULL
+ LIMIT 1
+ "#,
+ user_id,
+ notification_id,
+ )
+ .fetch_optional(db)
+ .await?;
+
+ let notification = row
+ .map(|row| -> Result<RawUserNotification, sqlx::Error> {
+ Ok(RawUserNotification {
+ owner_id: row.owner_id,
+ notification_id: row.notification_id,
+ notification_event_type: row.notification_event_type,
+ entity: EntityType::from_str(&row.event_item_type)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .with_entity_string(row.event_item_id),
+ sent: row.sent,
+ done: row.done,
+ created_at: row.created_at,
+ viewed_at: row.viewed_at,
+ deleted_at: row.deleted_at,
+ notification_metadata: row.notification_metadata,
+ sender_id: row
+ .sender_id
+ .map(|s| {
+ Result::<_, ParseErr>::Ok(MacroUserIdStr::parse_from_str(&s)?.into_owned())
+ })
+ .transpose()
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,
+ updated_at: row.updated_at,
+ })
+ })
+ .transpose()?;
+
+ Ok(notification)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use sqlx::{Pool, Postgres};
+
+ #[sqlx::test(fixtures(path = "../../../fixtures", scripts("user_notifications")))]
+ async fn test_get_user_notification_by_id_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let notification_id = "0193b1ea-a542-7589-893b-2b4a509c1e76".parse::<Uuid>()?;
+
+ let notification =
+ get_user_notification_by_id(&pool, "macro|[email protected]", notification_id)
+ .await?
+ .expect("expected notification to exist");
+
+ assert_eq!(notification.owner_id, "macro|[email protected]");
+ assert_eq!(notification.notification_id, notification_id);
+ assert_eq!(notification.notification_event_type, "test");
+ assert_eq!(notification.entity.entity_type, EntityType::Document);
+ assert_eq!(notification.entity.entity_id.as_ref(), "test");
+ assert!(!notification.sent);
+ assert!(!notification.done);
+ assert!(notification.sender_id.is_some());
+
+ Ok(())
+ }
+
+ #[sqlx::test(fixtures(path = "../../../fixtures", scripts("user_notifications")))]
+ async fn test_get_user_notification_by_id_wrong_user(
+ pool: Pool<Postgres>,
+ ) -> anyhow::Result<()> {
+ let notification_id = "0193b1ea-a542-7589-893b-2b4a509c1e76".parse::<Uuid>()?;
+
+ let notification =
+ get_user_notification_by_id(&pool, "macro|[email protected]", notification_id).await?;
+
+ assert!(notification.is_none());
+
+ Ok(())
+ }
+
+ #[sqlx::test(fixtures(path = "../../../fixtures", scripts("user_notifications")))]
+ async fn test_get_user_notification_by_id_ignores_deleted(
+ pool: Pool<Postgres>,
+ ) -> anyhow::Result<()> {
+ let notification_id = "0193b1ea-a542-7589-893b-2b4a509c1e76".parse::<Uuid>()?;
+
+ sqlx::query!(
+ r#"
+ UPDATE user_notification
+ SET deleted_at = NOW()
+ WHERE user_id = $1
+ AND notification_id = $2
+ "#,
+ notification_id,
+ )
+ .execute(&pool)
+ .await?;
+
+ let notification =
+ get_user_notification_by_id(&pool, "macro|[email protected]", notification_id).await?;
+
+ assert!(notification.is_none());
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rs
index 49df78203e..53d5bd1525 100644
--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rs
+++ b/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rs
@@ -1,3 +1,4 @@
pub mod get_all;
+pub mod get_by_id;
pub mod should_email;
pub mod unsent;
diff --git a/rust/cloud-storage/notification_service/src/api/swagger.rs b/rust/cloud-storage/notification_service/src/api/swagger.rs
index 601ab56ec6..aec4ddfea6 100644
--- a/rust/cloud-storage/notification_service/src/api/swagger.rs
+++ b/rust/cloud-storage/notification_service/src/api/swagger.rs
@@ -41,6 +41,7 @@ use crate::{
/// /user_notifications
user_notification::get_user_notification::handler,
+ user_notification::get_user_notification_by_id::handler,
user_notification::delete_user_notification::handler,
user_notification::bulk_mark_user_notification_seen_by_event::handler,
user_notification::bulk_mark_user_notification_done_by_event::handler,
diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification_by_id.rs b/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification_by_id.rs
new file mode 100644
index 0000000000..2522437671
--- /dev/null
+++ b/rust/cloud-storage/notification_service/src/api/user_notification/get_user_notification_by_id.rs
@@ -0,0 +1,112 @@
+use axum::{
+ Extension, Json,
+ extract::rejection::PathRejection,
+ extract::{Path, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use model::response::ErrorResponse;
+use model::user::UserContext;
+use model_notifications::UserNotification;
+use uuid::Uuid;
+
+use crate::api::context::ApiContext;
+
+#[derive(Debug, serde::Deserialize)]
+pub struct Params {
+ pub notification_id: Uuid,
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum GetNotificationErr {
+ #[error("invalid notification_id")]
+ InvalidNotificationId,
+ #[error("notification not found")]
+ NotFound,
+ #[error("failed to get user notification by id")]
+ Db(#[source] anyhow::Error),
+ #[error("failed to convert notification")]
+ Convert(#[source] anyhow::Error),
+}
+
+impl IntoResponse for GetNotificationErr {
+ fn into_response(self) -> Response {
+ match self {
+ GetNotificationErr::InvalidNotificationId => (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: "invalid notification_id",
+ }),
+ )
+ .into_response(),
+ GetNotificationErr::NotFound => (
+ StatusCode::NOT_FOUND,
+ Json(ErrorResponse {
+ message: "notification not found",
+ }),
+ )
+ .into_response(),
+ GetNotificationErr::Db(_) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "failed to get user notification by id",
+ }),
+ )
+ .into_response(),
+ GetNotificationErr::Convert(_) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "failed to convert notification",
+ }),
+ )
+ .into_response(),
+ }
+ }
+}
+
+/// Gets a single user notification by id.
+#[utoipa::path(
+ get,
+ operation_id = "get_user_notification_by_id",
+ path = "/user_notifications/{notification_id}",
+ params(
+ ("notification_id" = String, Path, description = "ID of the notification")
+ ),
+ responses(
+ (status = 200, body=UserNotification),
+ (status = 400, body=ErrorResponse),
+ (status = 401, body=ErrorResponse),
+ (status = 404, body=ErrorResponse),
+ (status = 500, body=ErrorResponse),
+ )
+ )]
+#[tracing::instrument(skip(ctx, user_context), fields(user_id=?user_context.user_id), err)]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ user_context: Extension<UserContext>,
+ path: Result<Path<Params>, PathRejection>,
+) -> Result<Json<UserNotification>, GetNotificationErr> {
+ let Path(Params { notification_id }) =
+ path.map_err(|_| GetNotificationErr::InvalidNotificationId)?;
+
+ let raw =
+ notification_db_client::user_notification::get::get_by_id::get_user_notification_by_id(
+ &ctx.db,
+ &user_context.user_id,
+ notification_id,
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, "failed to get user notification by id");
+ GetNotificationErr::Db(e)
+ })?;
+
+ let raw = raw.ok_or(GetNotificationErr::NotFound)?;
+
+ let notification = UserNotification::try_from(raw).map_err(|e| {
+ tracing::error!(error=?e, "failed to convert notification");
+ GetNotificationErr::Convert(e)
+ })?;
+
+ Ok(Json(notification))
+}
diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/mod.rs b/rust/cloud-storage/notification_service/src/api/user_notification/mod.rs
index e477180d50..3937cbb05a 100644
--- a/rust/cloud-storage/notification_service/src/api/user_notification/mod.rs
+++ b/rust/cloud-storage/notification_service/src/api/user_notification/mod.rs
@@ -13,6 +13,7 @@ pub(in crate::api) mod bulk_mark_user_notification_seen_by_event;
pub(in crate::api) mod bulk_mark_user_notification_undone;
pub(in crate::api) mod delete_user_notification;
pub(in crate::api) mod get_user_notification;
+pub(in crate::api) mod get_user_notification_by_id;
pub(in crate::api) mod get_user_notifications_by_event_item_id;
pub fn router() -> Router<ApiContext> {
@@ -28,7 +29,7 @@ pub fn router() -> Router<ApiContext> {
)
.route(
"/:notification_id",
- delete(delete_user_notification::handler),
+ get(get_user_notification_by_id::handler).delete(delete_user_notification::handler),
)
.route("/bulk", delete(bulk_delete_user_notification::handler))
.route(
diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
index ad6ee9d6eb..5ef1234633 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
@@ -81,6 +81,7 @@ pub fn generate_apns_notification<T: XmlFormatter>(
notif: &NotificationWithRecipient,
) -> Result<Option<APNSPushNotification<PushNotificationData>>, NotificationErr> {
let create_push_data = |route: Route| PushNotificationData {
+ notification_id: notif.inner.id,
notification_entity: notif.inner.notification_entity.clone(),
sender_id: notif.inner.sender_id.as_ref().map(|x| x.to_string()),
open_route: route.0,
diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs b/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs
index 9aacd7e35a..1f9a249fe9 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs
@@ -1,5 +1,6 @@
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
+use uuid::Uuid;
pub mod generate;
pub mod process;
@@ -8,6 +9,8 @@ pub mod remove;
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct PushNotificationData {
+ /// The id of the notification record (UserNotification.id)
+ pub notification_id: Uuid,
#[serde(flatten)]
pub notification_entity: model_entity::Entity<'static>,
/// user id of the macro user who generated the notification