Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(comms): channel invite sends email for non-existing user (#2468)
Sean Aye76bb17dd3422
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadata.tsindex a111e60cb4..37cd5b849b 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadata.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadata.ts@@ -4,12 +4,16 @@* notification_service* OpenAPI spec version: 0.1.0*/--import type { ChannelInviteMetadataAllOf } from './channelInviteMetadataAllOf';-import type { CommonChannelMetadata } from './commonChannelMetadata';+import type { ChannelInviteMetadataSenderProfilePictureUrl } from './channelInviteMetadataSenderProfilePictureUrl';/**- * Metadata for when a user is invited to a channel+ * Metadata for when a user is invited to a channel.*/-export type ChannelInviteMetadata = CommonChannelMetadata &- ChannelInviteMetadataAllOf;+export interface ChannelInviteMetadata {+ /** The name of the channel */+ channelName?: string;+ /** The user who sent the invitation */+ invitedBy: string;+ /** The sender's profile picture URL, if available. */+ senderProfilePictureUrl?: ChannelInviteMetadataSenderProfilePictureUrl;+}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataAllOf.tsdeleted file mode 100644index 0368df339a..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataAllOf.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */-import type { ChannelInviteMetadataAllOfSenderProfilePictureUrl } from './channelInviteMetadataAllOfSenderProfilePictureUrl';--export type ChannelInviteMetadataAllOf = {- invitedBy: string;- senderProfilePictureUrl?: ChannelInviteMetadataAllOfSenderProfilePictureUrl;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataAllOfSenderProfilePictureUrl.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataAllOfSenderProfilePictureUrl.tsdeleted file mode 100644index cb82d595e3..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataAllOfSenderProfilePictureUrl.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type ChannelInviteMetadataAllOfSenderProfilePictureUrl = string | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataSenderProfilePictureUrl.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataSenderProfilePictureUrl.tsnew file mode 100644index 0000000000..2b467755d6--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataSenderProfilePictureUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The sender's profile picture URL, if available.+ */+export type ChannelInviteMetadataSenderProfilePictureUrl = string | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts b/js/app/packages/service-clients/service-notification/generated/schemas/index.tsindex 54d813ee35..915bde1ccb 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts@@ -16,8 +16,7 @@ export * from './apiUserNotificationAllOfViewedAt';export * from './bulkGetByEventItemIdsRequest';export * from './bulkGetTypedNotificationsByEventItemIdsParams';export * from './channelInviteMetadata';-export * from './channelInviteMetadataAllOf';-export * from './channelInviteMetadataAllOfSenderProfilePictureUrl';+export * from './channelInviteMetadataSenderProfilePictureUrl';export * from './channelMentionMetadata';export * from './channelMentionMetadataAllOf';export * from './channelMentionMetadataAllOfSenderProfilePictureUrl';diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex 95496da5a7..571d7c7188 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -1102,24 +1102,23 @@}},"ChannelInviteMetadata": {- "allOf": [- {- "$ref": "#/components/schemas/CommonChannelMetadata"+ "type": "object",+ "description": "Metadata for when a user is invited to a channel.",+ "required": ["invitedBy"],+ "properties": {+ "channelName": {+ "type": "string",+ "description": "The name of the channel"},- {- "type": "object",- "required": ["invitedBy"],- "properties": {- "invitedBy": {- "type": "string"- },- "senderProfilePictureUrl": {- "type": ["string", "null"]- }- }+ "invitedBy": {+ "type": "string",+ "description": "The user who sent the invitation"+ },+ "senderProfilePictureUrl": {+ "type": ["string", "null"],+ "description": "The sender's profile picture URL, if available."}- ],- "description": "Metadata for when a user is invited to a channel"+ }},"ChannelMentionMetadata": {"allOf": [diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex aca9999c7a..c1ea14137d 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2100,6 +2100,7 @@ dependencies = ["models_permissions","notification","reqwest",+ "rootcause","secretsmanager_client","serde","serde_json",@@ -5409,7 +5410,9 @@ dependencies = ["askama","macro_env","macro_user_id",+ "model-entity","notification",+ "rootcause","serde","serde_json","url",diff --git a/rust/cloud-storage/comms_service/Cargo.toml b/rust/cloud-storage/comms_service/Cargo.tomlindex c160826366..5c784eb95f 100644--- a/rust/cloud-storage/comms_service/Cargo.toml+++ b/rust/cloud-storage/comms_service/Cargo.toml@@ -82,5 +82,9 @@ utoipa = { workspace = true, features = ["axum_extras", "chrono", "uuid"] }utoipa-swagger-ui = { workspace = true, features = ["axum"] }uuid = { workspace = true }+[dev-dependencies]+rootcause = { workspace = true }+tokio = { workspace = true, features = ["macros"] }+[package.metadata.cargo-machete]ignored = ["connection_gateway"]diff --git a/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs b/rust/cloud-storage/comms_service/src/api/channels/add_participants.rsindex 8e0a861f3c..8c944d7d3c 100644--- a/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs+++ b/rust/cloud-storage/comms_service/src/api/channels/add_participants.rs@@ -96,48 +96,46 @@ pub async fn handler(tracing::info!(elapsed=?start.elapsed(), "added user channel permissions");// There should always be participants, but better safe than sorry- if !participants.is_empty() {- let metadata = CommonChannelMetadata {- channel_type: model_notifications::ChannelType::mirror(channel_type),- channel_name: channel_name.clone(),- };- comms_notification::dispatch_notifications_for_invite(- &ctx,- &channel_id,- &MacroUserIdStr::parse_from_str(&channel_member.context.user_id)- .map_err(|_e| (StatusCode::BAD_REQUEST, "Invalid macro user id".to_string()))?- .into_owned(),- req.participants.clone(),- metadata.clone(),- )- .await- .inspect_err(|e| {- tracing::error!(error=?e, "unable to send channel invite notification");- })- .ok();+ let metadata = CommonChannelMetadata {+ channel_type: model_notifications::ChannelType::mirror(channel_type),+ channel_name: channel_name.clone(),+ };+ comms_notification::dispatch_notifications_for_invite(+ &ctx,+ &channel_id,+ &MacroUserIdStr::parse_from_str(&channel_member.context.user_id)+ .map_err(|_e| (StatusCode::BAD_REQUEST, "Invalid macro user id".to_string()))?+ .into_owned(),+ req.participants.clone(),+ metadata.clone(),+ )+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, "unable to send channel invite notification");+ })+ .ok();- if matches!(channel_type, ChannelType::Private) && !channel_participants.is_empty() {- // Contacts: add participants to social graph- let channel_participants: Vec<String> = channel_participants- .iter()- .map(|p| p.user_id.to_string())- .collect();- let sqs_client = &ctx.sqs_client;- sqs_client- .enqueue_contacts_add_participants(- participants.clone(),- channel_participants,- &channel_id.to_string(),+ if matches!(channel_type, ChannelType::Private) && !channel_participants.is_empty() {+ // Contacts: add participants to social graph+ let channel_participants: Vec<String> = channel_participants+ .iter()+ .map(|p| p.user_id.to_string())+ .collect();+ let sqs_client = &ctx.sqs_client;+ sqs_client+ .enqueue_contacts_add_participants(+ participants.clone(),+ channel_participants,+ &channel_id.to_string(),+ )+ .await+ .map_err(|e| {+ tracing::error!(error=?e, "unable to create 'add participant' SQS message");+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ "unable to create 'add participant' SQS message".to_string(),)- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to create 'add participant' SQS message");- (- StatusCode::INTERNAL_SERVER_ERROR,- "unable to create 'add participant' SQS message".to_string(),- )- })?;- }+ })?;}Ok(StatusCode::OK)diff --git a/rust/cloud-storage/comms_service/src/notification.rs b/rust/cloud-storage/comms_service/src/notification.rsindex bbc6fb2f66..91232ae58a 100644--- a/rust/cloud-storage/comms_service/src/notification.rs+++ b/rust/cloud-storage/comms_service/src/notification.rs@@ -8,24 +8,20 @@ use comms_db_client::{use macro_db_client::notification::BasicCloudStorageItemMetadata;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::comms::ChannelParticipant;-use model_entity::{Entity, EntityType};+use model_entity::EntityType;use model_notifications::{ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,- ChannelReplyMetadata, CommonChannelMetadata, DocumentMentionMetadata, NotifEvent,+ ChannelReplyMetadata, CommonChannelMetadata, DocumentMentionMetadata,};use notification_hex::domain::models::SendNotificationRequestBuilder;use notification_hex::domain::service::NotificationIngress;use std::{collections::HashSet, iter::once};use uuid::Uuid;-struct NotificationMsg {- notification_entity: Entity<'static>,- notification_event: NotifEvent,- sender_id: Option<MacroUserIdStr<'static>>,- recipient_ids: Vec<MacroUserIdStr<'static>>,-}+#[cfg(test)]+mod test;-pub struct ChannelMessageEvent<'a> {+struct ChannelMessageEvent<'a> {channel_id: &'a Uuid,message: &'a Message,channel_metadata: &'a CommonChannelMetadata,@@ -35,106 +31,82 @@ pub struct ChannelMessageEvent<'a> {participants: &'a [ChannelParticipant],thread_participants: &'a [MacroUserIdStr<'static>],thread_parent_sender_id: Option<MacroUserIdStr<'static>>,-}--pub struct ChannelInviteEvent<'a> {- channel_id: &'a Uuid,- invited_by_user_id: &'a MacroUserIdStr<'static>,- recipient_user_ids: &'a [String],- common: &'a CommonChannelMetadata,+ sender_profile_picture_url: Option<String>,}fn recipients_excluding<'a>(recipients: impl IntoIterator<Item = &'a str>,exclude: impl IntoIterator<Item = &'a str>,-) -> Vec<MacroUserIdStr<'static>> {+) -> impl Iterator<Item = MacroUserIdStr<'static>> {let exclude_set: HashSet<&str> = exclude.into_iter().collect();recipients.into_iter()- .filter(|id| !exclude_set.contains(id))+ .filter(move |id| !exclude_set.contains(id)).filter_map(|id| MacroUserIdStr::parse_from_str(id).ok()).map(|u| u.into_owned())- .collect()-}--fn create_notification_queue_message(- channel_id: &Uuid,- sender_id: MacroUserIdStr<'static>,- recipients: Vec<MacroUserIdStr<'static>>,- notification_event: NotifEvent,-) -> NotificationMsg {- NotificationMsg {- notification_entity: EntityType::Channel.with_entity_string(channel_id.to_string()),- sender_id: Some(sender_id),- recipient_ids: recipients,- notification_event,- }-}--impl<'a> ChannelInviteEvent<'a> {- fn generate_notifications(&self) -> Vec<NotificationMsg> {- let mut notifications: Vec<NotificationMsg> = vec![];-- if !self.recipient_user_ids.is_empty() {- notifications.push(create_notification_queue_message(- self.channel_id,- self.invited_by_user_id.copied().into_owned(),- recipients_excluding(- self.recipient_user_ids.iter().map(|m| m.as_str()),- once(self.invited_by_user_id.as_ref()),- ),- NotifEvent::ChannelInvite(ChannelInviteMetadata {- invited_by: self.invited_by_user_id.clone(),- common: self.common.clone(),- sender_profile_picture_url: None,- }),- ));- }-- notifications- }}impl ChannelMessageEvent<'_> {- fn generate_notifications(&self) -> Vec<NotificationMsg> {- let mut notifications: Vec<NotificationMsg> = vec![];+ async fn send(&self, ingress: &impl NotificationIngress) -> anyhow::Result<()> {+ let entity = || EntityType::Channel.with_entity_string(self.channel_id.to_string());+ let sender = || Some(self.message.sender_id.clone());+ // Send mention notifications for @mentioned usersif !self.user_mentions.is_empty() {- notifications.push(create_notification_queue_message(- self.channel_id,- self.message.sender_id.clone(),- recipients_excluding(- self.user_mentions.iter().map(|m| m.as_str()),- once(self.message.sender_id.0.as_ref()),- ),- NotifEvent::ChannelMention(ChannelMentionMetadata {- message_content: self.message.content.clone(),- message_id: self.message.id.to_string(),- thread_id: self.message.thread_id.map(|t| t.to_string()),- common: self.channel_metadata.clone(),- sender_profile_picture_url: None,- }),- ));+ ingress+ .send_notification(+ SendNotificationRequestBuilder {+ notification_entity: entity(),+ notification: ChannelMentionMetadata {+ message_content: self.message.content.clone(),+ message_id: self.message.id.to_string(),+ thread_id: self.message.thread_id.map(|t| t.to_string()),+ common: self.channel_metadata.clone(),+ sender_profile_picture_url: self.sender_profile_picture_url.clone(),+ },+ sender_id: sender(),+ recipient_ids: recipients_excluding(+ self.user_mentions.iter().map(|m| m.as_str()),+ once(self.message.sender_id.0.as_ref()),+ )+ .collect(),+ }+ .into_request()+ .with_apns()+ .with_conn_gateway(),+ )+ .await+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;}+ // Send document mention notificationsif !self.document_mentions.is_empty() {- let recipients_excluding_mentions = recipients_excluding(+ let doc_recipients: HashSet<_> = recipients_excluding(self.participants.iter().map(|p| p.user_id.as_ref()),once(self.message.sender_id.0.as_ref()),- );+ )+ .collect();for mention in self.document_mentions {- notifications.push(create_notification_queue_message(- self.channel_id,- self.message.sender_id.clone(),- recipients_excluding_mentions.clone(),- NotifEvent::DocumentMention(DocumentMentionMetadata {- document_name: mention.item_name.clone(),- owner: mention.item_owner.clone(),- file_type: mention.file_type.clone(),- sender_profile_picture_url: None,- }),- ));+ ingress+ .send_notification(+ SendNotificationRequestBuilder {+ notification_entity: entity(),+ notification: DocumentMentionMetadata {+ document_name: mention.item_name.clone(),+ owner: mention.item_owner.clone(),+ file_type: mention.file_type.clone(),+ sender_profile_picture_url: self.sender_profile_picture_url.clone(),+ },+ sender_id: sender(),+ recipient_ids: doc_recipients.clone(),+ }+ .into_request()+ .with_apns()+ .with_conn_gateway(),+ )+ .await+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;}}@@ -143,163 +115,99 @@ impl ChannelMessageEvent<'_> {.collect::<Vec<&str>>();// MessageSend and Invite notifications are sent to all participants except the sender and- // mentioned users. Mentioned users receive a seperate ChannelMention Notification.- let recipients_without_sender_and_mentions = recipients_excluding(+ // mentioned users. Mentioned users receive a separate ChannelMention notification.+ let recipients_without_sender_and_mentions: HashSet<_> = recipients_excluding(self.participants.iter().map(|p| p.user_id.as_ref()),sender_and_mentions.clone(),- );+ )+ .collect();match (self.channel_message_count, self.message.thread_id) {// Thread Message Reply(_, Some(thread_id)) => {if !self.thread_participants.is_empty() {- notifications.push(create_notification_queue_message(- self.channel_id,- self.message.sender_id.clone(),- recipients_excluding(- self.thread_participants.iter().map(|p| p.as_ref()),- sender_and_mentions,- ),- NotifEvent::ChannelMessageReply(ChannelReplyMetadata {- thread_id: thread_id.to_string(),- message_id: self.message.id.to_string(),- user_id: self.message.sender_id.clone(),- message_content: self.message.content.clone(),- thread_parent_sender_id: self.thread_parent_sender_id.clone(),- common: self.channel_metadata.clone(),- sender_profile_picture_url: None,- }),- ));+ ingress+ .send_notification(+ SendNotificationRequestBuilder {+ notification_entity: entity(),+ notification: ChannelReplyMetadata {+ thread_id: thread_id.to_string(),+ message_id: self.message.id.to_string(),+ user_id: self.message.sender_id.clone(),+ message_content: self.message.content.clone(),+ thread_parent_sender_id: self.thread_parent_sender_id.clone(),+ common: self.channel_metadata.clone(),+ sender_profile_picture_url: self+ .sender_profile_picture_url+ .clone(),+ },+ sender_id: sender(),+ recipient_ids: recipients_excluding(+ self.thread_participants.iter().map(|p| p.as_ref()),+ sender_and_mentions,+ )+ .collect(),+ }+ .into_request()+ .with_apns()+ .with_conn_gateway(),+ )+ .await+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;} else {tracing::warn!("thread participants is empty, but message has thread id");}}// Channel has no messages, send invite notification(0, None) => {- notifications.push(create_notification_queue_message(- self.channel_id,- self.message.sender_id.clone(),- recipients_without_sender_and_mentions.clone(),- NotifEvent::ChannelInvite(ChannelInviteMetadata {- invited_by: self.message.sender_id.clone(),- common: self.channel_metadata.clone(),- sender_profile_picture_url: None,- }),- ));+ ingress+ .send_notification(+ SendNotificationRequestBuilder {+ notification_entity: entity(),+ notification: ChannelInviteMetadata {+ invited_by: self.message.sender_id.clone(),+ channel_name: self.channel_metadata.channel_name.clone(),+ sender_profile_picture_url: self.sender_profile_picture_url.clone(),+ },+ sender_id: sender(),+ recipient_ids: recipients_without_sender_and_mentions,+ }+ .into_request()+ .with_apns()+ .with_conn_gateway(),+ )+ .await+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;}// Channel has messages, send message send notification(_, None) => {- notifications.push(create_notification_queue_message(- self.channel_id,- self.message.sender_id.clone(),- recipients_without_sender_and_mentions.clone(),- NotifEvent::ChannelMessageSend(ChannelMessageSendMetadata {- message_id: self.message.id.to_string(),- sender: self.message.sender_id.clone(),- message_content: self.message.content.to_string(),- common: self.channel_metadata.clone(),- sender_profile_picture_url: None,- }),- ));+ ingress+ .send_notification(+ SendNotificationRequestBuilder {+ notification_entity: entity(),+ notification: ChannelMessageSendMetadata {+ message_id: self.message.id.to_string(),+ sender: self.message.sender_id.clone(),+ message_content: self.message.content.to_string(),+ common: self.channel_metadata.clone(),+ sender_profile_picture_url: self.sender_profile_picture_url.clone(),+ },+ sender_id: sender(),+ recipient_ids: recipients_without_sender_and_mentions,+ }+ .into_request()+ .with_apns()+ .with_conn_gateway(),+ )+ .await+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;}}- notifications+ Ok(())}}-async fn send_notification_queue_message(- ingress: &impl NotificationIngress,- msg: NotificationMsg,-) -> anyhow::Result<()> {- let entity = msg.notification_entity;- let sender_id = msg.sender_id;- let recipient_ids: HashSet<MacroUserIdStr<'_>> = msg.recipient_ids.into_iter().collect();-- match msg.notification_event {- NotifEvent::ChannelInvite(metadata) => {- let req = SendNotificationRequestBuilder {- notification_entity: entity,- notification: metadata,- sender_id,- recipient_ids,- }- .into_request()- .with_apns()- .with_conn_gateway();- ingress- .send_notification(req)- .await- .map_err(|e| anyhow::anyhow!("{e}"))?;- }- NotifEvent::ChannelMessageSend(metadata) => {- let req = SendNotificationRequestBuilder {- notification_entity: entity,- notification: metadata,- sender_id,- recipient_ids,- }- .into_request()- .with_apns()- .with_conn_gateway();- ingress- .send_notification(req)- .await- .map_err(|e| anyhow::anyhow!("{e}"))?;- }- NotifEvent::ChannelMention(metadata) => {- let req = SendNotificationRequestBuilder {- notification_entity: entity,- notification: metadata,- sender_id,- recipient_ids,- }- .into_request()- .with_apns()- .with_conn_gateway();- ingress- .send_notification(req)- .await- .map_err(|e| anyhow::anyhow!("{e}"))?;- }- NotifEvent::ChannelMessageReply(metadata) => {- let req = SendNotificationRequestBuilder {- notification_entity: entity,- notification: metadata,- sender_id,- recipient_ids,- }- .into_request()- .with_apns()- .with_conn_gateway();- ingress- .send_notification(req)- .await- .map_err(|e| anyhow::anyhow!("{e}"))?;- }- NotifEvent::DocumentMention(metadata) => {- let req = SendNotificationRequestBuilder {- notification_entity: entity,- notification: metadata,- sender_id,- recipient_ids,- }- .into_request()- .with_apns()- .with_conn_gateway();- ingress- .send_notification(req)- .await- .map_err(|e| anyhow::anyhow!("{e}"))?;- }- other => {- tracing::warn!(?other, "unhandled notification event type in comms_service");- }- }-- Ok(())-}-pub async fn dispatch_notifications_for_invite(api_context: &AppState,channel_id: &Uuid,@@ -307,28 +215,59 @@ pub async fn dispatch_notifications_for_invite(recipient_user_ids: Vec<String>,common: CommonChannelMetadata,) -> anyhow::Result<()> {+ let parsed_recipients: Vec<_> = recipient_user_ids+ .iter()+ .filter_map(|id| MacroUserIdStr::parse_from_str(id).ok())+ .map(|u| u.0)+ .collect();+let sender_profile_picture_url =get_sender_profile_picture_url(&api_context.db, invited_by_user_id).await;- let event = ChannelInviteEvent {- channel_id,- invited_by_user_id,- recipient_user_ids: &recipient_user_ids,- common: &common,- };-- let mut notifications = event.generate_notifications();- for n in &mut notifications {- set_sender_profile_picture(- &mut n.notification_event,- sender_profile_picture_url.clone(),- );- }+ let existing_users: HashSet<String> =+ macro_db_client::user::get_all::get_existing_users(&api_context.db, &parsed_recipients)+ .await?+ .into_iter()+ .collect();- for notification in notifications {- send_notification_queue_message(&*api_context.notification_ingress_service, notification)- .await?;- }+ let (existing_users, not_existing_users): (HashSet<_>, HashSet<_>) = parsed_recipients+ .into_iter()+ .map(MacroUserIdStr)+ .partition(|id| existing_users.contains(id.as_ref()));++ let _ = tokio::try_join!(+ api_context.notification_ingress_service.send_notification(+ SendNotificationRequestBuilder {+ notification_entity: EntityType::Channel.with_entity_string(channel_id.to_string()),+ notification: ChannelInviteMetadata {+ invited_by: invited_by_user_id.clone(),+ channel_name: common.channel_name.clone(),+ sender_profile_picture_url: sender_profile_picture_url.clone(),+ },+ sender_id: Some(invited_by_user_id.copied().into_owned()),+ recipient_ids: existing_users,+ }+ .into_request()+ .with_apns()+ .with_conn_gateway(),+ ),+ api_context.notification_ingress_service.send_notification(+ SendNotificationRequestBuilder {+ notification_entity: EntityType::Channel.with_entity_string(channel_id.to_string()),+ notification: ChannelInviteMetadata {+ invited_by: invited_by_user_id.clone(),+ channel_name: common.channel_name.clone(),+ sender_profile_picture_url,+ },+ sender_id: Some(invited_by_user_id.copied().into_owned()),+ recipient_ids: not_existing_users,+ }+ .into_request()+ .with_apns()+ .with_conn_gateway(),+ )+ )+ .map_err(|e| anyhow::anyhow!("{e:?}"))?;Ok(())}@@ -384,7 +323,10 @@ pub async fn dispatch_notifications_for_message((vec![], None)};- let channel_message_event = ChannelMessageEvent {+ let sender_profile_picture_url =+ get_sender_profile_picture_url(&api_context.db, &message.sender_id).await;++ ChannelMessageEvent {channel_id,message: &message,channel_metadata: &channel_metadata,@@ -394,25 +336,10 @@ pub async fn dispatch_notifications_for_message(participants: &participants,thread_participants: &thread_participants,thread_parent_sender_id,- };-- let sender_profile_picture_url =- get_sender_profile_picture_url(&api_context.db, &message.sender_id).await;-- let mut notifications = channel_message_event.generate_notifications();- for n in &mut notifications {- set_sender_profile_picture(- &mut n.notification_event,- sender_profile_picture_url.clone(),- );+ sender_profile_picture_url,}-- for notification in notifications {- send_notification_queue_message(&*api_context.notification_ingress_service, notification)- .await?;- }-- Ok(())+ .send(&*api_context.notification_ingress_service)+ .await}async fn get_sender_profile_picture_url(@@ -427,477 +354,3 @@ async fn get_sender_profile_picture_url(.ok().and_then(|pics| pics.pictures.into_iter().next().map(|p| p.url))}--fn set_sender_profile_picture(event: &mut NotifEvent, url: Option<String>) {- match event {- NotifEvent::ChannelInvite(m) => m.sender_profile_picture_url = url,- NotifEvent::ChannelMessageSend(m) => m.sender_profile_picture_url = url,- NotifEvent::ChannelMention(m) => m.sender_profile_picture_url = url,- NotifEvent::ChannelMessageReply(m) => m.sender_profile_picture_url = url,- NotifEvent::DocumentMention(m) => m.sender_profile_picture_url = url,- NotifEvent::MentionedInDocumentComment(m) => m.sender_profile_picture_url = url,- NotifEvent::RepliedToDocumentCommentThread(m) => m.sender_profile_picture_url = url,- NotifEvent::CommentedOnDocument(m) => m.sender_profile_picture_url = url,- _ => {}- }-}--#[cfg(test)]-mod tests {- use super::*;- use model::comms::{ChannelId, ParticipantRole};- use std::collections::HashMap;- use uuid::Uuid;-- fn participant(user_id: MacroUserIdStr<'static>, channel_id: Uuid) -> ChannelParticipant {- ChannelParticipant {- user_id,- channel_id: ChannelId(channel_id),- role: ParticipantRole::Member,- left_at: None,- joined_at: chrono::Utc::now(),- }- }-- fn message(- channel_id: Uuid,- sender_id: MacroUserIdStr<'static>,- thread_id: Option<Uuid>,- ) -> Message {- Message {- id: Uuid::new_v4(),- sender_id,- content: "test".to_string(),- thread_id,- channel_id,- created_at: chrono::Utc::now(),- deleted_at: None,- edited_at: None,- updated_at: chrono::Utc::now(),- }- }-- fn doc_metadata(name: &str) -> BasicCloudStorageItemMetadata {- BasicCloudStorageItemMetadata {- item_name: name.to_string(),- item_owner: MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- file_type: Some("pdf".to_string()),- item_id: "id".to_string(),- }- }-- fn private_metadata() -> CommonChannelMetadata {- CommonChannelMetadata {- channel_type: model_notifications::ChannelType::Private,- channel_name: "group".to_string(),- }- }-- fn is_message_notification(event: &NotifEvent) -> bool {- matches!(- event,- NotifEvent::ChannelMessageSend(_)- | NotifEvent::ChannelMessageReply(_)- | NotifEvent::ChannelMention(_)- )- }-- fn uid(s: &str) -> MacroUserIdStr<'static> {- MacroUserIdStr::parse_from_str(s).unwrap().into_owned()- }-- // Ensures that each recipient receives only one message notification- fn assert_single_message_notification_per_recipient(notifications: &[NotificationMsg]) {- let mut visited: HashMap<MacroUserIdStr<'static>, usize> = HashMap::new();-- for n in notifications {- if !is_message_notification(&n.notification_event) {- continue;- }- for r in &n.recipient_ids {- *visited.entry(r.clone()).or_default() += 1;- }- }-- let violations: Vec<_> = visited- .into_iter()- .filter(|(_, count)| *count > 1)- .collect();-- assert!(- violations.is_empty(),- "notifications sent to multiple recipients: {violations:?}"- );- }-- #[test]- fn sender_excluded_from_all_recipients() {- let channel_id = Uuid::new_v4();- let participants = vec![- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- ];- let msg = message(- channel_id,- MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- None,- );- let metadata = private_metadata();-- let event = ChannelMessageEvent {- channel_id: &channel_id,- message: &msg,- channel_metadata: &metadata,- channel_message_count: 1,- user_mentions: &[],- document_mentions: &[],- participants: &participants,- thread_participants: &[],- thread_parent_sender_id: None,- };-- let notifications = event.generate_notifications();-- assert_single_message_notification_per_recipient(¬ifications);-- for n in ¬ifications {- let recipients = &n.recipient_ids;- assert!(- !recipients.contains(&uid("macro|[email protected]")),- "sender should never receive their own notifications"- );- }- }-- #[test]- fn first_message_sends_invite_notification() {- let channel_id = Uuid::new_v4();- let participants = vec![- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- ];- let msg = message(- channel_id,- MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- None,- );- let metadata = private_metadata();-- let event = ChannelMessageEvent {- channel_id: &channel_id,- message: &msg,- channel_metadata: &metadata,- channel_message_count: 0,- user_mentions: &[],- document_mentions: &[],- participants: &participants,- thread_participants: &[],- thread_parent_sender_id: None,- };-- let notifications = event.generate_notifications();- assert_single_message_notification_per_recipient(¬ifications);-- assert_eq!(notifications.len(), 1);- assert!(matches!(- notifications[0].notification_event,- NotifEvent::ChannelInvite(_)- ));- }-- #[test]- fn subsequent_messages_send_message_send_notification() {- let channel_id = Uuid::new_v4();- let participants = vec![- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- ];- let msg = message(- channel_id,- MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- None,- );- let metadata = private_metadata();-- let event = ChannelMessageEvent {- channel_id: &channel_id,- message: &msg,- channel_metadata: &metadata,- channel_message_count: 5,- user_mentions: &[],- document_mentions: &[],- participants: &participants,- thread_participants: &[],- thread_parent_sender_id: None,- };-- let notifications = event.generate_notifications();- assert_single_message_notification_per_recipient(¬ifications);-- assert_eq!(notifications.len(), 1);- assert!(matches!(- notifications[0].notification_event,- NotifEvent::ChannelMessageSend(_)- ));- }-- #[test]- fn mentioned_users_get_mention_not_message_send() {- let channel_id = Uuid::new_v4();- let participants = vec![- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- ];- let msg = message(- channel_id,- MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- None,- );- let metadata = private_metadata();- let user_mentions = vec!["macro|[email protected]".to_string()];-- let event = ChannelMessageEvent {- channel_id: &channel_id,- message: &msg,- channel_metadata: &metadata,- channel_message_count: 1,- user_mentions: &user_mentions,- document_mentions: &[],- participants: &participants,- thread_participants: &[],- thread_parent_sender_id: None,- };-- let notifications = event.generate_notifications();- assert_single_message_notification_per_recipient(¬ifications);-- let mention = notifications- .iter()- .find(|n| matches!(n.notification_event, NotifEvent::ChannelMention(_)))- .expect("should have mention notification");-- let mention_recipients = &mention.recipient_ids;-- assert!(mention_recipients.contains(&uid("macro|[email protected]")));-- let send = notifications- .iter()- .find(|n| matches!(n.notification_event, NotifEvent::ChannelMessageSend(_)))- .expect("should have message send notification");-- let send_recipients = &send.recipient_ids;- assert!(!send_recipients.contains(&uid("macro|[email protected]")));- assert!(send_recipients.contains(&uid("macro|[email protected]")));- }-- #[test]- fn thread_reply_excludes_sender_and_mentions() {- let channel_id = Uuid::new_v4();- let thread_id = Uuid::new_v4();- let participants = vec![- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- ];- let msg = message(- channel_id,- MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- Some(thread_id),- );- let metadata = private_metadata();- let user_mentions = vec!["macro|[email protected]".to_string()];- let thread_participants = vec![- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- ];-- let thread_parent_sender_id = Some(- MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- );- let event = ChannelMessageEvent {- channel_id: &channel_id,- message: &msg,- channel_metadata: &metadata,- channel_message_count: 5,- user_mentions: &user_mentions,- document_mentions: &[],- participants: &participants,- thread_participants: &thread_participants,- thread_parent_sender_id,- };-- let notifications = event.generate_notifications();- assert_single_message_notification_per_recipient(¬ifications);-- let reply = notifications- .iter()- .find(|n| matches!(n.notification_event, NotifEvent::ChannelMessageReply(_)))- .expect("should have reply notification");-- let recipients = &reply.recipient_ids;- assert!(!recipients.contains(&uid("macro|[email protected]")));- assert!(!recipients.contains(&uid("macro|[email protected]")));- assert!(recipients.contains(&uid("macro|[email protected]")));- assert!(recipients.contains(&uid("macro|[email protected]")));- }-- #[test]- fn document_mentions_exclude_sender() {- let channel_id = Uuid::new_v4();- let participants = vec![- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- ];- let msg = message(- channel_id,- MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- None,- );- let metadata = private_metadata();- let doc_mentions = vec![doc_metadata("test.pdf")];-- let event = ChannelMessageEvent {- channel_id: &channel_id,- message: &msg,- channel_metadata: &metadata,- channel_message_count: 1,- user_mentions: &[],- document_mentions: &doc_mentions,- participants: &participants,- thread_participants: &[],- thread_parent_sender_id: None,- };-- let notifications = event.generate_notifications();- assert_single_message_notification_per_recipient(¬ifications);-- let doc_notif = notifications- .iter()- .find(|n| matches!(n.notification_event, NotifEvent::DocumentMention(_)))- .expect("should have document notification");-- let recipients = &doc_notif.recipient_ids;- assert!(!recipients.contains(&uid("macro|[email protected]")));- assert!(recipients.contains(&uid("macro|[email protected]")));- assert!(recipients.contains(&uid("macro|[email protected]")));- }-- #[test]- fn empty_thread_participants_logs_warning() {- let channel_id = Uuid::new_v4();- let thread_id = Uuid::new_v4();- let participants = vec![- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- participant(- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),- channel_id,- ),- ];- let msg = message(- channel_id,- MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned(),- Some(thread_id),- );- let metadata = private_metadata();-- let event = ChannelMessageEvent {- channel_id: &channel_id,- message: &msg,- channel_metadata: &metadata,- channel_message_count: 5,- user_mentions: &[],- document_mentions: &[],- participants: &participants,- thread_participants: &[],- thread_parent_sender_id: None,- };-- let notifications = event.generate_notifications();- assert_single_message_notification_per_recipient(¬ifications);-- // Should not create reply notification with empty thread participants- let has_reply = notifications- .iter()- .any(|n| matches!(n.notification_event, NotifEvent::ChannelMessageReply(_)));-- assert!(!has_reply);- }-}diff --git a/rust/cloud-storage/comms_service/src/notification/test.rs b/rust/cloud-storage/comms_service/src/notification/test.rsnew file mode 100644index 0000000000..7746b6a486--- /dev/null+++ b/rust/cloud-storage/comms_service/src/notification/test.rs@@ -0,0 +1,219 @@+use super::*;+use model::comms::{ChannelId, ParticipantRole};+use notification_hex::domain::models::{Notification, NotificationResult, SendNotificationRequest};+use notification_hex::domain::service::SendNotificationError;+use std::collections::HashMap;+use std::sync::Mutex;+use uuid::Uuid;++struct MockNotificationIngress {+ recorded_requests: Mutex<Vec<serde_json::Value>>,+}++impl MockNotificationIngress {+ fn new() -> Self {+ Self {+ recorded_requests: Mutex::new(Vec::new()),+ }+ }++ fn recorded_requests(&self) -> Vec<serde_json::Value> {+ self.recorded_requests.lock().unwrap().clone()+ }+}++impl NotificationIngress for MockNotificationIngress {+ async fn send_notification<+ 'a,+ T: Notification + Clone + 'static,+ U: serde::Serialize + Send + Sync + 'static,+ >(+ &'a self,+ req: SendNotificationRequest<'a, T, U>,+ ) -> Result<Option<NotificationResult<'a>>, rootcause::Report<SendNotificationError>> {+ let snapshot = serde_json::to_value(&req).unwrap();+ self.recorded_requests.lock().unwrap().push(snapshot);+ Ok(None)+ }+}++fn participant(user_id: MacroUserIdStr<'static>, channel_id: Uuid) -> ChannelParticipant {+ ChannelParticipant {+ user_id,+ channel_id: ChannelId(channel_id),+ role: ParticipantRole::Member,+ left_at: None,+ joined_at: chrono::Utc::now(),+ }+}++fn message(+ channel_id: Uuid,+ sender_id: MacroUserIdStr<'static>,+ thread_id: Option<Uuid>,+) -> Message {+ Message {+ id: Uuid::new_v4(),+ sender_id,+ content: "test".to_string(),+ thread_id,+ channel_id,+ created_at: chrono::Utc::now(),+ deleted_at: None,+ edited_at: None,+ updated_at: chrono::Utc::now(),+ }+}++fn private_metadata() -> CommonChannelMetadata {+ CommonChannelMetadata {+ channel_type: model_notifications::ChannelType::Private,+ channel_name: "group".to_string(),+ }+}++fn uid(s: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str(s).unwrap().into_owned()+}++fn get_type_name(req: &serde_json::Value) -> &str {+ req["req"]["notification"]["tag"].as_str().unwrap()+}++fn get_recipient_ids(req: &serde_json::Value) -> HashSet<String> {+ req["req"]["recipient_ids"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap().to_string())+ .collect()+}++const MESSAGE_NOTIF_TYPES: &[&str] = &[+ "channel_message_send",+ "channel_message_reply",+ "channel_mention",+];++fn assert_single_message_notification_per_recipient(requests: &[serde_json::Value]) {+ let mut visited: HashMap<String, usize> = HashMap::new();++ for req in requests {+ let type_name = get_type_name(req);+ if !MESSAGE_NOTIF_TYPES.contains(&type_name) {+ continue;+ }+ for r in get_recipient_ids(req) {+ *visited.entry(r).or_default() += 1;+ }+ }++ let violations: Vec<_> = visited+ .into_iter()+ .filter(|(_, count)| *count > 1)+ .collect();++ assert!(+ violations.is_empty(),+ "notifications sent to multiple recipients: {violations:?}"+ );+}++#[tokio::test]+async fn mentioned_users_get_mention_not_message_send() {+ let channel_id = Uuid::new_v4();+ let participants = vec![+ participant(uid("macro|[email protected]"), channel_id),+ participant(uid("macro|[email protected]"), channel_id),+ participant(uid("macro|[email protected]"), channel_id),+ ];+ let msg = message(channel_id, uid("macro|[email protected]"), None);+ let metadata = private_metadata();+ let user_mentions = vec!["macro|[email protected]".to_string()];++ let ingress = MockNotificationIngress::new();+ ChannelMessageEvent {+ channel_id: &channel_id,+ message: &msg,+ channel_metadata: &metadata,+ channel_message_count: 1,+ user_mentions: &user_mentions,+ document_mentions: &[],+ participants: &participants,+ thread_participants: &[],+ thread_parent_sender_id: None,+ sender_profile_picture_url: None,+ }+ .send(&ingress)+ .await+ .unwrap();++ let requests = ingress.recorded_requests();+ assert_single_message_notification_per_recipient(&requests);++ let mention = requests+ .iter()+ .find(|r| get_type_name(r) == "channel_mention")+ .expect("should have mention notification");+ let mention_recipients = get_recipient_ids(mention);+ assert!(mention_recipients.contains("macro|[email protected]"));++ let send = requests+ .iter()+ .find(|r| get_type_name(r) == "channel_message_send")+ .expect("should have message send notification");+ let send_recipients = get_recipient_ids(send);+ assert!(!send_recipients.contains("macro|[email protected]"));+ assert!(send_recipients.contains("macro|[email protected]"));+}++#[tokio::test]+async fn thread_reply_excludes_sender_and_mentions() {+ let channel_id = Uuid::new_v4();+ let thread_id = Uuid::new_v4();+ let participants = vec![+ participant(uid("macro|[email protected]"), channel_id),+ participant(uid("macro|[email protected]"), channel_id),+ participant(uid("macro|[email protected]"), channel_id),+ participant(uid("macro|[email protected]"), channel_id),+ ];+ let msg = message(channel_id, uid("macro|[email protected]"), Some(thread_id));+ let metadata = private_metadata();+ let user_mentions = vec!["macro|[email protected]".to_string()];+ let thread_participants = vec![+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ ];++ let ingress = MockNotificationIngress::new();+ ChannelMessageEvent {+ channel_id: &channel_id,+ message: &msg,+ channel_metadata: &metadata,+ channel_message_count: 5,+ user_mentions: &user_mentions,+ document_mentions: &[],+ participants: &participants,+ thread_participants: &thread_participants,+ thread_parent_sender_id: Some(uid("macro|[email protected]")),+ sender_profile_picture_url: None,+ }+ .send(&ingress)+ .await+ .unwrap();++ let requests = ingress.recorded_requests();+ assert_single_message_notification_per_recipient(&requests);++ let reply = requests+ .iter()+ .find(|r| get_type_name(r) == "channel_message_reply")+ .expect("should have reply notification");+ let recipients = get_recipient_ids(reply);+ assert!(!recipients.contains("macro|[email protected]"));+ assert!(!recipients.contains("macro|[email protected]"));+ assert!(recipients.contains("macro|[email protected]"));+ assert!(recipients.contains("macro|[email protected]"));+}diff --git a/rust/cloud-storage/email_formatting/src/lib.rs b/rust/cloud-storage/email_formatting/src/lib.rsindex f5eafcc097..2312b85215 100644--- a/rust/cloud-storage/email_formatting/src/lib.rs+++ b/rust/cloud-storage/email_formatting/src/lib.rs@@ -4,10 +4,11 @@ use hmac::Hmac;use macro_env::Environment;use macro_service_urls::EnvExtMacroServiceUrls;use macro_user_id::cowlike::CowLike;-use model_notifications::{NotifEvent, NotificationTitle};+use model_notifications::NotifEvent;use notification::domain::models::{- Notification, NotificationExtEmail, RateLimitConfig, RateLimitKey, UserNotificationRow,- email_notification_digest::ports::DigestBatch, queue_message::EmailContent, signing::SignedUrl,+ Notification, NotificationExtEmail, NotificationTitle, RateLimitConfig, RateLimitKey,+ UserNotificationRow, email_notification_digest::ports::DigestBatch,+ queue_message::EmailContent, signing::SignedUrl,};use rootcause::Report;use serde::{Deserialize, Serialize};diff --git a/rust/cloud-storage/email_formatting/templates/digest.html b/rust/cloud-storage/email_formatting/templates/digest.htmlindex b127010d6b..1ae314761c 100644--- a/rust/cloud-storage/email_formatting/templates/digest.html+++ b/rust/cloud-storage/email_formatting/templates/digest.html@@ -5,7 +5,7 @@xmlns="http://www.w3.org/1999/xhtml"><head>- <title>You're Invited to Macro</title>+ <title>Macro Notification Digest</title><meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /><meta content="width=device-width, initial-scale=1" name="viewport" /><!--[if mso]>diff --git a/rust/cloud-storage/invite_email/Cargo.toml b/rust/cloud-storage/invite_email/Cargo.tomlindex c1407fead3..368e80144d 100644--- a/rust/cloud-storage/invite_email/Cargo.toml+++ b/rust/cloud-storage/invite_email/Cargo.toml@@ -9,7 +9,9 @@ version = "0.1.0"askama = { workspace = true }macro_env = { path = "../macro_env" }macro_user_id = { path = "../macro_user_id" }+model-entity = { path = "../model-entity" }notification = { path = "../notification" }+rootcause = { workspace = true }serde = { workspace = true }url = { workspace = true, features = ["serde"] }utoipa = { workspace = true }diff --git a/rust/cloud-storage/invite_email/src/lib.rs b/rust/cloud-storage/invite_email/src/lib.rsindex 70c1ab68ca..4daf29bc82 100644--- a/rust/cloud-storage/invite_email/src/lib.rs+++ b/rust/cloud-storage/invite_email/src/lib.rs@@ -2,17 +2,24 @@//! Domain models for invitation email notifications.//!//! Contains the [`InviteToMacro`] referral notification, the [`InviteToTeamMetadata`] team-//! invitation notification, and the [`ReferralCode`] newtype.+//! invitation notification, the [`ChannelInviteMetadata`] channel invitation, and the+//! [`ReferralCode`] newtype.#[cfg(test)]mod test;use askama::Template;use macro_env::Environment;+use macro_user_id::cowlike::CowLike;use macro_user_id::email::EmailStr;+use macro_user_id::email::ReadEmailParts;use macro_user_id::user_id::MacroUserIdStr;+use model_entity::Entity;use notification::domain::models::{- Notification, NotificationExtEmail, RateLimitConfig, RateLimitKey, queue_message::EmailContent,+ NotifCollapseKey, Notification, NotificationExtEmail, NotificationExtIos, NotificationTitle,+ RateLimitConfig, RateLimitKey,+ apple::{APNSPushNotification, AlertDictionary, Aps, PushNotificationData},+ queue_message::EmailContent,};use serde::{Deserialize, Serialize};use std::time::Duration;@@ -109,6 +116,123 @@ impl NotificationExtEmail for InviteToMacro {}}+/// Metadata for when a user is invited to a channel.+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema, Template)]+#[serde(rename_all = "camelCase")]+#[template(path = "invite_to_channel.html")]+pub struct ChannelInviteMetadata {+ /// The user who sent the invitation+ #[serde(alias = "invited_by")]+ #[schema(value_type = String)]+ pub invited_by: MacroUserIdStr<'static>,+ /// The name of the channel+ #[serde(default)]+ #[serde(alias = "channel_name")]+ pub channel_name: String,+ /// The sender's profile picture URL, if available.+ #[serde(default)]+ pub sender_profile_picture_url: Option<String>,+}++impl ChannelInviteMetadata {+ fn signup_url(&self) -> Url {+ signup_url(Environment::new_or_prod())+ }++ fn sender_display(&self) -> &str {+ self.invited_by.email_str()+ }+}++impl Notification for ChannelInviteMetadata {+ const TYPE_NAME: &'static str = "channel_invite";+}++impl NotificationTitle for ChannelInviteMetadata {+ fn format_title(+ &self,+ _sender_id: Option<MacroUserIdStr<'_>>,+ ) -> Result<String, rootcause::Report> {+ let email = self.invited_by.email_part();+ let sender = email.email_str();+ Ok(format!(+ "{sender} invited you to join #{}",+ self.channel_name+ ))+ }++ fn format_body(+ &self,+ _sender_id: Option<MacroUserIdStr<'_>>,+ ) -> Result<String, rootcause::Report> {+ Ok("Open macro to continue".to_string())+ }+}++impl NotificationExtEmail for ChannelInviteMetadata {+ fn format_email(&self) -> EmailContent {+ let sender = self.sender_display();+ EmailContent {+ subject: format!("{sender} has invited you to join #{}", self.channel_name),+ body: self+ .render()+ .expect("ChannelInviteMetadata template render failed in format_email"),+ }+ }++ fn rate_limit_config() -> RateLimitConfig {+ RateLimitConfig {+ max_count: 1,+ window: Duration::from_hours(24 * 7),+ }+ }++ fn rate_limit_key(&self) -> RateLimitKey {+ RateLimitKey::builder(&Self::TYPE_NAME)+ .append(&self.invited_by)+ .finish()+ }+}++impl NotificationExtIos for ChannelInviteMetadata {+ type NotifData = PushNotificationData;++ fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {+ let entity_type: &'static str = entity.entity_type.into();+ NotifCollapseKey::new(entity_type).append(&entity.entity_id)+ }++ fn as_apns<'a>(+ &self,+ sender_id: Option<MacroUserIdStr<'a>>,+ _entity: &Entity<'_>,+ notification_id: Uuid,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ let title = self+ .format_title(sender_id.as_ref().map(CowLike::copied))+ .ok()?;+ let body = self.format_body(sender_id).ok()?;+ let mutable_content = self.sender_profile_picture_url.as_ref().map(|_| 1);+ Some(APNSPushNotification {+ aps: Aps {+ alert: Some(notification::domain::models::apple::Alert::Dictionary(+ AlertDictionary {+ title: Some(title),+ body: Some(body),+ ..Default::default()+ },+ )),+ mutable_content,+ ..Default::default()+ },+ push_notification_data: PushNotificationData {+ notification_id,+ sender_profile_picture_url: self.sender_profile_picture_url.clone(),+ },+ })+ }+}+/// Metadata for when a user is invited to a team.#[derive(Serialize, Deserialize, Debug, Clone, ToSchema, Template)]#[serde(rename_all = "camelCase")]diff --git a/rust/cloud-storage/invite_email/templates/invite_to_channel.html b/rust/cloud-storage/invite_email/templates/invite_to_channel.htmlnew file mode 100644index 0000000000..2f20bddcc9--- /dev/null+++ b/rust/cloud-storage/invite_email/templates/invite_to_channel.html@@ -0,0 +1,228 @@+<!doctype html>+<html+ xmlns:o="urn:schemas-microsoft-com:office:office"+ xmlns:v="urn:schemas-microsoft-com:vml"+ xmlns="http://www.w3.org/1999/xhtml"+>+ <head>+ <title>You're Invited to Join #{{ channel_name }} on Macro</title>+ <!--[if !mso]><!-->+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <!--<![endif]-->+ <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />+ <meta content="width=device-width, initial-scale=1" name="viewport" />+ <!--[if mso]>+ <noscript>+ <xml>+ <o:OfficeDocumentSettings>+ <o:AllowPNG />+ <o:PixelsPerInch>96</o:PixelsPerInch>+ </o:OfficeDocumentSettings>+ </xml>+ </noscript>+ <![endif]-->+ <!--[if lte mso 11]>+ <style type="text/css">+ .mj-outlook-group-fix {+ width: 100% !important;+ }+ </style>+ <![endif]-->++ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,[email protected],500&display=swap" rel="stylesheet">++ <style type="text/css">+ @font-face {+ font-family: "Berkeley Mono";+ src: url("https://pub-4030931feb3e4212b2ac93166a411ea7.r2.dev/berkley.woff2")+ format("woff2");+ font-display: fallback;+ }++ #outlook a {+ padding: 0;+ }++ img {+ -ms-interpolation-mode: bicubic;+ text-decoration: none;+ line-height: 100%;+ outline: none;+ height: auto;+ border: 0;+ }+ </style>+ </head>+ <body+ style="+ -webkit-text-size-adjust: 100%;+ -ms-text-size-adjust: 100%;+ word-spacing: normal;+ padding: 0;+ margin: 0;+ "+ >+ <div style="box-sizing: border-box; padding: 60px 20px; width: 100%">+ <div+ style="+ font-family:+ "Berkeley Mono", "Courier New", Courier,+ monospace;+ background-color: #fcfcfc;+ border: 1px solid #e0e0e0;+ box-sizing: border-box;+ border-radius: 4px;+ max-width: 570px;+ font-size: 15px;+ margin: 0 auto;+ overflow: clip;+ color: #999;+ width: 100%;+ "+ >+ <table+ cellpadding="0"+ cellspacing="0"+ style="+ font-family: "Inter", sans-serif;+ background-color: #f5f5f5;+ color: #090909;+ box-sizing: border-box;+ font-size: 18px;+ padding: 10px 20px;+ width: 100%;+ border: none;+ "+ >+ <tbody>+ <tr>+ {% if let Some(url) = sender_profile_picture_url %}+ <td+ style="+ vertical-align: middle;+ width: 40px;+ min-width: 40px;+ padding-right: 8px;+ "+ >+ <div+ style="+ border: 1px solid #e0e0e0;+ box-sizing: border-box;+ border-radius: 20px;+ overflow: clip;+ height: 40px;+ width: 40px;+ "+ >+ <img+ src="{{ url }}"+ alt=""+ style="+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+ "+ />+ </div>+ </td>+ {% endif %}+ <td style="vertical-align: middle; line-height: 1.2">+ <span+ style="+ color: #626262;+ font-family:+ "Berkeley Mono", "Courier New",+ Courier, monospace;+ "+ >{{ sender_display() }}</span+ > has invited you to join <strong>#{{ channel_name }}</strong>+ </td>+ </tr>+ </tbody>+ </table>+ <hr style="border: none; border-top: 1px dashed #e0e0e0; margin: 0" />+ <div style="box-sizing: border-box; padding: 20px">+ <div+ style="+ color: #090909;+ font-size: 16px;+ font-family: "Inter", sans-serif;+ line-height: 1.4;+ "+ >+ You've been invited to join <strong>#{{ channel_name }}</strong> on Macro.+ Collaborate on documents. Stay in sync with tasks. Search over+ everything. AI Assistance with anything.+ </div>++ <table+ style="+ mso-table-lspace: 0pt;+ mso-table-rspace: 0pt;+ border: none;+ width: 100%;+ "+ cellpadding="0"+ cellspacing="0"+ >+ <tbody>+ <tr>+ <td+ style="+ vertical-align: bottom;+ padding: 20px 0 0 0;+ width: 50%;+ "+ >+ <a+ style="+ font-family:+ "Berkeley Mono", "Courier New",+ Courier, monospace;+ background-color: #ff8f00;+ text-decoration: none;+ display: inline-block;+ white-space: nowrap;+ border-radius: 2px;+ width: min-content;+ padding: 4px 10px;+ color: #090909;+ "+ href="{{ signup_url() }}"+ target="_blank"+ >+ Join #{{ channel_name }}+ </a>+ </td>+ <td+ style="+ vertical-align: top;+ text-align: right;+ padding: 0;+ width: 50%;+ "+ >+ <img+ src="https://static-file-service.macro.com/file/b911aba9-94a6-435c-aa16-8404739f13b0"+ alt="Macro"+ style="+ -ms-interpolation-mode: bicubic;+ line-height: 100%;+ outline: none;+ width: 60px;+ border: 0;+ "+ />+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>+ </div>+ </body>+</html>diff --git a/rust/cloud-storage/macro_user_id/src/user_id.rs b/rust/cloud-storage/macro_user_id/src/user_id.rsindex 922926564b..3f38bff768 100644--- a/rust/cloud-storage/macro_user_id/src/user_id.rs+++ b/rust/cloud-storage/macro_user_id/src/user_id.rs@@ -199,10 +199,15 @@ where{/// return the [EmailParts] contained within selfpub fn email_part<'a>(&'a self) -> Email<ArcCowStr<'a>> {- let id_str = self.user_id.as_ref();- let email_str = &id_str[self.email_part_offset..];+ let email_str = self.email_str();self.email_part.map(|_| ArcCowStr::Borrowed(email_str))}++ /// return the email as a string slice+ pub fn email_str(&self) -> &str {+ let id_str = self.user_id.as_ref();+ &id_str[self.email_part_offset..]+ }}impl<'a, T> CowLike<'a> for MacroUserId<T>diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rsindex ce1ec54cc0..6004fe100d 100644--- a/rust/cloud-storage/model_notifications/src/lib.rs+++ b/rust/cloud-storage/model_notifications/src/lib.rs@@ -215,9 +215,7 @@ impl NotificationTitle for NotifEvent {}NotifEvent::RepliedToDocumentCommentThread(m) => m.format_title(sender_id),NotifEvent::CommentedOnDocument(m) => m.format_title(sender_id),- NotifEvent::ChannelInvite(channel_invite_metadata) => {- channel_invite_metadata.format_title(sender_id)- }+ NotifEvent::ChannelInvite(m) => m.format_title(sender_id),NotifEvent::ChannelMessageSend(channel_message_send_metadata) => {channel_message_send_metadata.format_title(sender_id)}@@ -251,9 +249,7 @@ impl NotificationTitle for NotifEvent {}NotifEvent::RepliedToDocumentCommentThread(m) => m.format_body(sender_id),NotifEvent::CommentedOnDocument(m) => m.format_body(sender_id),- NotifEvent::ChannelInvite(channel_invite_metadata) => {- channel_invite_metadata.format_body(sender_id)- }+ NotifEvent::ChannelInvite(m) => m.format_body(sender_id),NotifEvent::ChannelMessageSend(channel_message_send_metadata) => {channel_message_send_metadata.format_body(sender_id)}diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rsindex 5341159c5f..730b98d02e 100644--- a/rust/cloud-storage/model_notifications/src/metadata.rs+++ b/rust/cloud-storage/model_notifications/src/metadata.rs@@ -1,10 +1,11 @@use doppleganger::Doppleganger;-pub use invite_email::InviteToTeamMetadata;+pub use invite_email::{ChannelInviteMetadata, InviteToTeamMetadata};use macro_user_id::cowlike::CowLike;use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};use mention_utils::parse::{ParsedXmlText, XmlFormatter};use model_entity::Entity;use model_entity::EntityType;+pub use notification::domain::models::NotificationTitle;use notification::domain::models::{NotifCollapseKey, Notification, NotificationExtIos,apple::{APNSPushNotification, AlertDictionary, Aps, PushNotificationData},@@ -63,19 +64,6 @@ pub struct CommonChannelMetadata {pub channel_name: String,}-/// Metadata for when a user is invited to a channel-#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct ChannelInviteMetadata {- #[serde(alias = "invited_by")]- #[schema(value_type = String)]- pub invited_by: MacroUserIdStr<'static>,- #[serde(flatten)]- pub common: CommonChannelMetadata,- #[serde(default)]- pub sender_profile_picture_url: Option<String>,-}-#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]#[serde(rename_all = "camelCase")]pub struct ChannelMessageSendMetadata {@@ -222,10 +210,6 @@ impl NotificationTitle for NewEmailMetadata {}}-impl notification::domain::models::Notification for ChannelInviteMetadata {- const TYPE_NAME: &'static str = "channel_invite";-}-impl notification::domain::models::Notification for AiResponseMetadata {const TYPE_NAME: &'static str = "ai_response";}@@ -246,19 +230,6 @@ impl notification::domain::models::Notification for DocumentMentionMetadata {const TYPE_NAME: &'static str = "document_mention";}-pub trait NotificationTitle {- /// format the notification into a user facing title- fn format_title(- &self,- sender_id: Option<MacroUserIdStr<'_>>,- ) -> Result<String, rootcause::Report>;-- fn format_body(- &self,- sender_id: Option<MacroUserIdStr<'_>>,- ) -> Result<String, rootcause::Report>;-}-impl NotificationTitle for ChannelMentionMetadata {fn format_title(&self,@@ -373,25 +344,6 @@ impl NotificationTitle for ChannelReplyMetadata {}}-impl NotificationTitle for ChannelInviteMetadata {- fn format_title(- &self,- _sender_id: Option<MacroUserIdStr<'_>>,- ) -> Result<String, rootcause::Report> {- let email = self.invited_by.email_part();- let sender = email.email_str();- let channel = &self.common.channel_name;- Ok(format!("{sender} invited you to join #{channel}"))- }-- fn format_body(- &self,- _sender_id: Option<MacroUserIdStr<'_>>,- ) -> Result<String, rootcause::Report> {- Ok("Open macro to continue".to_string())- }-}-/// Metadata for when a user is assigned to a task#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]#[serde(rename_all = "camelCase")]@@ -501,25 +453,6 @@ fn alert_apns<T: NotificationTitle>(})}-impl NotificationExtIos for ChannelInviteMetadata {- type NotifData = ::notification::domain::models::apple::PushNotificationData;-- fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {- let entity_type: &'static str = entity.entity_type.into();- NotifCollapseKey::new(entity_type).append(&entity.entity_id)- }-- fn as_apns<'a>(- &self,- sender_id: Option<MacroUserIdStr<'a>>,- _entity: &Entity<'_>,- notification_id: Uuid,- ) -> Option<APNSPushNotification<Self::NotifData>> {- let profile_pic = self.sender_profile_picture_url.clone();- alert_apns(self, sender_id, notification_id, profile_pic).ok()- }-}-impl NotificationTitle for AiResponseMetadata {fn format_title(&self,diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rsindex 6819fdad87..a46833683f 100644--- a/rust/cloud-storage/notification/src/domain/models.rs+++ b/rust/cloud-storage/notification/src/domain/models.rs@@ -275,6 +275,23 @@ pub trait NotificationExtEmail: Notification {fn rate_limit_key(&self) -> RateLimitKey;}+/// Extension trait for notifications that have a user-facing title and body.+///+/// Used for formatting push notification alerts (APNS) and notification previews.+pub trait NotificationTitle {+ /// Format the notification into a user-facing title.+ fn format_title(+ &self,+ sender_id: Option<MacroUserIdStr<'_>>,+ ) -> Result<String, rootcause::Report>;++ /// Format the notification into a user-facing body.+ fn format_body(+ &self,+ sender_id: Option<MacroUserIdStr<'_>>,+ ) -> Result<String, rootcause::Report>;+}+/// Extension trait for notifications that can be delivered via iOS push (APNS).pub trait NotificationExtIos: Notification {/// The custom data type included in the APNS push notification payload.