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.

check invite count against seat count (#3303)

Will Hutchinsond05b3d1df8ab
diff --git a/rust/cloud-storage/.sqlx/query-2d57c3a99a46bf686884ad509c913941732afc0ed4d180fdd982f50cdf39b08b.json b/rust/cloud-storage/.sqlx/query-2d57c3a99a46bf686884ad509c913941732afc0ed4d180fdd982f50cdf39b08b.json
new file mode 100644
index 0000000000..fef16a70f7
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-2d57c3a99a46bf686884ad509c913941732afc0ed4d180fdd982f50cdf39b08b.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT t.email as \"email!\"\n FROM UNNEST($2::text[], $3::text[]) WITH ORDINALITY AS t(email, user_id, ord)\n WHERE NOT EXISTS (\n SELECT 1 FROM team_invite ti\n WHERE ti.team_id = $1 AND ti.email = t.email\n )\n AND NOT EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = $1 AND tu.user_id = t.user_id\n )\n GROUP BY t.email\n ORDER BY MIN(t.ord)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "email!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "2d57c3a99a46bf686884ad509c913941732afc0ed4d180fdd982f50cdf39b08b"
+}
diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rs
index a0a09786c0..7f653bdc4e 100644
--- a/rust/cloud-storage/teams/src/domain/model.rs
+++ b/rust/cloud-storage/teams/src/domain/model.rs
@@ -308,6 +308,9 @@ pub enum InviteUsersToTeamError {
/// Too many emails were provided
#[error("Too many emails were provided")]
TooManyEmails,
+ /// Not enough open seats
+ #[error("Not enough open seats")]
+ NotEnoughOpenSeats,
/// Underlying team error
#[error("Underlying team error {0}")]
TeamError(#[from] TeamError),
diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rs
index cba4beaaa1..2ae3c362f5 100644
--- a/rust/cloud-storage/teams/src/domain/team_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs
@@ -62,6 +62,14 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;
+ /// Compares the list of users you are trying to invite to ones already invited
+ /// to return a list of emails who will be newly invited
+ fn get_new_invites(
+ &self,
+ team_id: &uuid::Uuid,
+ invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
+ ) -> impl Future<Output = Result<Vec<Email<Lowercase<'static>>>, InviteUsersToTeamError>> + Send;
+
/// Marks the given team invites as sent by updating their last_sent_at timestamp.
fn mark_invites_sent(
&self,
diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rs
index 63a4256cbf..a2488c6d0b 100644
--- a/rust/cloud-storage/teams/src/domain/team_service.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service.rs
@@ -240,6 +240,20 @@ where
.get_authenticated_user()
.map_err(|e| InviteUsersToTeamError::TeamError(TeamError::AccessError(e)))?;
+ let team_plan = self.team_repository.get_team_plan(&team_id).await?;
+ let seat_count = self.team_repository.get_team_seat_count(&team_id).await?;
+
+ let new_invites = self
+ .team_repository
+ .get_new_invites(&team_id, invites.clone())
+ .await?;
+
+ if let Some(team_plan) = team_plan
+ && seat_count + new_invites.len() as i32 > team_plan.seat_cap()
+ {
+ return Err(InviteUsersToTeamError::NotEnoughOpenSeats);
+ }
+
let invited = self
.team_repository
.invite_users_to_team(&team_id, invited_by, invites)
diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rs
index 20e8e5a956..bfdf5da8ea 100644
--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs
@@ -127,6 +127,24 @@ impl TeamRepository for MockTeamRepository {
async move { Ok(invites) }
}
+ fn get_new_invites(
+ &self,
+ _: &uuid::Uuid,
+ invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
+ ) -> impl Future<Output = Result<Vec<Email<Lowercase<'static>>>, InviteUsersToTeamError>> + Send
+ {
+ let invites = invites
+ .iter()
+ .map(|email| {
+ Email::parse_from_str(email.as_ref())
+ .expect("test emails should be valid")
+ .into_owned()
+ .lowercase()
+ })
+ .collect();
+ async move { Ok(invites) }
+ }
+
fn mark_invites_sent(
&self,
invite_ids: &[uuid::Uuid],
@@ -335,14 +353,14 @@ impl TeamRepository for MockTeamRepository {
&self,
_: &uuid::Uuid,
) -> impl Future<Output = Result<i32, TeamError>> + Send {
- async { unimplemented!() }
+ async { Ok(0) }
}
fn get_team_plan(
&self,
_: &uuid::Uuid,
) -> impl Future<Output = Result<Option<TeamPlan>, TeamError>> + Send {
- async { unimplemented!() }
+ async { Ok(None) }
}
fn patch_team_plan(
diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rs
index 1427eaccea..b58d4d867b 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs
@@ -335,6 +335,59 @@ impl TeamRepository for TeamRepositoryImpl {
Ok(all_invites)
}
+ #[tracing::instrument(skip(self), err)]
+ async fn get_new_invites(
+ &self,
+ team_id: &uuid::Uuid,
+ invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
+ ) -> Result<Vec<Email<Lowercase<'static>>>, InviteUsersToTeamError> {
+ let email_strings: Vec<String> = invites
+ .iter()
+ .map(|email| email.as_ref().to_string())
+ .collect();
+
+ let macro_user_ids: Vec<String> = invites
+ .iter()
+ .map(|email| format!("macro|{}", email.as_ref()))
+ .collect();
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT t.email as "email!"
+ FROM UNNEST($2::text[], $3::text[]) WITH ORDINALITY AS t(email, user_id, ord)
+ WHERE NOT EXISTS (
+ SELECT 1 FROM team_invite ti
+ WHERE ti.team_id = $1 AND ti.email = t.email
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM team_user tu
+ WHERE tu.team_id = $1 AND tu.user_id = t.user_id
+ )
+ GROUP BY t.email
+ ORDER BY MIN(t.ord)
+ "#,
+ team_id,
+ &email_strings[..],
+ &macro_user_ids[..],
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ let mut new_invites = Vec::with_capacity(rows.len());
+ for row in rows {
+ let email = Email::parse_from_str(&row.email)
+ .map(|email| email.into_owned().lowercase())
+ .map_err(|e| {
+ InviteUsersToTeamError::StorageLayerError(anyhow::anyhow!(
+ "unable to parse email {e}"
+ ))
+ })?;
+ new_invites.push(email);
+ }
+
+ Ok(new_invites)
+ }
+
#[tracing::instrument(skip(self), err)]
async fn mark_invites_sent(&self, invite_ids: &[uuid::Uuid]) -> Result<(), TeamError> {
sqlx::query!(
diff --git a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
index 3969f43e98..ea7a6ef311 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
@@ -130,6 +130,85 @@ async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
Ok(())
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn test_get_new_invites_filters_existing_invites(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let team_repo = TeamRepositoryImpl::new(pool);
+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
+
+ let invites = vec![
+ Email::parse_from_str("[email protected]")?.lowercase(),
+ Email::parse_from_str("[email protected]")?.lowercase(),
+ ];
+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;
+
+ let new_invites = team_repo.get_new_invites(&team_id, invites).await?;
+
+ assert_eq!(new_invites.len(), 1);
+ assert_eq!(new_invites[0].as_ref(), "[email protected]");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn test_get_new_invites_filters_existing_team_members(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let team_repo = TeamRepositoryImpl::new(pool);
+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
+
+ let invites = vec![
+ Email::parse_from_str("[email protected]")?.lowercase(),
+ Email::parse_from_str("[email protected]")?.lowercase(),
+ ];
+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;
+
+ let new_invites = team_repo.get_new_invites(&team_id, invites).await?;
+
+ assert_eq!(new_invites.len(), 1);
+ assert_eq!(new_invites[0].as_ref(), "[email protected]");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn test_get_new_invites_keeps_invites_scoped_to_team(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let team_repo = TeamRepositoryImpl::new(pool.clone());
+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
+ let other_team_id = macro_uuid::string_to_uuid("22222222-2222-2222-2222-222222222222")?;
+
+ sqlx::query!(
+ r#"
+ INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at)
+ VALUES ($1, $2, '[email protected]', 'member', 'macro|[email protected]', NOW(), NOW())
+ "#,
+ macro_uuid::generate_uuid_v7(),
+ other_team_id,
+ )
+ .execute(&pool)
+ .await?;
+
+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;
+
+ let new_invites = team_repo.get_new_invites(&team_id, invites).await?;
+
+ assert_eq!(new_invites.len(), 1);
+ assert_eq!(new_invites[0].as_ref(), "[email protected]");
+
+ Ok(())
+}
+
/// Re-inviting an already-invited user within the 5-minute window should not
/// return them (rate limited), so the result should be empty.
#[sqlx::test(