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(teams): derive slug from team name (#5121)

Will Hutchinson960ff11a5956
diff --git a/.sqlx/query-3077b37e938c3d4c03d3a555a2bafbee6ca8ad05a9fca54736aeb6fc19409002.json b/.sqlx/query-fe4923829f168f5b5df199802772022b6a602bbb4d1b6a05036481a416074939.json
similarity index 71%
rename from .sqlx/query-3077b37e938c3d4c03d3a555a2bafbee6ca8ad05a9fca54736aeb6fc19409002.json
rename to .sqlx/query-fe4923829f168f5b5df199802772022b6a602bbb4d1b6a05036481a416074939.json
index 842118de4f..8104c4cf8f 100644
--- a/.sqlx/query-3077b37e938c3d4c03d3a555a2bafbee6ca8ad05a9fca54736aeb6fc19409002.json
+++ b/.sqlx/query-fe4923829f168f5b5df199802772022b6a602bbb4d1b6a05036481a416074939.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO team (id, name, owner_id, seat_count, subscription_id, paying)\n VALUES ($1, $2, $3, 1, $4, $5)\n RETURNING id, name, slug, owner_id, enterprise, allow_non_admin_invites\n ",
+ "query": "\n INSERT INTO team (id, name, slug, owner_id, seat_count, subscription_id, paying)\n VALUES ($1, $2, $3, $4, 1, $5, $6)\n RETURNING id, name, slug, owner_id, enterprise, allow_non_admin_invites\n ",
"describe": {
"columns": [
{
@@ -38,6 +38,7 @@
"Left": [
"Uuid",
"Text",
+ "Varchar",
"Text",
"Text",
"Bool"
@@ -52,5 +53,5 @@
false
]
},
- "hash": "3077b37e938c3d4c03d3a555a2bafbee6ca8ad05a9fca54736aeb6fc19409002"
+ "hash": "fe4923829f168f5b5df199802772022b6a602bbb4d1b6a05036481a416074939"
}
diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rs
index e8632fbe90..e045a9ec41 100644
--- a/crates/teams/src/domain/model.rs
+++ b/crates/teams/src/domain/model.rs
@@ -56,6 +56,61 @@ impl TeamPlan {
/// requires the owner to subscribe.
pub const FREE_TEAM_MAX_MEMBERS: i32 = 5;
+/// Slug assigned when a team name cannot be converted to a valid team slug.
+pub const DEFAULT_TEAM_SLUG: &str = "MACRO";
+
+const MAX_TEAM_SLUG_LEN: usize = 20;
+
+pub(crate) fn normalize_team_slug(slug: &str) -> Result<String, TeamError> {
+ let mut normalized = String::new();
+ let mut last_was_separator = false;
+
+ for ch in slug.chars() {
+ let normalized_char = if ch.is_ascii_alphabetic() {
+ ch.to_ascii_uppercase()
+ } else if ch == '_' || ch == '-' || ch.is_ascii_whitespace() {
+ '_'
+ } else {
+ return Err(TeamError::BadRequest(
+ "team slug may only contain ASCII letters, spaces, hyphens, and underscores"
+ .to_string(),
+ ));
+ };
+
+ if normalized_char == '_' {
+ if !normalized.is_empty() && !last_was_separator {
+ normalized.push('_');
+ }
+ last_was_separator = true;
+ } else {
+ normalized.push(normalized_char);
+ last_was_separator = false;
+ }
+ }
+
+ while normalized.ends_with('_') {
+ normalized.pop();
+ }
+
+ if normalized.is_empty() {
+ return Err(TeamError::BadRequest(
+ "team slug cannot be empty".to_string(),
+ ));
+ }
+
+ if normalized.len() > MAX_TEAM_SLUG_LEN {
+ return Err(TeamError::BadRequest(format!(
+ "team slug cannot be longer than {MAX_TEAM_SLUG_LEN} characters"
+ )));
+ }
+
+ Ok(normalized)
+}
+
+pub(crate) fn team_slug_from_name(team_name: &str) -> String {
+ normalize_team_slug(team_name).unwrap_or_else(|_| DEFAULT_TEAM_SLUG.to_string())
+}
+
#[derive(
Eq,
PartialEq,
diff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rs
index 1ae53580f3..525236391a 100644
--- a/crates/teams/src/domain/team_repo.rs
+++ b/crates/teams/src/domain/team_repo.rs
@@ -47,12 +47,13 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
team_id: &uuid::Uuid,
) -> impl Future<Output = Result<bool, TeamError>> + Send;
- /// Creates a new team. `subscription_id` is `None` for free teams
- /// (capped at [`crate::domain::model::FREE_TEAM_MAX_MEMBERS`] members).
+ /// Creates a new team with the provided normalized slug. `subscription_id` is `None` for
+ /// free teams (capped at [`crate::domain::model::FREE_TEAM_MAX_MEMBERS`] members).
fn create_team(
&self,
user_id: &MacroUserIdStr<'_>,
team_name: &str,
+ team_slug: &str,
subscription_id: Option<&stripe::SubscriptionId>,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;
diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rs
index 4f2cb052b0..326b78e1b5 100644
--- a/crates/teams/src/domain/team_service.rs
+++ b/crates/teams/src/domain/team_service.rs
@@ -44,7 +44,7 @@ use crate::domain::{
RemoveTeamInviteError, RemoveUserFromTeamError, RestorePermissionsForTeamMembersError,
RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,
TeamMember, TeamMembers, TeamRole, TeamWithMembers, ToggleAutoJoinDomainError,
- TryJoinTeamByDomainError, is_generic_email_domain,
+ TryJoinTeamByDomainError, is_generic_email_domain, team_slug_from_name,
},
team_analytics::{NoOpTeamAnalytics, TeamAnalytics, TeamAnalyticsEvent},
team_crm_settings_repo::TeamCrmSettingsRepository,
@@ -556,9 +556,10 @@ 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`.
+ let team_slug = team_slug_from_name(team_name);
let team = self
.team_repository
- .create_team(user_id, team_name, subscription_id)
+ .create_team(user_id, team_name, &team_slug, subscription_id)
.await?;
let owner_id = user_id.clone().into_owned();
self.channel_service
diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rs
index 4f6bb36b1b..de3f22d1dd 100644
--- a/crates/teams/src/domain/team_service/test.rs
+++ b/crates/teams/src/domain/team_service/test.rs
@@ -97,6 +97,7 @@ struct MockTeamRepository {
patch_team_name_calls: Arc<Mutex<Vec<(uuid::Uuid, Option<String>, Option<String>)>>>,
fail_patch_team: bool,
created_team: Team,
+ create_team_calls: Arc<Mutex<Vec<(String, String)>>>,
github_installation_move_calls: Arc<Mutex<Vec<(String, uuid::Uuid)>>>,
subscription_update_calls: Arc<Mutex<Vec<(uuid::Uuid, String)>>>,
payment_update_calls: Arc<Mutex<Vec<(uuid::Uuid, bool)>>>,
@@ -169,6 +170,7 @@ impl MockTeamRepository {
false,
false,
),
+ create_team_calls: Arc::new(Mutex::new(Vec::new())),
github_installation_move_calls: Arc::new(Mutex::new(Vec::new())),
subscription_update_calls: Arc::new(Mutex::new(Vec::new())),
payment_update_calls: Arc::new(Mutex::new(Vec::new())),
@@ -303,9 +305,14 @@ impl TeamRepository for MockTeamRepository {
fn create_team(
&self,
_: &MacroUserIdStr<'_>,
- _: &str,
+ team_name: &str,
+ team_slug: &str,
_: Option<&stripe::SubscriptionId>,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send {
+ self.create_team_calls
+ .lock()
+ .unwrap()
+ .push((team_name.to_string(), team_slug.to_string()));
let team = self.created_team.clone();
async move { Ok(team) }
}
@@ -1947,6 +1954,36 @@ async fn team_payment_patch_payment_status_delegates_to_repository() {
);
}
+#[tokio::test]
+async fn create_team_sets_slug_from_name_or_uses_default() {
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ for (team_name, expected_slug) in [
+ ("Product Engineering", "PRODUCT_ENGINEERING"),
+ ("Team 42", "MACRO"),
+ ] {
+ let team_repository =
+ MockTeamRepository::new(Vec::new(), team_name, Arc::new(Mutex::new(Vec::new())));
+ let create_team_calls = team_repository.create_team_calls.clone();
+ let service = TeamServiceImpl::new(
+ team_repository,
+ MockCustomerRepository::default(),
+ RecordingChannelService::default(),
+ MockUserRolesAndPermissionsService::default(),
+ Arc::new(MockNotificationIngress::new(HashSet::new())),
+ NoOpCrmEnqueuer,
+ NoOpTeamCrmSettingsRepository,
+ );
+
+ service.create_team(&owner, team_name, None).await.unwrap();
+
+ assert_eq!(
+ *create_team_calls.lock().unwrap(),
+ vec![(team_name.to_string(), expected_slug.to_string())]
+ );
+ }
+}
+
#[tokio::test]
async fn create_team_creates_default_team_channel() {
let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
diff --git a/crates/teams/src/outbound/team_repo.rs b/crates/teams/src/outbound/team_repo.rs
index d2c2ebdf31..2071c62190 100644
--- a/crates/teams/src/outbound/team_repo.rs
+++ b/crates/teams/src/outbound/team_repo.rs
@@ -4,7 +4,7 @@ use crate::domain::{
AcceptedTeamInvite, CreateTeamError, InviteUsersToTeamError, PatchTeamRequest,
RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError, TeamInvite,
TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamMembers, TeamPlan, TeamRole,
- TeamWithMembers, ToggleAutoJoinDomainError, is_generic_email_domain,
+ TeamWithMembers, ToggleAutoJoinDomainError, is_generic_email_domain, normalize_team_slug,
},
team_repo::{TeamMembersService, TeamRepository},
};
@@ -24,54 +24,6 @@ fn type_err<E: std::fmt::Display>(e: E) -> sqlx::Error {
}
}
-const MAX_TEAM_SLUG_LEN: usize = 20;
-
-fn normalize_team_slug(slug: &str) -> Result<String, TeamError> {
- let mut normalized = String::new();
- let mut last_was_separator = false;
-
- for ch in slug.chars() {
- let normalized_char = if ch.is_ascii_alphabetic() {
- ch.to_ascii_uppercase()
- } else if ch == '_' || ch == '-' || ch.is_ascii_whitespace() {
- '_'
- } else {
- return Err(TeamError::BadRequest(
- "team slug may only contain ASCII letters, spaces, hyphens, and underscores"
- .to_string(),
- ));
- };
-
- if normalized_char == '_' {
- if !normalized.is_empty() && !last_was_separator {
- normalized.push('_');
- }
- last_was_separator = true;
- } else {
- normalized.push(normalized_char);
- last_was_separator = false;
- }
- }
-
- while normalized.ends_with('_') {
- normalized.pop();
- }
-
- if normalized.is_empty() {
- return Err(TeamError::BadRequest(
- "team slug cannot be empty".to_string(),
- ));
- }
-
- if normalized.len() > MAX_TEAM_SLUG_LEN {
- return Err(TeamError::BadRequest(format!(
- "team slug cannot be longer than {MAX_TEAM_SLUG_LEN} characters"
- )));
- }
-
- Ok(normalized)
-}
-
#[cfg(test)]
mod test;
@@ -138,6 +90,7 @@ impl TeamRepositoryImpl {
&self,
user_id: &MacroUserIdStr<'_>,
team_name: &str,
+ team_slug: &str,
subscription_id: Option<&stripe::SubscriptionId>,
) -> Result<Team, sqlx::Error> {
let mut transaction = self.pool.begin().await?;
@@ -146,12 +99,13 @@ impl TeamRepositoryImpl {
let team = sqlx::query!(
r#"
- INSERT INTO team (id, name, owner_id, seat_count, subscription_id, paying)
- VALUES ($1, $2, $3, 1, $4, $5)
+ INSERT INTO team (id, name, slug, owner_id, seat_count, subscription_id, paying)
+ VALUES ($1, $2, $3, $4, 1, $5, $6)
RETURNING id, name, slug, owner_id, enterprise, allow_non_admin_invites
"#,
id,
team_name,
+ team_slug,
user_id.as_ref(),
subscription_id.map(|s| s.to_string()),
subscription_id.is_some(),
@@ -378,13 +332,14 @@ impl TeamRepository for TeamRepositoryImpl {
&self,
user_id: &MacroUserIdStr<'_>,
team_name: &str,
+ team_slug: &str,
subscription_id: Option<&stripe::SubscriptionId>,
) -> Result<Team, CreateTeamError> {
if team_name.is_empty() || team_name.len() > 50 {
return Err(CreateTeamError::InvalidTeamName(team_name.to_string()));
}
- self.create_team_inner(user_id, team_name, subscription_id)
+ self.create_team_inner(user_id, team_name, team_slug, subscription_id)
.await
.map_err(|e| e.into())
}
diff --git a/crates/teams/src/outbound/team_repo/test.rs b/crates/teams/src/outbound/team_repo/test.rs
index b9de21b0d0..4445066def 100644
--- a/crates/teams/src/outbound/team_repo/test.rs
+++ b/crates/teams/src/outbound/team_repo/test.rs
@@ -170,18 +170,23 @@ async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let result = team_repo
- .create_team(&user_id, "team1", Some(&"sub_test".parse().unwrap()))
+ .create_team(
+ &user_id,
+ "Product Team",
+ "PRODUCT_TEAM",
+ Some(&"sub_test".parse().unwrap()),
+ )
.await?;
assert!(!result.id.to_string().is_empty());
- assert_eq!(result.name, "team1");
- assert_eq!(result.slug, "MACRO");
+ assert_eq!(result.name, "Product Team");
+ assert_eq!(result.slug, "PRODUCT_TEAM");
assert_eq!(result.owner_id.0.as_ref(), "macro|[email protected]");
assert!(!result.enterprise());
// Create team with too large a name
let err = team_repo
- .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", Some(&"sub_test".parse().unwrap()))
+ .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", "MACRO", Some(&"sub_test".parse().unwrap()))
.await
.err()
.unwrap();
@@ -223,6 +228,7 @@ async fn test_move_github_app_installation_to_team_moves_existing_user_rows(
.create_team(
&user_id,
"GitHub Owner Team",
+ "GITHUB_OWNER_TEAM",
Some(&"sub_test".parse().unwrap()),
)
.await?;
@@ -344,6 +350,7 @@ async fn test_move_github_app_installation_to_team_noops_when_user_has_no_rows(
.create_team(
&user_id,
"GitHub Owner Team",
+ "GITHUB_OWNER_TEAM",
Some(&"sub_test".parse().unwrap()),
)
.await?;