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): move github app installation to team on team creation (#3712)
Will Hutchinsoncc5210c820f1
diff --git a/rust/cloud-storage/.sqlx/query-d8677557689260c205fa17b9b36990834ea8846624132386f2fcd92d0d9b9905.json b/rust/cloud-storage/.sqlx/query-d8677557689260c205fa17b9b36990834ea8846624132386f2fcd92d0d9b9905.jsonnew file mode 100644index 0000000000..bbc7330bb2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-d8677557689260c205fa17b9b36990834ea8846624132386f2fcd92d0d9b9905.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE github_app_installation\n SET source_id = $2::text,\n source_type = 'team'::github_app_installation_source_type\n WHERE source_id = $1\n AND source_type = 'user'::github_app_installation_source_type\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "d8677557689260c205fa17b9b36990834ea8846624132386f2fcd92d0d9b9905"+}diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rsindex d38da61332..2a4d5e4aa5 100644--- a/rust/cloud-storage/teams/src/domain/team_repo.rs+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs@@ -64,6 +64,13 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {team_name: &str,) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;+ /// Moves any user-owned GitHub App installation rows to the given team.+ fn move_github_app_installation_to_team_if_exists(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<(), CreateTeamError>> + Send;+/// Invites users to a team./// This will also handle the teams subscription./// Returns the number of users invited.diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rsindex dd7bfa67ea..324bbb0878 100644--- a/rust/cloud-storage/teams/src/domain/team_service.rs+++ b/rust/cloud-storage/teams/src/domain/team_service.rs@@ -290,7 +290,11 @@ where// for the email-backfill fan-out to populate yet. The fan-out// happens later, on the disabled → enabled transition in// `set_team_crm_enabled`.- self.team_repository.create_team(user_id, team_name).await+ let team = self.team_repository.create_team(user_id, team_name).await?;+ self.team_repository+ .move_github_app_installation_to_team_if_exists(user_id, team.id())+ .await?;+ Ok(team)}#[tracing::instrument(skip(self), err)]diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rsindex d68ef5fe1a..37c5ba41c9 100644--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs@@ -65,6 +65,9 @@ struct MockTeamRepository {fail_rollback_remove: bool,patch_team_user_role_calls: Arc<Mutex<Vec<(uuid::Uuid, String, TeamRole)>>>,patch_team_name_calls: Arc<Mutex<Vec<(uuid::Uuid, Option<String>, Option<String>)>>>,+ created_team: Team,+ github_installation_move_calls: Arc<Mutex<Vec<(String, uuid::Uuid)>>>,+ fail_github_installation_move: bool,}impl MockTeamRepository {@@ -89,6 +92,16 @@ impl MockTeamRepository {fail_rollback_remove: false,patch_team_user_role_calls: Arc::new(Mutex::new(Vec::new())),patch_team_name_calls: Arc::new(Mutex::new(Vec::new())),+ created_team: Team::new(+ uuid::Uuid::from_u128(1000),+ "Created Team".to_string(),+ "CREATED_TEAM".to_string(),+ MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned(),+ ),+ github_installation_move_calls: Arc::new(Mutex::new(Vec::new())),+ fail_github_installation_move: false,}}@@ -135,7 +148,29 @@ impl TeamRepository for MockTeamRepository {_: &MacroUserIdStr<'_>,_: &str,) -> impl Future<Output = Result<Team, CreateTeamError>> + Send {- async { unimplemented!() }+ let team = self.created_team.clone();+ async move { Ok(team) }+ }++ fn move_github_app_installation_to_team_if_exists(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<(), CreateTeamError>> + Send {+ self.github_installation_move_calls+ .lock()+ .unwrap()+ .push((user_id.as_ref().to_string(), *team_id));+ let fail = self.fail_github_installation_move;+ async move {+ if fail {+ Err(CreateTeamError::StorageLayerError(anyhow::anyhow!(+ "github installation move failed"+ )))+ } else {+ Ok(())+ }+ }}fn invite_users_to_team(@@ -733,6 +768,77 @@ fn build_service(// -- Tests --+#[tokio::test]+async fn test_create_team_moves_github_installation_to_created_team() {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team = Team::new(+ uuid::Uuid::from_u128(2000),+ "New Team".to_string(),+ "NEW_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.clone();+ let move_calls = team_repo.github_installation_move_calls.clone();++ let service = TeamServiceImpl::new(+ team_repo,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let created_team = service.create_team(&user_id, "New Team").await.unwrap();++ assert_eq!(created_team.id(), team.id());+ assert_eq!(+ *move_calls.lock().unwrap(),+ vec![(user_id.as_ref().to_string(), *team.id())]+ );+}++#[tokio::test]+async fn test_create_team_propagates_github_installation_move_failure() {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team = Team::new(+ uuid::Uuid::from_u128(2001),+ "New Team".to_string(),+ "NEW_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.clone();+ team_repo.fail_github_installation_move = true;+ let move_calls = team_repo.github_installation_move_calls.clone();++ let service = TeamServiceImpl::new(+ team_repo,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let err = service+ .create_team(&user_id, "New Team")+ .await+ .err()+ .unwrap();++ assert!(matches!(err, CreateTeamError::StorageLayerError(_)));+ assert_eq!(+ *move_calls.lock().unwrap(),+ vec![(user_id.as_ref().to_string(), *team.id())]+ );+}+/// When one notification fails, only the successful invite IDs are passed to/// mark_invites_sent.#[tokio::test]diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rsindex 4fdb29d7df..2c86fffb54 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs@@ -354,6 +354,29 @@ impl TeamRepository for TeamRepositoryImpl {.map_err(|e| e.into())}+ #[tracing::instrument(skip(self), err)]+ async fn move_github_app_installation_to_team_if_exists(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: &uuid::Uuid,+ ) -> Result<(), CreateTeamError> {+ sqlx::query!(+ r#"+ UPDATE github_app_installation+ SET source_id = $2::text,+ source_type = 'team'::github_app_installation_source_type+ WHERE source_id = $1+ AND source_type = 'user'::github_app_installation_source_type+ "#,+ user_id.as_ref(),+ team_id.to_string(),+ )+ .execute(&self.pool)+ .await?;++ Ok(())+ }+#[tracing::instrument(skip(self), err)]async fn invite_users_to_team(&self,diff --git a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs b/rust/cloud-storage/teams/src/outbound/team_repo/test.rsindex e9bda3013f..43b200fe4c 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs@@ -159,6 +159,187 @@ async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {Ok(())}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_move_github_app_installation_to_team_moves_existing_user_rows(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let unrelated_user_id = "macro|[email protected]";+ let existing_team_id = "22222222-2222-2222-2222-222222222222";++ sqlx::query(+ r#"+ INSERT INTO github_app_installation (id, source_id, source_type)+ VALUES+ ('installation-one', $1, 'user'::github_app_installation_source_type),+ ('installation-two', $1, 'user'::github_app_installation_source_type),+ ('other-user-installation', $2, 'user'::github_app_installation_source_type),+ ('existing-team-installation', $3, 'team'::github_app_installation_source_type)+ "#,+ )+ .bind(user_id.as_ref())+ .bind(unrelated_user_id)+ .bind(existing_team_id)+ .execute(&pool)+ .await?;++ let team = team_repo.create_team(&user_id, "GitHub Owner Team").await?;+ let team_id = team.id().to_string();++ team_repo+ .move_github_app_installation_to_team_if_exists(&user_id, team.id())+ .await?;++ let remaining_user_row_count = sqlx::query(+ r#"+ SELECT COUNT(*) AS count+ FROM github_app_installation+ WHERE source_id = $1+ AND source_type = 'user'::github_app_installation_source_type+ "#,+ )+ .bind(user_id.as_ref())+ .fetch_one(&pool)+ .await?+ .try_get::<i64, _>("count")?;+ assert_eq!(remaining_user_row_count, 0);++ let moved_rows = sqlx::query(+ r#"+ SELECT id, source_id, source_type::text AS source_type+ FROM github_app_installation+ WHERE source_id = $1+ AND source_type = 'team'::github_app_installation_source_type+ ORDER BY id+ "#,+ )+ .bind(&team_id)+ .fetch_all(&pool)+ .await?+ .into_iter()+ .map(|row| {+ Ok((+ row.try_get::<String, _>("id")?,+ row.try_get::<String, _>("source_id")?,+ row.try_get::<String, _>("source_type")?,+ ))+ })+ .collect::<Result<Vec<_>, sqlx::Error>>()?;++ assert_eq!(+ moved_rows,+ vec![+ (+ "installation-one".to_string(),+ team_id.clone(),+ "team".to_string()+ ),+ ("installation-two".to_string(), team_id, "team".to_string()),+ ]+ );++ let unrelated_rows = sqlx::query(+ r#"+ SELECT id, source_id, source_type::text AS source_type+ FROM github_app_installation+ WHERE id IN ('existing-team-installation', 'other-user-installation')+ ORDER BY id+ "#,+ )+ .fetch_all(&pool)+ .await?+ .into_iter()+ .map(|row| {+ Ok((+ row.try_get::<String, _>("id")?,+ row.try_get::<String, _>("source_id")?,+ row.try_get::<String, _>("source_type")?,+ ))+ })+ .collect::<Result<Vec<_>, sqlx::Error>>()?;++ assert_eq!(+ unrelated_rows,+ vec![+ (+ "existing-team-installation".to_string(),+ existing_team_id.to_string(),+ "team".to_string()+ ),+ (+ "other-user-installation".to_string(),+ unrelated_user_id.to_string(),+ "user".to_string()+ ),+ ]+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_move_github_app_installation_to_team_noops_when_user_has_no_rows(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let unrelated_user_id = "macro|[email protected]";++ sqlx::query(+ r#"+ INSERT INTO github_app_installation (id, source_id, source_type)+ VALUES ('other-user-installation', $1, 'user'::github_app_installation_source_type)+ "#,+ )+ .bind(unrelated_user_id)+ .execute(&pool)+ .await?;++ let team = team_repo.create_team(&user_id, "GitHub Owner Team").await?;++ team_repo+ .move_github_app_installation_to_team_if_exists(&user_id, team.id())+ .await?;++ let team_row_count = sqlx::query(+ r#"+ SELECT COUNT(*) AS count+ FROM github_app_installation+ WHERE source_id = $1+ "#,+ )+ .bind(team.id().to_string())+ .fetch_one(&pool)+ .await?+ .try_get::<i64, _>("count")?;+ assert_eq!(team_row_count, 0);++ let unrelated_row = sqlx::query(+ r#"+ SELECT source_id, source_type::text AS source_type+ FROM github_app_installation+ WHERE id = 'other-user-installation'+ "#,+ )+ .fetch_one(&pool)+ .await?;++ assert_eq!(+ unrelated_row.try_get::<String, _>("source_id")?,+ unrelated_user_id+ );+ assert_eq!(unrelated_row.try_get::<String, _>("source_type")?, "user");++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("teams"))