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): allow patching team user role (#2855)

Will Hutchinson0d93ab0f0fc8
diff --git a/js/app/packages/app/component/settings/Team.tsx b/js/app/packages/app/component/settings/Team.tsx
index d19e76843f..36027d550e 100644
--- a/js/app/packages/app/component/settings/Team.tsx
+++ b/js/app/packages/app/component/settings/Team.tsx
@@ -36,9 +36,9 @@ import { formatRelativeTimestamp } from '@entity';
import { z } from 'zod';
const roleOrder: Record<string, number> = {
- [TeamRole.Owner]: 0,
- [TeamRole.Admin]: 1,
- [TeamRole.Member]: 2,
+ [TeamRole.owner]: 0,
+ [TeamRole.admin]: 1,
+ [TeamRole.member]: 2,
};
type TierOption = { value: TeamUserTier; label: string };
@@ -128,9 +128,9 @@ function MemberRow(props: {
</Show>
<Show when={props.isOwner}>
<Show
- when={!props.isCurrentUser && props.member.role !== TeamRole.Owner}
+ when={!props.isCurrentUser && props.member.role !== TeamRole.owner}
fallback={
- <Tooltip tooltip={props.member.role === TeamRole.Owner ? "Cannot remove team owner" : "Cannot remove yourself"}>
+ <Tooltip tooltip={props.member.role === TeamRole.owner ? "Cannot remove team owner" : "Cannot remove yourself"}>
<Button variant="ghost" size="sm" disabled class="rounded-xs opacity-50 cursor-not-allowed">
<TrashIcon class="w-4 h-4" />
</Button>
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
index ca0c26fca6..fd9b09bf78 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
@@ -42,6 +42,8 @@ export * from './passwordRequest';
export * from './patchSubscriptionTierRequest';
export * from './patchTeamRequest';
export * from './patchTeamRequestName';
+export * from './patchTeamRequestUserRoleUpdates';
+export * from './patchTeamUserRole';
export * from './patchTeamUserTierRequest';
export * from './patchUserGroupRequest';
export * from './patchUserOnboardingRequest';
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequest.ts
index 3bbaa44f80..3e95479fc8 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequest.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequest.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { PatchTeamRequestName } from './patchTeamRequestName';
+import type { PatchTeamRequestUserRoleUpdates } from './patchTeamRequestUserRoleUpdates';
/**
* Request to update a team
@@ -12,4 +13,6 @@ import type { PatchTeamRequestName } from './patchTeamRequestName';
export interface PatchTeamRequest {
/** The new name for the team */
name?: PatchTeamRequestName;
+ /** Role updates to apply to team users */
+ user_role_updates?: PatchTeamRequestUserRoleUpdates;
}
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequestUserRoleUpdates.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequestUserRoleUpdates.ts
new file mode 100644
index 0000000000..6b13817d01
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamRequestUserRoleUpdates.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PatchTeamUserRole } from './patchTeamUserRole';
+
+/**
+ * Role updates to apply to team users
+ */
+export type PatchTeamRequestUserRoleUpdates = PatchTeamUserRole[] | null;
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamUserRole.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamUserRole.ts
new file mode 100644
index 0000000000..5fd0193d71
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamUserRole.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { TeamRole } from './teamRole';
+
+/**
+ * Request to update a team user's role
+ */
+export interface PatchTeamUserRole {
+ /** The new role of the team user */
+ role: TeamRole;
+ /** The team user you are updating */
+ team_user_id: string;
+}
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamRole.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamRole.ts
index e6d646b5e7..6c2807317b 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamRole.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamRole.ts
@@ -12,7 +12,7 @@ export type TeamRole = (typeof TeamRole)[keyof typeof TeamRole];
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const TeamRole = {
- Member: 'Member',
- Admin: 'Admin',
- Owner: 'Owner',
+ member: 'member',
+ admin: 'admin',
+ owner: 'owner',
} as const;
diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.json
index 07ddef1efb..ba2e3139d8 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -3537,6 +3537,28 @@
"name": {
"type": ["string", "null"],
"description": "The new name for the team"
+ },
+ "user_role_updates": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/PatchTeamUserRole"
+ },
+ "description": "Role updates to apply to team users"
+ }
+ }
+ },
+ "PatchTeamUserRole": {
+ "type": "object",
+ "description": "Request to update a team user's role",
+ "required": ["team_user_id", "role"],
+ "properties": {
+ "role": {
+ "$ref": "#/components/schemas/TeamRole",
+ "description": "The new role of the team user"
+ },
+ "team_user_id": {
+ "type": "string",
+ "description": "The team user you are updating"
}
}
},
@@ -3828,7 +3850,7 @@
"TeamRole": {
"type": "string",
"description": "Ordered from least to most access top -> bottom",
- "enum": ["Member", "Admin", "Owner"]
+ "enum": ["member", "admin", "owner"]
},
"TeamUserTier": {
"type": "string",
diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rs
index e8645417cd..a4a661bc71 100644
--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs
+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs
@@ -1,7 +1,7 @@
use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};
use teams::domain::model::{
- PatchTeamRequest, PatchTeamUserTierRequest, Team, TeamInviteDetails, TeamMember, TeamRole,
- TeamUserTier, TeamWithMembers,
+ PatchTeamRequest, PatchTeamUserRole, PatchTeamUserTierRequest, Team, TeamInviteDetails,
+ TeamMember, TeamRole, TeamUserTier, TeamWithMembers,
};
use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;
use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;
@@ -189,6 +189,7 @@ use model::user::{
CreateTeamRequest,
InviteToTeamRequest,
PatchTeamRequest,
+ PatchTeamUserRole,
TeamTeamInvitesResponse,
UserTeamInvitesResponse,
PatchTeamUserTierRequest,
diff --git a/rust/cloud-storage/teams/.sqlx/query-0e38fa7c2ebae20feb864567132405260eb8fd223e65f4c6da337a8fbe2acc82.json b/rust/cloud-storage/teams/.sqlx/query-0e38fa7c2ebae20feb864567132405260eb8fd223e65f4c6da337a8fbe2acc82.json
new file mode 100644
index 0000000000..aa088ef8b7
--- /dev/null
+++ b/rust/cloud-storage/teams/.sqlx/query-0e38fa7c2ebae20feb864567132405260eb8fd223e65f4c6da337a8fbe2acc82.json
@@ -0,0 +1,27 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE team_user\n SET team_role = $3\n WHERE team_id = $1\n AND user_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0e38fa7c2ebae20feb864567132405260eb8fd223e65f4c6da337a8fbe2acc82"
+}
diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rs
index c6071212e9..f58ea7b33b 100644
--- a/rust/cloud-storage/teams/src/domain/model.rs
+++ b/rust/cloud-storage/teams/src/domain/model.rs
@@ -70,13 +70,24 @@ impl TeamUserTier {
}
}
-#[derive(Eq, PartialEq, Debug, Clone, PartialOrd, Copy, std::cmp::Ord, serde::Serialize)]
+#[derive(
+ Eq,
+ PartialEq,
+ Debug,
+ Clone,
+ PartialOrd,
+ Copy,
+ std::cmp::Ord,
+ serde::Serialize,
+ serde::Deserialize,
+)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "outbound", derive(sqlx::Type))]
#[cfg_attr(
feature = "outbound",
sqlx(type_name = "\"team_role\"", rename_all = "lowercase")
)]
+#[serde(rename_all = "lowercase")]
/// Ordered from least to most access top -> bottom
pub enum TeamRole {
/// The user is a member of the team
@@ -149,6 +160,19 @@ pub struct TeamInviteDetails {
pub struct PatchTeamRequest {
/// The new name for the team
pub name: Option<String>,
+ /// Role updates to apply to team users
+ pub user_role_updates: Option<Vec<PatchTeamUserRole>>,
+}
+
+/// Request to update a team user's role
+#[derive(Debug, serde::Deserialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+pub struct PatchTeamUserRole {
+ /// The team user you are updating
+ #[cfg_attr(feature = "axum", schema(value_type = String))]
+ pub team_user_id: MacroUserIdStr<'static>,
+ /// The new role of the team user
+ pub role: TeamRole,
}
/// Request to update a team user's tier
diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rs
index d5277b8c21..e221bc4b49 100644
--- a/rust/cloud-storage/teams/src/domain/team_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs
@@ -192,6 +192,14 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
user_id: &MacroUserIdStr<'_>,
team_tier: TeamUserTier,
) -> impl Future<Output = Result<(), TeamError>> + Send;
+
+ /// Patches the role of the provided user id for the team
+ fn patch_team_user_role(
+ &self,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ team_role: TeamRole,
+ ) -> impl Future<Output = Result<(), TeamError>> + Send;
}
/// The TeamService defines a set of actions to perform on the teams
diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rs
index 09ebb67af7..7e98e17502 100644
--- a/rust/cloud-storage/teams/src/domain/team_service.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service.rs
@@ -497,6 +497,33 @@ where
team_id: &uuid::Uuid,
req: &PatchTeamRequest,
) -> Result<(), TeamError> {
+ if let Some(user_role_updates) = req.user_role_updates.as_ref() {
+ if user_role_updates.iter().any(|u| u.role == TeamRole::Owner) {
+ return Err(TeamError::BadRequest(
+ "cannot assign the Owner role".to_string(),
+ ));
+ }
+
+ if !user_role_updates.is_empty() {
+ let team = self.team_repository.get_team_by_id(team_id).await?;
+
+ if user_role_updates
+ .iter()
+ .any(|u| u.team_user_id.as_ref() == team.team.owner_id())
+ {
+ return Err(TeamError::BadRequest(
+ "cannot downgrade the team owner's role".to_string(),
+ ));
+ }
+
+ for update in user_role_updates {
+ self.team_repository
+ .patch_team_user_role(team_id, &update.team_user_id, update.role)
+ .await?;
+ }
+ }
+ }
+
self.team_repository.patch_team(team_id, req).await
}
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 ea9ad3d2d0..a8f0ea634e 100644
--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs
@@ -21,9 +21,9 @@ use super::*;
use crate::domain::{
customer_repo::CustomerRepository,
model::{
- CreateSubscriptionArgs, CustomerError, PatchTeamRequest, RemoveTeamInviteError,
- RemoveUserFromTeamError, Team, TeamError, TeamInvite, TeamInviteDetails, TeamMember,
- TeamRole, TeamUserTier, TeamWithMembers,
+ CreateSubscriptionArgs, CustomerError, PatchTeamRequest, PatchTeamUserRole,
+ RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError, TeamInvite,
+ TeamInviteDetails, TeamMember, TeamRole, TeamUserTier, TeamWithMembers,
},
team_repo::{TeamChannelsRepository, TeamRepository},
};
@@ -35,6 +35,9 @@ struct MockTeamRepository {
invites_to_return: Vec<TeamInvite<'static>>,
team_name: String,
mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>>,
+ team_for_get_by_id: Option<Team>,
+ patch_team_user_role_calls: Arc<Mutex<Vec<(uuid::Uuid, String, TeamRole)>>>,
+ patch_team_name_calls: Arc<Mutex<Vec<(uuid::Uuid, Option<String>)>>>,
}
impl MockTeamRepository {
@@ -47,8 +50,16 @@ impl MockTeamRepository {
invites_to_return: invites,
team_name: team_name.to_string(),
mark_sent_calls,
+ team_for_get_by_id: None,
+ patch_team_user_role_calls: Arc::new(Mutex::new(Vec::new())),
+ patch_team_name_calls: Arc::new(Mutex::new(Vec::new())),
}
}
+
+ fn with_team(mut self, team: Team) -> Self {
+ self.team_for_get_by_id = Some(team);
+ self
+ }
}
impl TeamRepository for MockTeamRepository {
@@ -172,7 +183,14 @@ impl TeamRepository for MockTeamRepository {
&self,
_: &uuid::Uuid,
) -> impl Future<Output = Result<TeamWithMembers, TeamError>> + Send {
- async { unimplemented!() }
+ let team = self.team_for_get_by_id.clone();
+ async move {
+ let team = team.ok_or(TeamError::TeamDoesNotExist)?;
+ Ok(TeamWithMembers {
+ team,
+ members: Vec::new(),
+ })
+ }
}
fn get_user_teams(
@@ -206,10 +224,14 @@ impl TeamRepository for MockTeamRepository {
fn patch_team(
&self,
- _: &uuid::Uuid,
- _: &PatchTeamRequest,
+ team_id: &uuid::Uuid,
+ req: &PatchTeamRequest,
) -> impl Future<Output = Result<(), TeamError>> + Send {
- async { unimplemented!() }
+ self.patch_team_name_calls
+ .lock()
+ .unwrap()
+ .push((*team_id, req.name.clone()));
+ async { Ok(()) }
}
fn get_team_role(
@@ -236,6 +258,20 @@ impl TeamRepository for MockTeamRepository {
) -> impl Future<Output = Result<(), TeamError>> + Send {
async { unimplemented!() }
}
+
+ fn patch_team_user_role(
+ &self,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ role: TeamRole,
+ ) -> impl Future<Output = Result<(), TeamError>> + Send {
+ self.patch_team_user_role_calls.lock().unwrap().push((
+ *team_id,
+ user_id.as_ref().to_string(),
+ role,
+ ));
+ async { Ok(()) }
+ }
}
// -- Mock CustomerRepository --
@@ -582,3 +618,151 @@ async fn test_invite_marks_all_sent_when_all_notifications_succeed() {
assert!(marked_ids.contains(&invite_id_1));
assert!(marked_ids.contains(&invite_id_2));
}
+
+fn build_service_with_team(
+ team: Team,
+) -> (
+ impl TeamService,
+ Arc<Mutex<Vec<(uuid::Uuid, String, TeamRole)>>>,
+ Arc<Mutex<Vec<(uuid::Uuid, Option<String>)>>>,
+) {
+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));
+ let team_repo =
+ MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls).with_team(team);
+ let role_calls = team_repo.patch_team_user_role_calls.clone();
+ let name_calls = team_repo.patch_team_name_calls.clone();
+ let notification_ingress = Arc::new(MockNotificationIngress::new(HashSet::new()));
+ let service = TeamServiceImpl::new(
+ team_repo,
+ MockCustomerRepository,
+ MockTeamChannelsRepository,
+ MockUserRolesAndPermissionsService,
+ notification_ingress,
+ );
+ (service, role_calls, name_calls)
+}
+
+/// Attempting to assign the Owner role via patch_team is rejected.
+#[tokio::test]
+async fn test_patch_team_rejects_owner_role_assignment() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let team = Team::new(team_id, "Test Team".to_string(), owner_id);
+
+ let (service, role_calls, name_calls) = build_service_with_team(team);
+
+ let req = PatchTeamRequest {
+ name: Some("New Name".to_string()),
+ user_role_updates: Some(vec![PatchTeamUserRole {
+ team_user_id: MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ role: TeamRole::Owner,
+ }]),
+ };
+
+ let err = service.patch_team(&team_id, &req).await.err().unwrap();
+ assert!(matches!(err, TeamError::BadRequest(_)));
+ assert!(role_calls.lock().unwrap().is_empty());
+ assert!(name_calls.lock().unwrap().is_empty());
+}
+
+/// Attempting to modify the team owner's role via patch_team is rejected.
+#[tokio::test]
+async fn test_patch_team_rejects_owner_downgrade() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let team = Team::new(team_id, "Test Team".to_string(), owner_id.clone());
+
+ let (service, role_calls, name_calls) = build_service_with_team(team);
+
+ let req = PatchTeamRequest {
+ name: None,
+ user_role_updates: Some(vec![PatchTeamUserRole {
+ team_user_id: owner_id,
+ role: TeamRole::Member,
+ }]),
+ };
+
+ let err = service.patch_team(&team_id, &req).await.err().unwrap();
+ assert!(matches!(err, TeamError::BadRequest(_)));
+ assert!(role_calls.lock().unwrap().is_empty());
+ assert!(name_calls.lock().unwrap().is_empty());
+}
+
+/// Valid role updates are applied and the team name is also updated.
+#[tokio::test]
+async fn test_patch_team_applies_role_updates_and_name() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let member_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let admin_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let team = Team::new(team_id, "Old Name".to_string(), owner_id);
+
+ let (service, role_calls, name_calls) = build_service_with_team(team);
+
+ let req = PatchTeamRequest {
+ name: Some("New Name".to_string()),
+ user_role_updates: Some(vec![
+ PatchTeamUserRole {
+ team_user_id: member_id.clone(),
+ role: TeamRole::Admin,
+ },
+ PatchTeamUserRole {
+ team_user_id: admin_id.clone(),
+ role: TeamRole::Member,
+ },
+ ]),
+ };
+
+ service.patch_team(&team_id, &req).await.unwrap();
+
+ let role_calls = role_calls.lock().unwrap();
+ assert_eq!(role_calls.len(), 2);
+ assert_eq!(
+ role_calls[0],
+ (team_id, member_id.as_ref().to_string(), TeamRole::Admin)
+ );
+ assert_eq!(
+ role_calls[1],
+ (team_id, admin_id.as_ref().to_string(), TeamRole::Member)
+ );
+
+ let name_calls = name_calls.lock().unwrap();
+ assert_eq!(name_calls.len(), 1);
+ assert_eq!(name_calls[0], (team_id, Some("New Name".to_string())));
+}
+
+/// Empty user_role_updates vec is a no-op for roles but still applies name.
+#[tokio::test]
+async fn test_patch_team_empty_role_updates() {
+ let team_id = uuid::Uuid::from_u128(1);
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let team = Team::new(team_id, "Old Name".to_string(), owner_id);
+
+ let (service, role_calls, name_calls) = build_service_with_team(team);
+
+ let req = PatchTeamRequest {
+ name: Some("New Name".to_string()),
+ user_role_updates: Some(Vec::new()),
+ };
+
+ service.patch_team(&team_id, &req).await.unwrap();
+
+ assert!(role_calls.lock().unwrap().is_empty());
+ let name_calls = name_calls.lock().unwrap();
+ assert_eq!(name_calls.len(), 1);
+ assert_eq!(name_calls[0], (team_id, Some("New Name".to_string())));
+}
diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rs
index f7c9f46295..89482e5843 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs
@@ -971,4 +971,32 @@ impl TeamRepository for TeamRepositoryImpl {
Ok(())
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn patch_team_user_role(
+ &self,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ team_role: TeamRole,
+ ) -> Result<(), TeamError> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE team_user
+ SET team_role = $3
+ WHERE team_id = $1
+ AND user_id = $2
+ "#,
+ team_id,
+ user_id.as_ref(),
+ team_role as _,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ if result.rows_affected() == 0 {
+ return Err(TeamError::TeamMemberNotFound(*team_id));
+ }
+
+ Ok(())
+ }
}
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 9dbd5be2a8..ca76841425 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
@@ -773,3 +773,42 @@ async fn test_patch_team_tier(pool: Pool<Postgres>) -> anyhow::Result<()> {
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("teams"))
+)]
+async fn test_patch_team_user_role(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 user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+
+ // Promote to Admin
+ team_repo
+ .patch_team_user_role(&team_id, &user_id, TeamRole::Admin)
+ .await?;
+
+ let member = team_repo.get_team_member(&team_id, &user_id).await?;
+ assert_eq!(member.role, TeamRole::Admin);
+
+ // Demote back to Member
+ team_repo
+ .patch_team_user_role(&team_id, &user_id, TeamRole::Member)
+ .await?;
+
+ let member = team_repo.get_team_member(&team_id, &user_id).await?;
+ assert_eq!(member.role, TeamRole::Member);
+
+ // Patch role for non-existent member
+ let missing_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ let err = team_repo
+ .patch_team_user_role(&team_id, &missing_id, TeamRole::Admin)
+ .await
+ .err()
+ .unwrap();
+
+ assert!(err.to_string().contains("member not found"));
+
+ Ok(())
+}