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(teams): track team events on be (#4584)
Will Hutchinsone962eb1b5826
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex a2d69c09da..f442cb10d7 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -23,6 +23,7 @@"ai_tools","ai_toolset","ai_usage",+ "analytics_client","anthropic","attachment","authentication_service_client",@@ -170,6 +171,7 @@"ai_tools","ai_toolset","ai_usage",+ "analytics_client","anthropic","attachment","authentication_service_client",@@ -610,6 +612,7 @@"ai_tools","ai_toolset","ai_usage",+ "analytics_client","anthropic","attachment","authentication_service_client",@@ -1241,6 +1244,7 @@"ai_tools","ai_toolset","ai_usage",+ "analytics_client","anthropic","attachment","authentication_service_client",@@ -2886,6 +2890,7 @@"ai_tools","ai_toolset","ai_usage",+ "analytics_client","anthropic","attachment","authentication_service_client",@@ -2992,6 +2997,7 @@"ai_tools","ai_toolset","ai_usage",+ "analytics_client","anthropic","attachment","authentication_service_client",@@ -3803,6 +3809,7 @@"ai_tools","ai_toolset","ai_usage",+ "analytics_client","anthropic","attachment","authentication_service_client",@@ -4615,6 +4622,7 @@"agent","ai_toolset","ai_usage",+ "analytics_client","attachment","authentication_service_client","bot_id",diff --git a/.pi/skills/rust-validation/SKILL.md b/.pi/skills/rust-validation/SKILL.mdindex a522571eeb..111fbffef7 100644--- a/.pi/skills/rust-validation/SKILL.md+++ b/.pi/skills/rust-validation/SKILL.md@@ -24,6 +24,7 @@ Run these commands one at a time, in this exact order:just checkjust clippyjust format+just hakari```If `just check` or `just clippy` fails, do not continue to later commands. Inspect the failure, fix it if it is in scope, then rerun the full sequence starting at `just check`.diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex e1b0a6a5b4..56ba83afd2 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -13430,6 +13430,7 @@ name = "teams"version = "0.1.0"dependencies = ["ai_toolset",+ "analytics_client","anyhow","async-stripe","async-trait",diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex e418f02316..cedf6f5ea6 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -41,6 +41,7 @@ pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<NotificationIngressType,teams::outbound::crm_enqueuer::SqsCrmEnqueuer,teams::outbound::team_crm_settings_repo::TeamCrmSettingsRepositoryImpl,+ teams::outbound::team_analytics::AnalyticsClientTeamAnalytics,>;type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex a26ab11233..31d56c7b77 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -38,8 +38,8 @@ use sqlx::postgres::PgPoolOptions;use teams::{domain::team_service::TeamServiceImpl,outbound::{- customer_repo::CustomerRepositoryImpl, team_channels_repo::TeamChannelsRepositoryImpl,- team_repo::TeamRepositoryImpl,+ customer_repo::CustomerRepositoryImpl, team_analytics::AnalyticsClientTeamAnalytics,+ team_channels_repo::TeamChannelsRepositoryImpl, team_repo::TeamRepositoryImpl,},};@@ -204,7 +204,7 @@ async fn main() -> anyhow::Result<()> {tracing::trace!("initialized sqs client");// Initialize analytics client with configured providers- let analytics_client = AnalyticsClient::new(AnalyticsClientConfig {+ let analytics_client = Arc::new(AnalyticsClient::new(AnalyticsClientConfig {google_analytics: config.ga_measurement_id.value()@@ -239,7 +239,7 @@ async fn main() -> anyhow::Result<()> {.unwrap_or_else(|| "https://us.i.posthog.com".to_string()),}}),- });+ }));tracing::trace!("initialized analytics client");let user_roles_and_permissions_macro_db = MacroDB::new(db.clone());@@ -261,8 +261,9 @@ async fn main() -> anyhow::Result<()> {let notification_ingress_service = Arc::new(notification_ingress_service);let crm_enqueuer = teams::outbound::crm_enqueuer::SqsCrmEnqueuer::new(sqs_client.clone());+ let team_analytics = AnalyticsClientTeamAnalytics::new(analytics_client.clone());- let teams_service_impl = TeamServiceImpl::new(+ let teams_service_impl = TeamServiceImpl::new_with_analytics(teams_repo_impl,customer_repo_impl,team_channels_repo_impl,@@ -270,6 +271,7 @@ async fn main() -> anyhow::Result<()> {notification_ingress_service.clone(),crm_enqueuer,team_crm_settings_repo_impl,+ team_analytics,);let foreign_entity_service =@@ -348,7 +350,7 @@ async fn main() -> anyhow::Result<()> {ios_app_bundle_id: IOS_APP_BUNDLE_ID.to_string(),},}),- analytics_client: Arc::new(analytics_client),+ analytics_client,stripe_price_id: config.stripe_price_id.to_string(),},config.port,diff --git a/rust/cloud-storage/teams/Cargo.toml b/rust/cloud-storage/teams/Cargo.tomlindex bbf54d4b23..eb6322c6f9 100644--- a/rust/cloud-storage/teams/Cargo.toml+++ b/rust/cloud-storage/teams/Cargo.toml@@ -24,6 +24,7 @@ axum = [default = ["ai_tools", "axum", "inbound", "outbound", "ports"]inbound = ["axum", "ports"]outbound = [+ "dep:analytics_client","dep:sqlx","dep:sqs_client","dep:models_email",@@ -77,6 +78,7 @@ model_notifications = { path = "../model_notifications", optional = true }notification = { path = "../notification", optional = true, default-features = false }# Outbound dependencies+analytics_client = { path = "../analytics_client", optional = true }sqlx = { workspace = true, optional = true }url = { workspace = true, optional = true }sqs_client = { path = "../sqs_client", default-features = false, features = [diff --git a/rust/cloud-storage/teams/src/domain.rs b/rust/cloud-storage/teams/src/domain.rsindex d53574023b..7e80140bc3 100644--- a/rust/cloud-storage/teams/src/domain.rs+++ b/rust/cloud-storage/teams/src/domain.rs@@ -1,6 +1,7 @@pub mod crm_enqueuer;pub mod customer_repo;pub mod model;+pub mod team_analytics;pub mod team_crm_settings_repo;pub mod team_repo;pub mod team_service;diff --git a/rust/cloud-storage/teams/src/domain/team_analytics.rs b/rust/cloud-storage/teams/src/domain/team_analytics.rsnew file mode 100644index 0000000000..89577b8a8a--- /dev/null+++ b/rust/cloud-storage/teams/src/domain/team_analytics.rs@@ -0,0 +1,79 @@+//! Outbound port for product analytics emitted by the teams domain.++#[cfg(test)]+mod test;++use macro_user_id::user_id::MacroUserIdStr;++use crate::domain::model::TeamRole;++/// Product analytics events emitted by team lifecycle operations.+#[derive(Clone, Debug, Eq, PartialEq)]+pub enum TeamAnalyticsEvent {+ /// A new team was created.+ TeamCreated {+ /// The id of the team that was created.+ team_id: uuid::Uuid,+ /// The macro user id of the user who owns the created team.+ owner_id: MacroUserIdStr<'static>,+ /// The name of the created team.+ team_name: String,+ },+ /// One user was invited to a team.+ TeamInvited {+ /// The id of the team that the user was invited to join.+ team_id: uuid::Uuid,+ /// The id of the team invite that was created.+ team_invite_id: uuid::Uuid,+ /// The macro user id of the user who created the invite.+ inviter_id: MacroUserIdStr<'static>,+ /// The team name, when it was available to the caller.+ team_name: Option<String>,+ },+ /// An invited user joined a team.+ TeamJoined {+ /// The id of the team that the user joined.+ team_id: uuid::Uuid,+ /// The id of the team invite that the user accepted.+ team_invite_id: uuid::Uuid,+ /// The macro user id of the user who joined the team.+ member_id: MacroUserIdStr<'static>,+ /// The role granted to the user who joined the team.+ role: TeamRole,+ },+ /// A member left or was removed from a team.+ TeamLeft {+ /// The id of the team that the user left.+ team_id: uuid::Uuid,+ /// The macro user id of the member who left the team.+ member_id: MacroUserIdStr<'static>,+ /// The macro user id of the user who removed the member.+ removed_by_id: MacroUserIdStr<'static>,+ /// The role the member had before leaving the team.+ role: TeamRole,+ },+}++/// Outbound port for recording team product analytics events.+pub trait TeamAnalytics: Clone + Send + Sync + 'static {+ /// Error type returned by the analytics implementation.+ type Err: std::fmt::Display + std::fmt::Debug + Send;++ /// Track one team analytics event.+ fn track_team_event(+ &self,+ event: TeamAnalyticsEvent,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+}++/// No-op team analytics implementation for callers without analytics wiring.+#[derive(Clone, Copy, Debug, Default)]+pub struct NoOpTeamAnalytics;++impl TeamAnalytics for NoOpTeamAnalytics {+ type Err = std::convert::Infallible;++ async fn track_team_event(&self, _event: TeamAnalyticsEvent) -> Result<(), Self::Err> {+ Ok(())+ }+}diff --git a/rust/cloud-storage/teams/src/domain/team_analytics/test.rs b/rust/cloud-storage/teams/src/domain/team_analytics/test.rsnew file mode 100644index 0000000000..e0eec2f218--- /dev/null+++ b/rust/cloud-storage/teams/src/domain/team_analytics/test.rs@@ -0,0 +1,44 @@+use macro_user_id::user_id::MacroUserIdStr;++use super::*;++fn macro_user_id(value: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(value.to_string()).expect("valid macro user id")+}++#[tokio::test]+async fn no_op_team_analytics_accepts_all_event_variants() {+ let analytics = NoOpTeamAnalytics;+ let team_id = uuid::Uuid::from_u128(1);+ let team_invite_id = uuid::Uuid::from_u128(2);++ let events = [+ TeamAnalyticsEvent::TeamCreated {+ team_id,+ owner_id: macro_user_id("macro|[email protected]"),+ team_name: "Acme".to_string(),+ },+ TeamAnalyticsEvent::TeamInvited {+ team_id,+ team_invite_id,+ inviter_id: macro_user_id("macro|[email protected]"),+ team_name: Some("Acme".to_string()),+ },+ TeamAnalyticsEvent::TeamJoined {+ team_id,+ team_invite_id,+ member_id: macro_user_id("macro|[email protected]"),+ role: TeamRole::Member,+ },+ TeamAnalyticsEvent::TeamLeft {+ team_id,+ member_id: macro_user_id("macro|[email protected]"),+ removed_by_id: macro_user_id("macro|[email protected]"),+ role: TeamRole::Member,+ },+ ];++ for event in events {+ analytics.track_team_event(event).await.unwrap();+ }+}diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rsindex 1857a8ee58..2590fd4d10 100644--- a/rust/cloud-storage/teams/src/domain/team_service.rs+++ b/rust/cloud-storage/teams/src/domain/team_service.rs@@ -31,13 +31,14 @@ use crate::domain::{RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,TeamMember, TeamMembers, TeamRole, TeamWithMembers,},+ team_analytics::{NoOpTeamAnalytics, TeamAnalytics, TeamAnalyticsEvent},team_crm_settings_repo::TeamCrmSettingsRepository,team_repo::{TeamChannelsRepository, TeamMembersService, TeamRepository, TeamService},};/// Implementation of the TeamService using a TeamRepository#[derive(Debug)]-pub struct TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>+pub struct TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA = NoOpTeamAnalytics>whereTR: TeamRepository,CR: CustomerRepository,@@ -46,6 +47,7 @@ whereNI: NotificationIngress,CE: CrmEnqueuer,TCRMS: TeamCrmSettingsRepository,+ TA: TeamAnalytics,{/// The underlying team repositoryteam_repository: TR,@@ -64,9 +66,12 @@ where/// Repository for the `team_crm_settings` row and the bulk CRM/// teardown invoked from `set_team_crm_enabled`.team_crm_settings_repository: TCRMS,+ /// Outbound port for best-effort team lifecycle analytics events.+ team_analytics: TA,}-impl<TR, CR, TCR, URPS, NI, CE, TCRMS> Clone for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA> Clone+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA>whereTR: TeamRepository,CR: CustomerRepository,@@ -75,6 +80,7 @@ whereNI: NotificationIngress,CE: CrmEnqueuer,TCRMS: TeamCrmSettingsRepository,+ TA: TeamAnalytics,{fn clone(&self) -> Self {Self {@@ -85,11 +91,13 @@ wherenotification_ingress: self.notification_ingress.clone(),crm_enqueuer: self.crm_enqueuer.clone(),team_crm_settings_repository: self.team_crm_settings_repository.clone(),+ team_analytics: self.team_analytics.clone(),}}}-impl<TR, CR, TCR, URPS, NI, CE, TCRMS> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS>+ TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, NoOpTeamAnalytics>whereTR: TeamRepository,CR: CustomerRepository,@@ -99,7 +107,7 @@ whereCE: CrmEnqueuer,TCRMS: TeamCrmSettingsRepository,{- /// Creates a new TeamService+ /// Creates a new TeamService with no-op analytics.pub fn new(team_repository: TR,customer_repository: CR,@@ -109,7 +117,7 @@ wherecrm_enqueuer: CE,team_crm_settings_repository: TCRMS,) -> Self {- Self {+ Self::new_with_analytics(team_repository,customer_repository,team_channels_repository,@@ -117,11 +125,12 @@ wherenotification_ingress,crm_enqueuer,team_crm_settings_repository,- }+ NoOpTeamAnalytics,+ )}}-impl<TR, CR, TCR, URPS, NI, CE, TCRMS> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA> TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA>whereTR: TeamRepository,CR: CustomerRepository,@@ -130,7 +139,48 @@ whereNI: NotificationIngress,CE: CrmEnqueuer,TCRMS: TeamCrmSettingsRepository,+ TA: TeamAnalytics,{+ /// Creates a new TeamService with an analytics implementation.+ #[allow(+ clippy::too_many_arguments,+ reason = "constructor mirrors TeamServiceImpl::new plus analytics port"+ )]+ pub fn new_with_analytics(+ team_repository: TR,+ customer_repository: CR,+ team_channels_repository: TCR,+ user_roles_and_permissions_service: URPS,+ notification_ingress: Arc<NI>,+ crm_enqueuer: CE,+ team_crm_settings_repository: TCRMS,+ team_analytics: TA,+ ) -> Self {+ Self {+ team_repository,+ customer_repository,+ team_channels_repository,+ user_roles_and_permissions_service,+ notification_ingress,+ crm_enqueuer,+ team_crm_settings_repository,+ team_analytics,+ }+ }++ async fn track_team_analytics_event(&self, event: TeamAnalyticsEvent) {+ self.team_analytics+ .track_team_event(event)+ .await+ .inspect_err(|error| {+ tracing::error!(+ error = ?error,+ "failed to track team analytics event"+ );+ })+ .ok();+ }+/// Gets the teams subscription id/// If the team doesn't have a subscription yet, it will convert the owners personal subscription into a team subscription#[tracing::instrument(skip(self), err)]@@ -297,8 +347,8 @@ impl GetTeamSubscriptionError {}}-impl<TR, CR, TCR, URPS, NI, CE, TCRMS> TeamMembersService- for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA> TeamMembersService+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA>whereTR: TeamRepository,CR: CustomerRepository,@@ -307,6 +357,7 @@ whereNI: NotificationIngress,CE: CrmEnqueuer,TCRMS: TeamCrmSettingsRepository,+ TA: TeamAnalytics,{#[tracing::instrument(skip(self), err)]async fn list_team_members(@@ -323,8 +374,8 @@ where}}-impl<TR, CR, TCR, URPS, NI, CE, TCRMS> TeamService- for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS>+impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA> TeamService+ for TeamServiceImpl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA>whereTR: TeamRepository,CR: CustomerRepository,@@ -333,6 +384,7 @@ whereNI: NotificationIngress,CE: CrmEnqueuer,TCRMS: TeamCrmSettingsRepository,+ TA: TeamAnalytics,{#[tracing::instrument(skip(self), err)]async fn create_team(@@ -357,6 +409,14 @@ whereself.team_repository.move_github_app_installation_to_team_if_exists(user_id, team.id()).await?;++ self.track_team_analytics_event(TeamAnalyticsEvent::TeamCreated {+ team_id: *team.id(),+ owner_id: user_id.clone().into_owned(),+ team_name: team.name().to_owned(),+ })+ .await;+Ok(team)}@@ -429,52 +489,73 @@ wherereturn Err(InviteUsersToTeamError::NotEnoughOpenSeats);}+ let new_invite_emails: HashSet<String> = new_invites+ .iter()+ .map(|email| email.as_ref().to_owned())+ .collect();+let invited = self.team_repository.invite_users_to_team(&team_id, invited_by, invites).await?;+ let team_name = if invited.is_empty() {+ None+ } else {+ self.team_repository.get_team_name(&team_id).await.ok()+ };+// Send notifications for new invites- if !invited.is_empty() {- let team_name = self.team_repository.get_team_name(&team_id).await.ok();-- if let Some(team_name) = team_name {- let invited_by_owned = invited_by.clone().into_owned();- let mut sent_invite_ids = Vec::new();- for invite in &invited {- if self- .send_invite_notification(- MacroUserIdStr::try_from_email(invite.email.as_ref())- .expect("this cannot fail"),- invite.team_invite_id,- InviteToTeamMetadata {- team_id,- team_invite_id: invite.team_invite_id,- invited_by: invited_by_owned.clone(),- team_name: team_name.clone(),- role: None,- sender_profile_picture_url: None,- },- )- .await- .inspect_err(- |e| tracing::error!(error=?e, "unable to send invite notification"),- )- .is_ok()- {- sent_invite_ids.push(invite.team_invite_id);- }- }- if !sent_invite_ids.is_empty() {- self.team_repository- .mark_invites_sent(&sent_invite_ids)- .await- .inspect_err(- |e| tracing::error!(error=?e, "unable to mark invites as sent"),- )- .ok();+ if !invited.is_empty()+ && let Some(team_name) = team_name.clone()+ {+ let invited_by_owned = invited_by.clone().into_owned();+ let mut sent_invite_ids = Vec::new();+ for invite in &invited {+ if self+ .send_invite_notification(+ MacroUserIdStr::try_from_email(invite.email.as_ref())+ .expect("this cannot fail"),+ invite.team_invite_id,+ InviteToTeamMetadata {+ team_id,+ team_invite_id: invite.team_invite_id,+ invited_by: invited_by_owned.clone(),+ team_name: team_name.clone(),+ role: None,+ sender_profile_picture_url: None,+ },+ )+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "unable to send invite notification"),+ )+ .is_ok()+ {+ sent_invite_ids.push(invite.team_invite_id);}}+ if !sent_invite_ids.is_empty() {+ self.team_repository+ .mark_invites_sent(&sent_invite_ids)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "unable to mark invites as sent"))+ .ok();+ }+ }++ for invite in &invited {+ if !new_invite_emails.contains(invite.email.as_ref()) {+ continue;+ }++ self.track_team_analytics_event(TeamAnalyticsEvent::TeamInvited {+ team_id,+ team_invite_id: invite.team_invite_id,+ inviter_id: invited_by.clone().into_owned(),+ team_name: team_name.clone(),+ })+ .await;}Ok(invited)@@ -488,6 +569,11 @@ where) -> Result<(), RemoveUserFromTeamError> {let team_id =macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();+ let removed_by_id = entity_access_receipt+ .get_authenticated_user()+ .map_err(|e| RemoveUserFromTeamError::TeamError(TeamError::AccessError(e)))?+ .clone()+ .into_owned();let removed_member = self.team_repository@@ -619,6 +705,14 @@ where);}+ self.track_team_analytics_event(TeamAnalyticsEvent::TeamLeft {+ team_id,+ member_id: removed_member.user_id.clone().into_owned(),+ removed_by_id,+ role: removed_member.role,+ })+ .await;+Ok(())}@@ -890,6 +984,14 @@ where);}+ self.track_team_analytics_event(TeamAnalyticsEvent::TeamJoined {+ team_id: team_member.team_id,+ team_invite_id: accepted_invite.invite.id,+ member_id: team_member.user_id.clone().into_owned(),+ role: team_member.role,+ })+ .await;+Ok(team_member)}diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rsindex b57ae99c72..9aeafdc506 100644--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs@@ -21,7 +21,9 @@ use roles_and_permissions::domain::{};use crate::domain::{- crm_enqueuer::NoOpCrmEnqueuer, team_crm_settings_repo::NoOpTeamCrmSettingsRepository,+ crm_enqueuer::NoOpCrmEnqueuer,+ team_analytics::{TeamAnalytics, TeamAnalyticsEvent},+ team_crm_settings_repo::NoOpTeamCrmSettingsRepository,};fn test_team_receipt<T: RequiredPermission>(@@ -71,6 +73,7 @@ struct MockTeamRepository {subscription_update_calls: Arc<Mutex<Vec<(uuid::Uuid, String)>>>,payment_update_calls: Arc<Mutex<Vec<(uuid::Uuid, bool)>>>,fail_github_installation_move: bool,+ fail_invite_users_to_team: bool,}impl MockTeamRepository {@@ -108,6 +111,7 @@ impl MockTeamRepository {subscription_update_calls: Arc::new(Mutex::new(Vec::new())),payment_update_calls: Arc::new(Mutex::new(Vec::new())),fail_github_installation_move: false,+ fail_invite_users_to_team: false,}}@@ -192,7 +196,16 @@ impl TeamRepository for MockTeamRepository {_: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send {let invites = self.invites_to_return.clone();- async move { Ok(invites) }+ let fail = self.fail_invite_users_to_team;+ async move {+ if fail {+ Err(InviteUsersToTeamError::StorageLayerError(anyhow::anyhow!(+ "invite failed"+ )))+ } else {+ Ok(invites)+ }+ }}fn get_new_invites(@@ -743,6 +756,46 @@ impl NotificationIngress for MockNotificationIngress {}}+// -- Mock TeamAnalytics --++#[derive(Clone)]+struct MockTeamAnalytics {+ events: Arc<Mutex<Vec<TeamAnalyticsEvent>>>,+ fail: bool,+}++impl MockTeamAnalytics {+ fn new(events: Arc<Mutex<Vec<TeamAnalyticsEvent>>>) -> Self {+ Self {+ events,+ fail: false,+ }+ }++ fn failing(events: Arc<Mutex<Vec<TeamAnalyticsEvent>>>) -> Self {+ Self { events, fail: true }+ }+}++impl TeamAnalytics for MockTeamAnalytics {+ type Err = String;++ fn track_team_event(+ &self,+ event: TeamAnalyticsEvent,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send {+ self.events.lock().unwrap().push(event);+ let fail = self.fail;+ async move {+ if fail {+ Err("analytics failed".to_string())+ } else {+ Ok(())+ }+ }+ }+}+// -- Helpers --fn make_invite(email: &str, invite_id: uuid::Uuid, team_id: uuid::Uuid) -> TeamInvite<'static> {@@ -803,6 +856,25 @@ fn build_service((service, notification_ingress)}+fn build_service_with_analytics(+ team_repo: MockTeamRepository,+ customer_repo: MockCustomerRepository,+ channels_repo: MockTeamChannelsRepository,+ roles_service: MockUserRolesAndPermissionsService,+ team_analytics: MockTeamAnalytics,+) -> impl TeamService {+ TeamServiceImpl::new_with_analytics(+ team_repo,+ customer_repo,+ channels_repo,+ roles_service,+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ team_analytics,+ )+}+// -- Tests --#[tokio::test]@@ -879,6 +951,114 @@ async fn test_create_team_propagates_github_installation_move_failure() {);}+#[tokio::test]+async fn team_analytics_create_team_emits_created_event_with_team_id() {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team_id = uuid::Uuid::from_u128(2100);+ let team = Team::new(+ team_id,+ "Analytics Team".to_string(),+ "ANALYTICS_TEAM".to_string(),+ user_id.clone().into_owned(),+ );+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);+ team_repo.created_team = team;++ let events = Arc::new(Mutex::new(Vec::new()));+ let service = build_service_with_analytics(+ team_repo,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ MockTeamAnalytics::new(events.clone()),+ );++ service+ .create_team(&user_id, "Analytics Team", &"sub_test".parse().unwrap())+ .await+ .unwrap();++ let events = events.lock().unwrap();+ assert_eq!(events.len(), 1);+ match &events[0] {+ TeamAnalyticsEvent::TeamCreated {+ team_id: event_team_id,+ owner_id,+ team_name,+ } => {+ assert_eq!(*event_team_id, team_id);+ assert_eq!(owner_id.as_ref(), user_id.as_ref());+ assert_eq!(team_name, "Analytics Team");+ }+ event => panic!("unexpected event: {event:?}"),+ }+}++#[tokio::test]+async fn team_analytics_failure_is_swallowed_by_create_team() {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team_id = uuid::Uuid::from_u128(2101);+ let team = Team::new(+ team_id,+ "Analytics Team".to_string(),+ "ANALYTICS_TEAM".to_string(),+ user_id.clone().into_owned(),+ );+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);+ team_repo.created_team = team;++ let events = Arc::new(Mutex::new(Vec::new()));+ let service = build_service_with_analytics(+ team_repo,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ MockTeamAnalytics::failing(events.clone()),+ );++ let result = service+ .create_team(&user_id, "Analytics Team", &"sub_test".parse().unwrap())+ .await;++ assert!(result.is_ok());+ assert_eq!(events.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn team_analytics_create_team_does_not_emit_when_side_effect_fails() {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team = Team::new(+ uuid::Uuid::from_u128(2102),+ "Analytics Team".to_string(),+ "ANALYTICS_TEAM".to_string(),+ user_id.clone().into_owned(),+ );+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);+ team_repo.created_team = team;+ team_repo.fail_github_installation_move = true;++ let events = Arc::new(Mutex::new(Vec::new()));+ let service = build_service_with_analytics(+ team_repo,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ MockTeamAnalytics::new(events.clone()),+ );++ let err = service+ .create_team(&user_id, "Analytics Team", &"sub_test".parse().unwrap())+ .await+ .err()+ .unwrap();++ assert!(matches!(err, CreateTeamError::StorageLayerError(_)));+ assert!(events.lock().unwrap().is_empty());+}+fn build_service_for_premium_check(stripe_customer_id: Option<stripe::CustomerId>,no_active_subscription: bool,@@ -1057,6 +1237,102 @@ async fn test_invite_marks_all_sent_when_all_notifications_succeed() {assert!(marked_ids.contains(&invite_id_2));}+#[tokio::test]+async fn team_analytics_invite_users_emits_invited_events_with_team_id() {+ let team_id = uuid::Uuid::from_u128(310);+ let invite_id_1 = uuid::Uuid::from_u128(311);+ let invite_id_2 = uuid::Uuid::from_u128(312);+ let invites_to_return = vec![+ make_invite("[email protected]", invite_id_1, team_id),+ make_invite("[email protected]", invite_id_2, team_id),+ ];+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));+ let team_repo = MockTeamRepository::new(invites_to_return, "Test Team", mark_sent_calls);+ let events = Arc::new(Mutex::new(Vec::new()));+ let service = build_service_with_analytics(+ team_repo,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ MockTeamAnalytics::new(events.clone()),+ );++ let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let invites = vec![+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ ];+ let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();+ let receipt = test_team_receipt::<AdminTeamRole>(team_id, &invited_by);++ service+ .invite_users_to_team(receipt, invites)+ .await+ .unwrap();++ let events = events.lock().unwrap();+ assert_eq!(events.len(), 2);+ for (event, expected_invite_id) in events.iter().zip([invite_id_1, invite_id_2]) {+ match event {+ TeamAnalyticsEvent::TeamInvited {+ team_id: event_team_id,+ team_invite_id,+ inviter_id,+ team_name,+ } => {+ assert_eq!(*event_team_id, team_id);+ assert_eq!(*team_invite_id, expected_invite_id);+ assert_eq!(inviter_id.as_ref(), invited_by.as_ref());+ assert_eq!(team_name.as_deref(), Some("Test Team"));+ }+ event => panic!("unexpected event: {event:?}"),+ }+ }+}++#[tokio::test]+async fn team_analytics_invite_users_does_not_emit_when_invite_creation_fails() {+ let team_id = uuid::Uuid::from_u128(313);+ let invite_id = uuid::Uuid::from_u128(314);+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(+ vec![make_invite("[email protected]", invite_id, team_id)],+ "Test Team",+ mark_sent_calls,+ );+ team_repo.fail_invite_users_to_team = true;+ let events = Arc::new(Mutex::new(Vec::new()));+ let service = build_service_with_analytics(+ team_repo,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ MockTeamAnalytics::new(events.clone()),+ );++ let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let invites = vec![+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ ];+ let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();+ let receipt = test_team_receipt::<AdminTeamRole>(team_id, &invited_by);++ let err = service+ .invite_users_to_team(receipt, invites)+ .await+ .err()+ .unwrap();++ assert!(matches!(err, InviteUsersToTeamError::StorageLayerError(_)));+ assert!(events.lock().unwrap().is_empty());+}+fn build_service_with_team(team: Team,) -> (@@ -1467,6 +1743,50 @@ async fn test_join_team_increments_customer_seat_count() {assert_eq!(upsert_role_calls.lock().unwrap().len(), 1);}+#[tokio::test]+async fn team_analytics_join_team_emits_joined_event_with_team_id() {+ let team_id = uuid::Uuid::from_u128(321);+ let invite_id = uuid::Uuid::from_u128(322);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));++ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);+ team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));+ team_repo.team_subscription_id = Some(subscription_id.clone());+ let customer_repo = MockCustomerRepository {+ subscription_id,+ ..Default::default()+ };+ let events = Arc::new(Mutex::new(Vec::new()));+ let service = build_service_with_analytics(+ team_repo,+ customer_repo,+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ MockTeamAnalytics::new(events.clone()),+ );++ service.join_team(&invite_id, &user_id).await.unwrap();++ let events = events.lock().unwrap();+ assert_eq!(events.len(), 1);+ match &events[0] {+ TeamAnalyticsEvent::TeamJoined {+ team_id: event_team_id,+ team_invite_id,+ member_id,+ role,+ } => {+ assert_eq!(*event_team_id, team_id);+ assert_eq!(*team_invite_id, invite_id);+ assert_eq!(member_id.as_ref(), user_id.as_ref());+ assert_eq!(*role, TeamRole::Member);+ }+ event => panic!("unexpected event: {event:?}"),+ }+}+#[tokio::test]async fn test_join_team_rolls_back_accept_when_customer_increment_fails() {let team_id = uuid::Uuid::from_u128(1);@@ -1573,6 +1893,60 @@ async fn test_remove_user_from_team_decrements_customer_seat_count() {assert_eq!(remove_role_calls.lock().unwrap().len(), 1);}+#[tokio::test]+async fn team_analytics_remove_user_from_team_emits_left_event_with_team_id() {+ let team_id = uuid::Uuid::from_u128(331);+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let member_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));++ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);+ team_repo.removed_member = Some(TeamMember {+ team_id,+ user_id: member_id.clone().into_owned(),+ role: TeamRole::Admin,+ });+ team_repo.team_subscription_id = Some(subscription_id.clone());+ let customer_repo = MockCustomerRepository {+ subscription_id,+ ..Default::default()+ };+ let events = Arc::new(Mutex::new(Vec::new()));+ let service = build_service_with_analytics(+ team_repo,+ customer_repo,+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ MockTeamAnalytics::new(events.clone()),+ );++ service+ .remove_user_from_team(+ test_team_receipt::<AdminTeamRole>(team_id, &owner_id),+ &member_id,+ )+ .await+ .unwrap();++ let events = events.lock().unwrap();+ assert_eq!(events.len(), 1);+ match &events[0] {+ TeamAnalyticsEvent::TeamLeft {+ team_id: event_team_id,+ member_id: event_member_id,+ removed_by_id,+ role,+ } => {+ assert_eq!(*event_team_id, team_id);+ assert_eq!(event_member_id.as_ref(), member_id.as_ref());+ assert_eq!(removed_by_id.as_ref(), owner_id.as_ref());+ assert_eq!(*role, TeamRole::Admin);+ }+ event => panic!("unexpected event: {event:?}"),+ }+}+#[tokio::test]async fn test_remove_user_from_team_rolls_back_remove_when_customer_decrement_fails() {let team_id = uuid::Uuid::from_u128(1);@@ -1683,6 +2057,40 @@ async fn test_join_team_rolls_back_customer_roles_and_accept_when_channel_add_faassert_eq!(remove_role_calls.lock().unwrap().len(), 1);}+#[tokio::test]+async fn team_analytics_join_team_does_not_emit_when_join_is_rolled_back() {+ let team_id = uuid::Uuid::from_u128(323);+ let invite_id = uuid::Uuid::from_u128(324);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));++ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);+ team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));+ team_repo.team_subscription_id = Some(subscription_id.clone());+ let customer_repo = MockCustomerRepository {+ subscription_id,+ ..Default::default()+ };+ let channels_repo = MockTeamChannelsRepository {+ fail_add: true,+ ..Default::default()+ };+ let events = Arc::new(Mutex::new(Vec::new()));+ let service = build_service_with_analytics(+ team_repo,+ customer_repo,+ channels_repo,+ MockUserRolesAndPermissionsService::default(),+ MockTeamAnalytics::new(events.clone()),+ );++ let err = service.join_team(&invite_id, &user_id).await.err().unwrap();++ assert!(matches!(err, JoinTeamError::TeamError(_)));+ assert!(events.lock().unwrap().is_empty());+}+#[tokio::test]async fn test_remove_user_from_team_rolls_back_customer_and_remove_when_channel_remove_fails() {let team_id = uuid::Uuid::from_u128(1);@@ -1744,3 +2152,48 @@ async fn test_remove_user_from_team_rolls_back_customer_and_remove_when_channel_assert_eq!(*rollback_remove_calls.lock().unwrap(), 1);assert!(remove_role_calls.lock().unwrap().is_empty());}++#[tokio::test]+async fn team_analytics_remove_user_from_team_does_not_emit_when_remove_is_rolled_back() {+ let team_id = uuid::Uuid::from_u128(332);+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let member_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));++ let mut team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls);+ team_repo.removed_member = Some(TeamMember {+ team_id,+ user_id: member_id.clone().into_owned(),+ role: TeamRole::Member,+ });+ team_repo.team_subscription_id = Some(subscription_id.clone());+ let customer_repo = MockCustomerRepository {+ subscription_id,+ ..Default::default()+ };+ let channels_repo = MockTeamChannelsRepository {+ fail_remove: true,+ ..Default::default()+ };+ let events = Arc::new(Mutex::new(Vec::new()));+ let service = build_service_with_analytics(+ team_repo,+ customer_repo,+ channels_repo,+ MockUserRolesAndPermissionsService::default(),+ MockTeamAnalytics::new(events.clone()),+ );++ let err = service+ .remove_user_from_team(+ test_team_receipt::<AdminTeamRole>(team_id, &owner_id),+ &member_id,+ )+ .await+ .err()+ .unwrap();++ assert!(matches!(err, RemoveUserFromTeamError::TeamError(_)));+ assert!(events.lock().unwrap().is_empty());+}diff --git a/rust/cloud-storage/teams/src/outbound.rs b/rust/cloud-storage/teams/src/outbound.rsindex 42006c938d..111fddf5a9 100644--- a/rust/cloud-storage/teams/src/outbound.rs+++ b/rust/cloud-storage/teams/src/outbound.rs@@ -1,5 +1,6 @@pub mod crm_enqueuer;pub mod customer_repo;+pub mod team_analytics;pub mod team_channels_repo;pub mod team_crm_settings_repo;pub mod team_repo;diff --git a/rust/cloud-storage/teams/src/outbound/team_analytics.rs b/rust/cloud-storage/teams/src/outbound/team_analytics.rsnew file mode 100644index 0000000000..0450f6343e--- /dev/null+++ b/rust/cloud-storage/teams/src/outbound/team_analytics.rs@@ -0,0 +1,148 @@+//! [`TeamAnalytics`] adapter backed by `analytics_client::AnalyticsClient`.++#[cfg(test)]+mod test;++use std::sync::Arc;++use analytics_client::AnalyticsClient;+use serde::Serialize;++use crate::domain::team_analytics::{TeamAnalytics, TeamAnalyticsEvent};++/// Team analytics adapter that records events through the shared analytics client.+#[derive(Clone)]+pub struct AnalyticsClientTeamAnalytics {+ client: Arc<AnalyticsClient>,+}++impl AnalyticsClientTeamAnalytics {+ /// Construct a new team analytics adapter from a shared analytics client.+ pub fn new(client: Arc<AnalyticsClient>) -> Self {+ Self { client }+ }+}++#[derive(Debug, Eq, PartialEq, Serialize)]+struct TeamAnalyticsProperties {+ team_id: uuid::Uuid,+ #[serde(skip_serializing_if = "Option::is_none")]+ team_name: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ team_invite_id: Option<uuid::Uuid>,+ #[serde(skip_serializing_if = "Option::is_none")]+ owner_id: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ inviter_id: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ member_id: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ removed_by_id: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ role: Option<String>,+}++impl TeamAnalyticsProperties {+ fn new(team_id: uuid::Uuid) -> Self {+ Self {+ team_id,+ team_name: None,+ team_invite_id: None,+ owner_id: None,+ inviter_id: None,+ member_id: None,+ removed_by_id: None,+ role: None,+ }+ }+}++#[derive(Debug, Eq, PartialEq)]+struct PostHogTeamAnalyticsEvent {+ distinct_id: String,+ event_name: &'static str,+ properties: TeamAnalyticsProperties,+}++impl PostHogTeamAnalyticsEvent {+ fn from_team_event(event: TeamAnalyticsEvent) -> Self {+ match event {+ TeamAnalyticsEvent::TeamCreated {+ team_id,+ owner_id,+ team_name,+ } => Self {+ distinct_id: owner_id.as_ref().to_owned(),+ event_name: "team_create",+ properties: TeamAnalyticsProperties {+ team_name: Some(team_name),+ owner_id: Some(owner_id.as_ref().to_owned()),+ ..TeamAnalyticsProperties::new(team_id)+ },+ },+ TeamAnalyticsEvent::TeamInvited {+ team_id,+ team_invite_id,+ inviter_id,+ team_name,+ } => Self {+ distinct_id: inviter_id.as_ref().to_owned(),+ event_name: "team_invite",+ properties: TeamAnalyticsProperties {+ team_name,+ team_invite_id: Some(team_invite_id),+ inviter_id: Some(inviter_id.as_ref().to_owned()),+ ..TeamAnalyticsProperties::new(team_id)+ },+ },+ TeamAnalyticsEvent::TeamJoined {+ team_id,+ team_invite_id,+ member_id,+ role,+ } => Self {+ distinct_id: member_id.as_ref().to_owned(),+ event_name: "team_join",+ properties: TeamAnalyticsProperties {+ team_invite_id: Some(team_invite_id),+ member_id: Some(member_id.as_ref().to_owned()),+ role: Some(role.to_string()),+ ..TeamAnalyticsProperties::new(team_id)+ },+ },+ TeamAnalyticsEvent::TeamLeft {+ team_id,+ member_id,+ removed_by_id,+ role,+ } => Self {+ distinct_id: member_id.as_ref().to_owned(),+ event_name: "team_leave",+ properties: TeamAnalyticsProperties {+ member_id: Some(member_id.as_ref().to_owned()),+ removed_by_id: Some(removed_by_id.as_ref().to_owned()),+ role: Some(role.to_string()),+ ..TeamAnalyticsProperties::new(team_id)+ },+ },+ }+ }+}++impl TeamAnalytics for AnalyticsClientTeamAnalytics {+ type Err = String;++ async fn track_team_event(&self, event: TeamAnalyticsEvent) -> Result<(), Self::Err> {+ let posthog_event = PostHogTeamAnalyticsEvent::from_team_event(event);+ let event_name = posthog_event.event_name;++ self.client+ .track_posthog(+ &posthog_event.distinct_id,+ event_name,+ &posthog_event.properties,+ )+ .await+ .map_err(|err| format!("failed to track PostHog team event {event_name}: {err}"))+ }+}diff --git a/rust/cloud-storage/teams/src/outbound/team_analytics/test.rs b/rust/cloud-storage/teams/src/outbound/team_analytics/test.rsnew file mode 100644index 0000000000..a0594617fb--- /dev/null+++ b/rust/cloud-storage/teams/src/outbound/team_analytics/test.rs@@ -0,0 +1,168 @@+use std::sync::Arc;++use macro_user_id::user_id::MacroUserIdStr;+use serde_json::json;++use super::*;+use crate::domain::model::TeamRole;++fn macro_user_id(value: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(value.to_string()).expect("valid macro user id")+}++fn test_events() -> Vec<TeamAnalyticsEvent> {+ let team_id = uuid::Uuid::from_u128(1);+ let team_invite_id = uuid::Uuid::from_u128(2);++ vec![+ TeamAnalyticsEvent::TeamCreated {+ team_id,+ owner_id: macro_user_id("macro|[email protected]"),+ team_name: "Acme".to_string(),+ },+ TeamAnalyticsEvent::TeamInvited {+ team_id,+ team_invite_id,+ inviter_id: macro_user_id("macro|[email protected]"),+ team_name: Some("Acme".to_string()),+ },+ TeamAnalyticsEvent::TeamJoined {+ team_id,+ team_invite_id,+ member_id: macro_user_id("macro|[email protected]"),+ role: TeamRole::Member,+ },+ TeamAnalyticsEvent::TeamLeft {+ team_id,+ member_id: macro_user_id("macro|[email protected]"),+ removed_by_id: macro_user_id("macro|[email protected]"),+ role: TeamRole::Admin,+ },+ ]+}++#[test]+fn maps_team_events_to_expected_posthog_names() {+ let expected_names = ["team_create", "team_invite", "team_join", "team_leave"];++ for (event, expected_name) in test_events().into_iter().zip(expected_names) {+ let posthog_event = PostHogTeamAnalyticsEvent::from_team_event(event);++ assert_eq!(posthog_event.event_name, expected_name);+ }+}++#[test]+fn mapped_team_events_include_team_id_in_properties() {+ let team_id = uuid::Uuid::from_u128(1).to_string();++ for event in test_events() {+ let posthog_event = PostHogTeamAnalyticsEvent::from_team_event(event);+ let properties = serde_json::to_value(&posthog_event.properties).unwrap();++ assert_eq!(properties["team_id"], team_id);+ }+}++#[test]+fn maps_team_created_context() {+ let posthog_event =+ PostHogTeamAnalyticsEvent::from_team_event(TeamAnalyticsEvent::TeamCreated {+ team_id: uuid::Uuid::from_u128(1),+ owner_id: macro_user_id("macro|[email protected]"),+ team_name: "Acme".to_string(),+ });+ let properties = serde_json::to_value(&posthog_event.properties).unwrap();++ assert_eq!(posthog_event.distinct_id, "macro|[email protected]");+ assert_eq!(+ properties,+ json!({+ "team_id": uuid::Uuid::from_u128(1),+ "team_name": "Acme",+ "owner_id": "macro|[email protected]",+ })+ );+}++#[test]+fn maps_team_invited_context() {+ let posthog_event =+ PostHogTeamAnalyticsEvent::from_team_event(TeamAnalyticsEvent::TeamInvited {+ team_id: uuid::Uuid::from_u128(1),+ team_invite_id: uuid::Uuid::from_u128(2),+ inviter_id: macro_user_id("macro|[email protected]"),+ team_name: Some("Acme".to_string()),+ });+ let properties = serde_json::to_value(&posthog_event.properties).unwrap();++ assert_eq!(posthog_event.distinct_id, "macro|[email protected]");+ assert_eq!(+ properties,+ json!({+ "team_id": uuid::Uuid::from_u128(1),+ "team_name": "Acme",+ "team_invite_id": uuid::Uuid::from_u128(2),+ "inviter_id": "macro|[email protected]",+ })+ );+}++#[test]+fn maps_team_joined_context() {+ let posthog_event =+ PostHogTeamAnalyticsEvent::from_team_event(TeamAnalyticsEvent::TeamJoined {+ team_id: uuid::Uuid::from_u128(1),+ team_invite_id: uuid::Uuid::from_u128(2),+ member_id: macro_user_id("macro|[email protected]"),+ role: TeamRole::Member,+ });+ let properties = serde_json::to_value(&posthog_event.properties).unwrap();++ assert_eq!(posthog_event.distinct_id, "macro|[email protected]");+ assert_eq!(+ properties,+ json!({+ "team_id": uuid::Uuid::from_u128(1),+ "team_invite_id": uuid::Uuid::from_u128(2),+ "member_id": "macro|[email protected]",+ "role": "member",+ })+ );+}++#[test]+fn maps_team_left_context() {+ let posthog_event = PostHogTeamAnalyticsEvent::from_team_event(TeamAnalyticsEvent::TeamLeft {+ team_id: uuid::Uuid::from_u128(1),+ member_id: macro_user_id("macro|[email protected]"),+ removed_by_id: macro_user_id("macro|[email protected]"),+ role: TeamRole::Admin,+ });+ let properties = serde_json::to_value(&posthog_event.properties).unwrap();++ assert_eq!(posthog_event.distinct_id, "macro|[email protected]");+ assert_eq!(+ properties,+ json!({+ "team_id": uuid::Uuid::from_u128(1),+ "member_id": "macro|[email protected]",+ "removed_by_id": "macro|[email protected]",+ "role": "admin",+ })+ );+}++#[tokio::test]+async fn noop_analytics_client_adapter_returns_ok() {+ let analytics = AnalyticsClientTeamAnalytics::new(Arc::new(AnalyticsClient::noop()));++ analytics+ .track_team_event(TeamAnalyticsEvent::TeamCreated {+ team_id: uuid::Uuid::from_u128(1),+ owner_id: macro_user_id("macro|[email protected]"),+ team_name: "Acme".to_string(),+ })+ .await+ .unwrap();+}