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(channels): support welcome message from julia (#5104)

teodf91ba6c0ce0
diff --git a/Cargo.lock b/Cargo.lock
index 67be3dc046..6ea3240b59 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1006,6 +1006,7 @@ dependencies = [
"macro_user_id",
"macro_uuid",
"maud",
+ "mention_utils",
"miniserde",
"mobile_welcome_email_db_client",
"mockall",
@@ -1022,6 +1023,7 @@ dependencies = [
"remote_env_var",
"reqwest 0.13.4",
"roles_and_permissions",
+ "rootcause",
"rsa",
"secretsmanager_client",
"serde",
diff --git a/crates/channels/src/domain/models.rs b/crates/channels/src/domain/models.rs
index 0c2e39f4f9..2143a31079 100644
--- a/crates/channels/src/domain/models.rs
+++ b/crates/channels/src/domain/models.rs
@@ -794,6 +794,16 @@ pub struct SimpleMention {
pub entity_id: String,
}
+impl SimpleMention {
+ /// Construct a tracked mention of a Macro user.
+ pub fn user(user_id: &MacroUserIdStr<'_>) -> Self {
+ Self {
+ entity_type: "user".to_string(),
+ entity_id: user_id.as_ref().to_string(),
+ }
+ }
+}
+
/// Shareable entity type referenced by a channel message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ReferencedShareItemType {
diff --git a/crates/mention_utils/src/lib.rs b/crates/mention_utils/src/lib.rs
index 5ce9f7b758..b71921946d 100644
--- a/crates/mention_utils/src/lib.rs
+++ b/crates/mention_utils/src/lib.rs
@@ -1,4 +1,5 @@
pub mod parse;
+pub mod serialize;
#[cfg(test)]
mod tests;
diff --git a/crates/mention_utils/src/serialize.rs b/crates/mention_utils/src/serialize.rs
new file mode 100644
index 0000000000..31399235fa
--- /dev/null
+++ b/crates/mention_utils/src/serialize.rs
@@ -0,0 +1,21 @@
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::Serialize;
+
+#[cfg(test)]
+mod test;
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct UserMention<'a> {
+ user_id: &'a str,
+ email: &'a str,
+}
+
+/// Serialize a Macro user as an in-app user mention node.
+pub fn user_mention(user_id: &MacroUserIdStr<'_>) -> Result<String, serde_json::Error> {
+ let payload = serde_json::to_string(&UserMention {
+ user_id: user_id.as_ref(),
+ email: user_id.email_str(),
+ })?;
+ Ok(format!("<m-user-mention>{payload}</m-user-mention>"))
+}
diff --git a/crates/mention_utils/src/serialize/test.rs b/crates/mention_utils/src/serialize/test.rs
new file mode 100644
index 0000000000..85cde72390
--- /dev/null
+++ b/crates/mention_utils/src/serialize/test.rs
@@ -0,0 +1,13 @@
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::*;
+
+#[test]
+fn serializes_user_mention() {
+ let user_id = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+
+ assert_eq!(
+ user_mention(&user_id).unwrap(),
+ "<m-user-mention>{\"userId\":\"macro|[email protected]\",\"email\":\"[email protected]\"}</m-user-mention>"
+ );
+}
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index 00ad153405..77cf19193e 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -95,6 +95,7 @@ macro_queues = { path = "../../crates/macro_queues" }
macro_middleware = { path = "../../crates/macro_middleware", default-features = false, features = [
"tracking",
] }
+mention_utils = { path = "../../crates/mention_utils" }
macro_service_urls = { path = "../../crates/macro_service_urls" }
macro_tower_layers = { path = "../../crates/macro_tower_layers" }
macro_user_id = { path = "../../crates/macro_user_id" }
@@ -116,6 +117,7 @@ referral = { path = "../../crates/referral" }
remote_env_var = { path = "../../crates/remote_env_var" }
reqwest = { workspace = true }
roles_and_permissions = { path = "../../crates/roles_and_permissions" }
+rootcause = { workspace = true }
rsa = { version = "0.9.10", features = ["getrandom"] }
secretsmanager_client = { path = "../../crates/secretsmanager_client" }
serde = { workspace = true }
diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
index b09d2d2d52..9781205a19 100644
--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs
@@ -16,6 +16,7 @@ use crate::{
rate_limit_config::RATE_LIMIT_CONFIG,
};
use authentication_service::service::user::create_user::create_user;
+use authentication_service::service::user::support_channel_welcome::post_support_channel_welcome;
use channels::domain::{
models::{ChannelType, CreateChannelRequest, Sender},
ports::ChannelService,
@@ -37,7 +38,6 @@ const MACRO_SUPPORT_EMAILS: [&str; 3] = ["[email protected]", "[email protected]", "
fn support_channel_name<T: AsRef<str>>(email: &Email<T>) -> String {
format!("Macro Support x {}", email.local_part())
}
-
/// FusionAuth create user webhook
#[tracing::instrument(skip(ctx, req, _internal_authorization), fields(email=%req.event.user.email, fusionauth_user_id=%req.event.user.id, username=?req.event.user.username, event_type=%req.event.event_type, ip_address=%req.event.info.ip_address))]
pub async fn handler(
@@ -370,6 +370,16 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> an
{
tracing::error!(error=?e, channel_id=%channel.id, %email, "failed to favorite Macro support channel");
}
+
+ let _ = post_support_channel_welcome(
+ channel_service.as_ref(),
+ &channel.id,
+ owner_id,
+ )
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, channel_id=%channel.id, %email, "failed to post Macro support welcome message");
+ });
}
});
diff --git a/services/authentication_service/src/service/user/mod.rs b/services/authentication_service/src/service/user/mod.rs
index 8ea6fc477d..ca714dfe67 100644
--- a/services/authentication_service/src/service/user/mod.rs
+++ b/services/authentication_service/src/service/user/mod.rs
@@ -1 +1,2 @@
pub mod create_user;
+pub mod support_channel_welcome;
diff --git a/services/authentication_service/src/service/user/support_channel_welcome.rs b/services/authentication_service/src/service/user/support_channel_welcome.rs
new file mode 100644
index 0000000000..435ad7a329
--- /dev/null
+++ b/services/authentication_service/src/service/user/support_channel_welcome.rs
@@ -0,0 +1,95 @@
+use std::future::Future;
+
+use channels::domain::{
+ models::{PostMessageNotificationPolicy, PostMessageRequest, Sender, SimpleMention},
+ ports::ChannelService,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use mention_utils::serialize::user_mention;
+use rootcause::{Report, prelude::ResultExt};
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+const JACOB_EMAIL: &str = "[email protected]";
+const JULIA_EMAIL: &str = "[email protected]";
+const TEO_EMAIL: &str = "[email protected]";
+
+/// The channel operation required to post a new user's welcome message.
+pub trait SupportChannelMessageGateway: Send + Sync + 'static {
+ /// Post the initial welcome message.
+ fn post_message(
+ &self,
+ actor: Sender,
+ channel_id: Uuid,
+ request: PostMessageRequest,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+}
+
+impl<T> SupportChannelMessageGateway for T
+where
+ T: ChannelService,
+{
+ async fn post_message(
+ &self,
+ actor: Sender,
+ channel_id: Uuid,
+ request: PostMessageRequest,
+ ) -> Result<(), Report> {
+ ChannelService::post_message(self, actor, channel_id, request)
+ .await
+ .context("failed to post Macro support welcome message")?;
+
+ Ok(())
+ }
+}
+
+fn support_user(email: &str) -> Result<MacroUserIdStr<'static>, Report> {
+ Ok(MacroUserIdStr::try_from_email(email)
+ .context_with(|| format!("invalid Macro support user email: {email}"))?)
+}
+
+/// Post Julia's welcome message in a newly created support channel.
+pub async fn post_support_channel_welcome(
+ gateway: &impl SupportChannelMessageGateway,
+ channel_id: &str,
+ new_user: MacroUserIdStr<'static>,
+) -> Result<(), Report> {
+ let channel_id =
+ Uuid::parse_str(channel_id).context("support channel returned an invalid id")?;
+ let jacob = support_user(JACOB_EMAIL)?;
+ let julia = support_user(JULIA_EMAIL)?;
+ let teo = support_user(TEO_EMAIL)?;
+
+ let content = format!(
+ "Hey {},\n\
+Thanks signing up for Macro, we're excited for you to try it out.\n\
+In case you need any help, this is a support channel with {} (the ceo) and {} (the cto).\n\
+If you have any feedback or find any bugs let us know here!\n\
+Julia",
+ user_mention(&new_user)?,
+ user_mention(&jacob)?,
+ user_mention(&teo)?,
+ );
+ let mentions = [&new_user, &jacob, &teo]
+ .into_iter()
+ .map(SimpleMention::user)
+ .collect();
+
+ gateway
+ .post_message(
+ Sender::new_from_user(julia),
+ channel_id,
+ PostMessageRequest {
+ content,
+ mentions,
+ thread_id: None,
+ attachments: Vec::new(),
+ nonce: None,
+ notification_policy: PostMessageNotificationPolicy::Default,
+ triggered_by: None,
+ },
+ )
+ .await
+}
diff --git a/services/authentication_service/src/service/user/support_channel_welcome/test.rs b/services/authentication_service/src/service/user/support_channel_welcome/test.rs
new file mode 100644
index 0000000000..1fae2ce210
--- /dev/null
+++ b/services/authentication_service/src/service/user/support_channel_welcome/test.rs
@@ -0,0 +1,95 @@
+use std::sync::{Arc, Mutex};
+
+use super::*;
+
+#[derive(Clone, Default)]
+struct RecordingGateway {
+ posted: Arc<Mutex<Option<PostedWelcomeMessage>>>,
+}
+
+struct PostedWelcomeMessage {
+ actor: Sender,
+ channel_id: Uuid,
+ request: PostMessageRequest,
+}
+
+impl SupportChannelMessageGateway for RecordingGateway {
+ async fn post_message(
+ &self,
+ actor: Sender,
+ channel_id: Uuid,
+ request: PostMessageRequest,
+ ) -> Result<(), Report> {
+ *self.posted.lock().unwrap() = Some(PostedWelcomeMessage {
+ actor,
+ channel_id,
+ request,
+ });
+ Ok(())
+ }
+}
+
+fn user_id(email: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email(email).unwrap()
+}
+
+#[tokio::test]
+async fn posts_welcome_as_julia_with_valid_user_mentions() {
+ let channel_id = Uuid::new_v4();
+ let gateway = RecordingGateway::default();
+
+ post_support_channel_welcome(
+ &gateway,
+ &channel_id.to_string(),
+ user_id("[email protected]"),
+ )
+ .await
+ .unwrap();
+
+ let posted = gateway.posted.lock().unwrap();
+ let posted = posted.as_ref().unwrap();
+ assert_eq!(posted.actor.as_user(), Some(&user_id("[email protected]")));
+ assert_eq!(posted.channel_id, channel_id);
+ assert_eq!(
+ posted.request.content,
+ concat!(
+ "Hey <m-user-mention>{\"userId\":\"macro|[email protected]\",\"email\":\"[email protected]\"}</m-user-mention>,\n",
+ "Thanks signing up for Macro, we're excited for you to try it out.\n",
+ "In case you need any help, this is a support channel with <m-user-mention>{\"userId\":\"macro|[email protected]\",\"email\":\"[email protected]\"}</m-user-mention> (the ceo) and <m-user-mention>{\"userId\":\"macro|[email protected]\",\"email\":\"[email protected]\"}</m-user-mention> (the cto).\n",
+ "If you have any feedback or find any bugs let us know here!\n",
+ "Julia",
+ )
+ );
+ assert_eq!(
+ posted.request.mentions,
+ vec![
+ SimpleMention::user(&user_id("[email protected]")),
+ SimpleMention::user(&user_id("[email protected]")),
+ SimpleMention::user(&user_id("[email protected]")),
+ ]
+ );
+ assert_eq!(posted.request.thread_id, None);
+ assert!(posted.request.attachments.is_empty());
+ assert_eq!(posted.request.nonce, None);
+ assert_eq!(
+ posted.request.notification_policy,
+ PostMessageNotificationPolicy::Default
+ );
+ assert_eq!(posted.request.triggered_by, None);
+}
+
+#[tokio::test]
+async fn rejects_an_invalid_channel_id_without_posting() {
+ let gateway = RecordingGateway::default();
+
+ let error =
+ post_support_channel_welcome(&gateway, "not-a-uuid", user_id("[email protected]"))
+ .await
+ .unwrap_err();
+
+ assert_eq!(
+ error.downcast_current_context::<&str>().copied(),
+ Some("support channel returned an invalid id")
+ );
+ assert!(gateway.posted.lock().unwrap().is_none());
+}