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): invite members with a specific tier (#3038)
dev-rba5f30e00b7ee
diff --git a/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx b/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsxindex 2437a2e442..e0541f9448 100644--- a/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx+++ b/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx@@ -22,7 +22,17 @@ import {} from '../use-onboarding-checkout';import { throwOnErr } from '@core/util/maybeResult';import { authServiceClient } from '@service-auth/client';+import { TeamUserTier } from '@service-auth/generated/schemas/teamUserTier';import { invalidateUserTeams } from '@queries/team';++function toTeamUserTier(tier: PaidPlanTier): TeamUserTier {+ const map: Record<PaidPlanTier, TeamUserTier> = {+ haiku: TeamUserTier.Haiku,+ sonnet: TeamUserTier.Sonnet,+ opus: TeamUserTier.Opus,+ };+ return map[tier];+}import { analytics } from '@app/lib/analytics/analytics';import { Tooltip } from '@core/component/Tooltip';@@ -343,13 +353,13 @@ async function createPendingTeamOnReturn(): Promise<boolean> {authServiceClient.createTeam({ name: pendingTeam.name }));- const emails = pendingTeam.members+ const invites = pendingTeam.members.filter((m) => m.email.trim())- .map((m) => m.email);+ .map((m) => ({ email: m.email, tier: toTeamUserTier(m.tier) }));- if (emails.length > 0) {+ if (invites.length > 0) {await throwOnErr(() =>- authServiceClient.inviteToTeam(team.id, { emails })+ authServiceClient.inviteToTeam(team.id, { invites }));}@@ -357,7 +367,7 @@ async function createPendingTeamOnReturn(): Promise<boolean> {clearPendingTeam();analytics.track('onboarding_team_created', {- inviteCount: emails.length,+ inviteCount: invites.length,teamId: team.id,});diff --git a/js/app/packages/app/component/settings/Team.tsx b/js/app/packages/app/component/settings/Team.tsxindex 02972864b5..940842262c 100644--- a/js/app/packages/app/component/settings/Team.tsx+++ b/js/app/packages/app/component/settings/Team.tsx@@ -660,13 +660,12 @@ function CreateTeamDialog(props: { open: boolean; onClose: () => void }) {const result = teamNameSchema.safeParse(teamName());if (!result.success) return;- const emails = invites()- .map((i) => i.email.trim())- .filter((email) => email !== '');+ const inviteEntries = invites()+ .filter((i) => i.email.trim() !== '')+ .map((i) => ({ email: i.email.trim(), tier: i.tier }));- // TODO: Update mutation to accept invites with tiers once API supports itcreateTeamMutation.mutate(- { name: result.data, emails: emails.length > 0 ? emails : undefined },+ { name: result.data, invites: inviteEntries.length > 0 ? inviteEntries : undefined },{ onSuccess: props.onClose });};@@ -949,13 +948,12 @@ function TeamManagement(props: {return;}- // TODO: Update mutation to send invites with tiers once API supports it- const emails = currentInvites- .map((i) => i.email.trim())- .filter((email) => email !== '');+ const inviteEntries = currentInvites+ .filter((i) => i.email.trim() !== '')+ .map((i) => ({ email: i.email.trim(), tier: i.tier }));inviteToTeamMutation.mutate(- { teamId: props.teamId, request: { emails } },+ { teamId: props.teamId, request: { invites: inviteEntries } },{onSuccess: () => {setInvites([]);diff --git a/js/app/packages/queries/team/teams.ts b/js/app/packages/queries/team/teams.tsindex 8f78f6de98..348a69c401 100644--- a/js/app/packages/queries/team/teams.ts+++ b/js/app/packages/queries/team/teams.ts@@ -4,6 +4,7 @@ import { authServiceClient } from '@service-auth/client';import type { CreateTeamRequest } from '@service-auth/generated/schemas/createTeamRequest';import type { PatchTeamRequest } from '@service-auth/generated/schemas/patchTeamRequest';import type { Team } from '@service-auth/generated/schemas/team';+import type { TeamUserTier } from '@service-auth/generated/schemas/teamUserTier';import { useMutation, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';@@ -151,7 +152,7 @@ export function useDeleteTeamMutation(callbacks?: DeleteTeamCallbacks) {type CreateTeamWithInvitesArgs = {name: string;- emails?: string[];+ invites?: { email: string; tier: TeamUserTier }[];};type CreateTeamWithInvitesContext = { previousTeams: Team[] | undefined };type CreateTeamWithInvitesCallbacks = MutationCallbacks<@@ -165,14 +166,14 @@ export function useCreateTeamWithInvitesMutation(callbacks?: CreateTeamWithInvitesCallbacks) {return useMutation(() => ({- mutationFn: async ({ name, emails }: CreateTeamWithInvitesArgs) => {+ mutationFn: async ({ name, invites }: CreateTeamWithInvitesArgs) => {const team = await throwOnErr(() =>authServiceClient.createTeam({ name }));- if (emails && emails.length > 0) {+ if (invites && invites.length > 0) {await throwOnErr(() =>- authServiceClient.inviteToTeam(team.id, { emails })+ authServiceClient.inviteToTeam(team.id, { invites }));}@@ -215,9 +216,9 @@ export function useCreateTeamWithInvitesMutation(return { previousTeams };},- onSuccess: (_team, { emails }) => {+ onSuccess: (_team, { invites }) => {invalidateUserTeams();- const hasInvites = emails && emails.length > 0;+ const hasInvites = invites && invites.length > 0;toast.success(hasInvites ? 'Team created and invitations sent' : 'Team created');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.tsindex fd9b09bf78..d43742d3fd 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@@ -32,6 +32,7 @@ export * from './getUserInfoOrganizationId';export * from './getUserLinkExistsParams';export * from './initGithubLinkParams';export * from './initGithubLinkResponse';+export * from './inviteEntry';export * from './inviteToTeamRequest';export * from './macroApiTokenParams';export * from './macroApiTokenResponse';diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/inviteEntry.ts b/js/app/packages/service-clients/service-auth/generated/schemas/inviteEntry.tsnew file mode 100644index 0000000000..e66a911163--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/inviteEntry.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 { TeamUserTier } from './teamUserTier';++/**+ * A single invite entry with email and tier+ */+export interface InviteEntry {+ /** The email of the user to invite */+ email: string;+ /** The tier for this user (defaults to Haiku if not provided) */+ tier?: TeamUserTier;+}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/inviteToTeamRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/inviteToTeamRequest.tsindex 33259881ab..5179c9b135 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/inviteToTeamRequest.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/inviteToTeamRequest.ts@@ -4,11 +4,12 @@* authentication_service* OpenAPI spec version: 0.1.0*/+import type { InviteEntry } from './inviteEntry';/*** The request body to invite a user to a team*/export interface InviteToTeamRequest {- /** The emails of the users you want to invite to the team */- emails: string[];+ /** The invites to send, each with an email and tier */+ invites: InviteEntry[];}diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex ba2e3139d8..94bede14c2 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -3464,17 +3464,32 @@}}},+ "InviteEntry": {+ "type": "object",+ "description": "A single invite entry with email and tier",+ "required": ["email"],+ "properties": {+ "email": {+ "type": "string",+ "description": "The email of the user to invite"+ },+ "tier": {+ "$ref": "#/components/schemas/TeamUserTier",+ "description": "The tier for this user (defaults to Haiku if not provided)"+ }+ }+ },"InviteToTeamRequest": {"type": "object","description": "The request body to invite a user to a team",- "required": ["emails"],+ "required": ["invites"],"properties": {- "emails": {+ "invites": {"type": "array","items": {- "type": "string"+ "$ref": "#/components/schemas/InviteEntry"},- "description": "The emails of the users you want to invite to the team"+ "description": "The invites to send, each with an email and tier"}}},diff --git a/rust/cloud-storage/.sqlx/query-135a74cbd3480afc65012e82671f258a103985e6d52efd23886669872d9cf26a.json b/rust/cloud-storage/.sqlx/query-135a74cbd3480afc65012e82671f258a103985e6d52efd23886669872d9cf26a.jsonnew file mode 100644index 0000000000..f677d3af24--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-135a74cbd3480afc65012e82671f258a103985e6d52efd23886669872d9cf26a.json@@ -0,0 +1,69 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at, tier)\n SELECT\n t.id,\n $1::uuid,\n t.email,\n $2,\n $3::text,\n NOW(),\n NOW(),\n t.tier\n FROM UNNEST($4::uuid[], $5::text[], $6::text[], $7::\"team_user_tier\"[]) AS t(id, email, user_id, tier)\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 RETURNING id, team_id, email\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "email",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ {+ "Custom": {+ "name": "team_role",+ "kind": {+ "Enum": [+ "member",+ "admin",+ "owner"+ ]+ }+ }+ },+ "Text",+ "UuidArray",+ "TextArray",+ "TextArray",+ {+ "Custom": {+ "name": "team_user_tier[]",+ "kind": {+ "Array": {+ "Custom": {+ "name": "team_user_tier",+ "kind": {+ "Enum": [+ "haiku",+ "sonnet",+ "opus"+ ]+ }+ }+ }+ }+ }+ }+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "135a74cbd3480afc65012e82671f258a103985e6d52efd23886669872d9cf26a"+}diff --git a/rust/cloud-storage/.sqlx/query-bf8718d9bd46c2640cdd32ef2b2b2a0cf9a01f27f82076efe47059029af0d753.json b/rust/cloud-storage/.sqlx/query-bf8718d9bd46c2640cdd32ef2b2b2a0cf9a01f27f82076efe47059029af0d753.jsondeleted file mode 100644index 3fda14317e..0000000000--- a/rust/cloud-storage/.sqlx/query-bf8718d9bd46c2640cdd32ef2b2b2a0cf9a01f27f82076efe47059029af0d753.json+++ /dev/null@@ -1,50 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at)\n SELECT \n t.id,\n $1::uuid,\n t.email,\n $2,\n $3::text,\n NOW(),\n NOW()\n FROM UNNEST($4::uuid[], $5::text[], $6::text[]) AS t(id, email, user_id)\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 RETURNING id, team_id, email\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "email",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- {- "Custom": {- "name": "team_role",- "kind": {- "Enum": [- "member",- "admin",- "owner"- ]- }- }- },- "Text",- "UuidArray",- "TextArray",- "TextArray"- ]- },- "nullable": [- false,- false,- false- ]- },- "hash": "bf8718d9bd46c2640cdd32ef2b2b2a0cf9a01f27f82076efe47059029af0d753"-}diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rsindex 8c467564f9..1d9fd8f8e7 100644--- a/rust/cloud-storage/teams/src/domain/model.rs+++ b/rust/cloud-storage/teams/src/domain/model.rs@@ -17,6 +17,7 @@ use roles_and_permissions::domain::model::{RoleId, UserRolesAndPermissionsError}std::cmp::Ord,serde::Serialize,serde::Deserialize,+ Default,)]#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]#[cfg_attr(feature = "outbound", derive(sqlx::Type))]@@ -26,6 +27,7 @@ use roles_and_permissions::domain::model::{RoleId, UserRolesAndPermissionsError})]/// Ordered from lowest to highest tier top -> bottompub enum TeamUserTier {+ #[default]/// HaikuHaiku,/// Sonnet,diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rsindex 29a19b9f54..d591dc454a 100644--- a/rust/cloud-storage/teams/src/domain/team_repo.rs+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs@@ -57,7 +57,7 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {&self,team_id: &uuid::Uuid,invited_by: &MacroUserIdStr<'_>,- emails: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ invites: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;/// Marks the given team invites as sent by updating their last_sent_at timestamp.@@ -233,7 +233,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {&self,team_id: &uuid::Uuid,invited_by: &MacroUserIdStr<'_>,- emails: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ invites: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;/// Remove user from a team.diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rsindex a5b1fc0828..561554d674 100644--- a/rust/cloud-storage/teams/src/domain/team_service.rs+++ b/rust/cloud-storage/teams/src/domain/team_service.rs@@ -318,11 +318,11 @@ where&self,team_id: &uuid::Uuid,invited_by: &MacroUserIdStr<'_>,- emails: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ invites: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {let invited = self.team_repository- .invite_users_to_team(team_id, invited_by, emails)+ .invite_users_to_team(team_id, invited_by, invites).await?;// Send notifications for new invitesdiff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rsindex 40b5edbdcc..8c3e7869bf 100644--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs@@ -137,7 +137,7 @@ impl TeamRepository for MockTeamRepository {&self,_: &uuid::Uuid,_: &MacroUserIdStr<'_>,- _: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ _: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send {let invites = self.invites_to_return.clone();async move { Ok(invites) }@@ -761,21 +761,30 @@ async fn test_invite_marks_sent_only_for_successful_notifications() {build_service(invites, fail_indices, mark_sent_calls.clone());let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();- let emails = vec![- Email::parse_from_str("[email protected]")- .unwrap()- .lowercase(),- Email::parse_from_str("[email protected]")- .unwrap()- .lowercase(),- Email::parse_from_str("[email protected]")- .unwrap()- .lowercase(),+ let invites = vec![+ (+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ TeamUserTier::Haiku,+ ),+ (+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ TeamUserTier::Haiku,+ ),+ (+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ TeamUserTier::Haiku,+ ),];- let emails = non_empty::NonEmpty::new(emails.as_slice()).unwrap();+ let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();let result = service- .invite_users_to_team(&team_id, &invited_by, emails)+ .invite_users_to_team(&team_id, &invited_by, invites).await.unwrap();@@ -808,15 +817,16 @@ async fn test_invite_does_not_call_mark_sent_when_all_notifications_fail() {build_service(invites, fail_indices, mark_sent_calls.clone());let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();- let emails = vec![+ let invites = vec![(Email::parse_from_str("[email protected]").unwrap().lowercase(),- ];- let emails = non_empty::NonEmpty::new(emails.as_slice()).unwrap();+ TeamUserTier::Haiku,+ )];+ let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();service- .invite_users_to_team(&team_id, &invited_by, emails)+ .invite_users_to_team(&team_id, &invited_by, invites).await.unwrap();@@ -845,18 +855,24 @@ async fn test_invite_marks_all_sent_when_all_notifications_succeed() {);let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();- let emails = vec![- Email::parse_from_str("[email protected]")- .unwrap()- .lowercase(),- Email::parse_from_str("[email protected]")- .unwrap()- .lowercase(),+ let invites = vec![+ (+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ TeamUserTier::Haiku,+ ),+ (+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ TeamUserTier::Haiku,+ ),];- let emails = non_empty::NonEmpty::new(emails.as_slice()).unwrap();+ let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();service- .invite_users_to_team(&team_id, &invited_by, emails)+ .invite_users_to_team(&team_id, &invited_by, invites).await.unwrap();diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rsindex 33afe23086..4974c08356 100644--- a/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs+++ b/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs@@ -7,15 +7,28 @@ use macro_user_id::{email::Email, lowercased::Lowercase};use model_error_response::ErrorResponse;use model_user::axum_extractor::MacroUserExtractor;-use crate::domain::{model::InviteUsersToTeamError, team_repo::TeamService};+use crate::domain::{+ model::{InviteUsersToTeamError, TeamUserTier},+ team_repo::TeamService,+};use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};+/// A single invite entry with email and tier+#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema, Clone)]+pub struct InviteEntry {+ /// The email of the user to invite+ pub email: String,+ /// The tier for this user (defaults to Haiku if not provided)+ #[serde(default)]+ pub tier: TeamUserTier,+}+/// The request body to invite a user to a team#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]pub struct InviteToTeamRequest {- /// The emails of the users you want to invite to the team- pub emails: Vec<String>,+ /// The invites to send, each with an email and tier+ pub invites: Vec<InviteEntry>,}/// Error type for the invite to team handler@@ -92,24 +105,26 @@ pub async fn handler<T: TeamService>(Path(TeamPathParam { team_id }): Path<TeamPathParam>,Json(req): Json<InviteToTeamRequest>,) -> Result<StatusCode, InviteToTeamError> {- let emails: Vec<Result<Email<Lowercase<'_>>, _>> = req- .emails+ let parsed: Vec<Result<(Email<Lowercase<'_>>, TeamUserTier), _>> = req+ .invites.iter()- .map(|email| Email::parse_from_str(email).map(|email| email.lowercase()))+ .map(|entry| {+ Email::parse_from_str(&entry.email).map(|email| (email.lowercase(), entry.tier))+ }).collect();- if emails.iter().any(|e| e.is_err()) {+ if parsed.iter().any(|e| e.is_err()) {return Err(InviteToTeamError::InvalidEmails);}- let emails = emails.into_iter().map(|e| e.unwrap()).collect::<Vec<_>>();+ let invites: Vec<_> = parsed.into_iter().map(|e| e.unwrap()).collect();- let emails = non_empty::NonEmpty::new(emails.as_slice())+ let invites = non_empty::NonEmpty::new(invites.as_slice()).map_err(|_| InviteToTeamError::NoValidEmailsProvided)?;let team_invites = state.service- .invite_users_to_team(&team_id, &user_context.macro_user_id, emails)+ .invite_users_to_team(&team_id, &user_context.macro_user_id, invites).await.map_err(InviteToTeamError::InviteUsersToTeamError)?;diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rsindex 3e31e1f5ad..19aef4637e 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs@@ -246,18 +246,21 @@ impl TeamRepository for TeamRepositoryImpl {&self,team_id: &uuid::Uuid,invited_by: &MacroUserIdStr<'_>,- emails: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ invites: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {- // Convert emails to strings and macro_user_ids once- let email_strings: Vec<String> = emails.iter().map(|e| e.as_ref().to_string()).collect();+ let email_strings: Vec<String> = invites+ .iter()+ .map(|(email, _)| email.as_ref().to_string())+ .collect();- let macro_user_ids: Vec<String> = emails+ let macro_user_ids: Vec<String> = invites.iter()- .map(|email| format!("macro|{}", email.as_ref()))+ .map(|(email, _)| format!("macro|{}", email.as_ref())).collect();- // Generate UUIDs for all emails upfront- let team_invite_ids: Vec<uuid::Uuid> = emails+ let tiers: Vec<TeamUserTier> = invites.iter().map(|(_, tier)| *tier).collect();++ let team_invite_ids: Vec<uuid::Uuid> = invites.iter().map(|_| macro_uuid::generate_uuid_v7()).collect();@@ -265,24 +268,25 @@ impl TeamRepository for TeamRepositoryImpl {let mut transaction = self.pool.begin().await?;// Single query that filters out both already invited AND already on team- let invites: Vec<(uuid::Uuid, uuid::Uuid, String)> = sqlx::query!(+ let created_invites: Vec<(uuid::Uuid, uuid::Uuid, String)> = sqlx::query!(r#"- INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at)- SELECT+ INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at, tier)+ SELECTt.id,$1::uuid,t.email,$2,$3::text,NOW(),- NOW()- FROM UNNEST($4::uuid[], $5::text[], $6::text[]) AS t(id, email, user_id)+ NOW(),+ t.tier+ FROM UNNEST($4::uuid[], $5::text[], $6::text[], $7::"team_user_tier"[]) AS t(id, email, user_id, tier)WHERE NOT EXISTS (- SELECT 1 FROM team_invite ti+ SELECT 1 FROM team_invite tiWHERE ti.team_id = $1 AND ti.email = t.email)AND NOT EXISTS (- SELECT 1 FROM team_user tu+ SELECT 1 FROM team_user tuWHERE tu.team_id = $1 AND tu.user_id = t.user_id)RETURNING id, team_id, email@@ -292,7 +296,8 @@ impl TeamRepository for TeamRepositoryImpl {invited_by.as_ref(),&team_invite_ids[..],&email_strings[..],- ¯o_user_ids[..]+ ¯o_user_ids[..],+ &tiers[..] as _).map(|r| (r.id, r.team_id, r.email)).fetch_all(&mut *transaction)@@ -326,7 +331,7 @@ impl TeamRepository for TeamRepositoryImpl {};// Combine new invites and resent invites- let all_invites: Vec<TeamInvite<'static>> = invites+ let all_invites: Vec<TeamInvite<'static>> = created_invites.into_iter().chain(resent_invites).filter_map(|(id, team_id, email)| to_email(id, team_id, email))diff --git a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs b/rust/cloud-storage/teams/src/outbound/team_repo/test.rsindex 3c79c03489..7c82310fce 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs@@ -107,7 +107,10 @@ async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;- let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = vec![(+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ )];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo@@ -118,8 +121,14 @@ async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {assert_eq!(invited[0].email.as_ref(), "[email protected]");let invites = vec![- Email::parse_from_str("[email protected]")?.lowercase(),- Email::parse_from_str("[email protected]")?.lowercase(),+ (+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ ),+ (+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ ),];let invites = non_empty::NonEmpty::new(invites.as_slice())?;@@ -132,6 +141,59 @@ async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {Ok(())}+/// Inviting users with different tiers stores each tier correctly.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_invite_stores_tier(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ let invites = vec![+ (+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Opus,+ ),+ (+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Sonnet,+ ),+ ];+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;++ let invited = team_repo+ .invite_users_to_team(&team_id, &user_id, invites)+ .await?;++ assert_eq!(invited.len(), 2);++ let opus_row = sqlx::query!(+ r#"+ SELECT tier as "tier!: TeamUserTier"+ FROM team_invite+ WHERE email = '[email protected]'+ "#,+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(opus_row.tier, TeamUserTier::Opus);++ let sonnet_row = sqlx::query!(+ r#"+ SELECT tier as "tier!: TeamUserTier"+ FROM team_invite+ WHERE email = '[email protected]'+ "#,+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(sonnet_row.tier, TeamUserTier::Sonnet);++ 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(@@ -144,7 +206,10 @@ async fn test_invite_existing_user_within_rate_limit(pool: Pool<Postgres>) -> anlet team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;// [email protected] already has an invite with last_sent_at = NOW() in the fixture- let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = vec![(+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ )];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo@@ -176,7 +241,10 @@ async fn test_invite_existing_user_after_rate_limit(pool: Pool<Postgres>) -> any.execute(&pool).await?;- let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = vec![(+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ )];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo@@ -209,8 +277,14 @@ async fn test_invite_mix_new_and_existing(pool: Pool<Postgres>) -> anyhow::Resul.await?;let invites = vec![- Email::parse_from_str("[email protected]")?.lowercase(),- Email::parse_from_str("[email protected]")?.lowercase(),+ (+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ ),+ (+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ ),];let invites = non_empty::NonEmpty::new(invites.as_slice())?;@@ -247,7 +321,10 @@ async fn test_reinvite_updates_last_sent_at(pool: Pool<Postgres>) -> anyhow::Res.await?;// First re-invite should succeed- let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = vec![(+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ )];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo.invite_users_to_team(&team_id, &user_id, invites)@@ -259,7 +336,10 @@ async fn test_reinvite_updates_last_sent_at(pool: Pool<Postgres>) -> anyhow::Resteam_repo.mark_invites_sent(&sent_ids).await?;// Second immediate re-invite should be rate limited- let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = vec![(+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ )];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo.invite_users_to_team(&team_id, &user_id, invites)@@ -289,7 +369,10 @@ async fn test_resend_without_mark_sent_stays_eligible(pool: Pool<Postgres>) -> a.await?;// First re-invite returns the invite- let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = vec![(+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ )];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo.invite_users_to_team(&team_id, &user_id, invites)@@ -299,7 +382,10 @@ async fn test_resend_without_mark_sent_stays_eligible(pool: Pool<Postgres>) -> a// Do NOT call mark_invites_sent (simulating failed notification delivery)// Second re-invite should still return the invite because last_sent_at was not updated- let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = vec![(+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ )];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo.invite_users_to_team(&team_id, &user_id, invites)@@ -349,7 +435,10 @@ async fn test_mark_invites_sent(pool: Pool<Postgres>) -> anyhow::Result<()> {// The invite should now be rate limitedlet user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;- let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = vec![(+ Email::parse_from_str("[email protected]")?.lowercase(),+ TeamUserTier::Haiku,+ )];let invites = non_empty::NonEmpty::new(invites.as_slice())?;let invited = team_repo.invite_users_to_team(&team_id, &user_id, invites)