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): free teams up to 5 members, member invites, auto-join domain by default (#4994)
Jacob Beckerman59f4336ad5e3
diff --git a/apps/web/src/features/settings/Team.tsx b/apps/web/src/features/settings/Team.tsxindex 27807535fc..7ed91e3c60 100644--- a/apps/web/src/features/settings/Team.tsx+++ b/apps/web/src/features/settings/Team.tsx@@ -1,7 +1,4 @@-import { useFeatureFlag } from '@app/lib/analytics/posthog';-import { useHasPaidAccess } from '@core/auth/license';import { UserIcon } from '@core/component/UserIcon';-import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';import { SERVER_HOSTS } from '@core/constant/servers';import { useUserId } from '@core/context/user';import { macroIdToEmail, tryMacroId, useDisplayName } from '@core/user';@@ -72,12 +69,6 @@ import {} from './teamMemberPermissions';import { getTeamSlugError, normalizeTeamSlugInput } from './teamSlug';-function useRequiresPaidUpgrade() {- const hasPaidAccess = useHasPaidAccess();- const newPricingFlag = useFeatureFlag('enable-new-pricing');- return createMemo(() => newPricingFlag().enabled && !hasPaidAccess());-}-const roleOrder: Record<string, number> = {[TeamRole.owner]: 0,[TeamRole.admin]: 1,@@ -469,8 +460,6 @@ function UserInviteRow(props: {onDecline: () => void;isAccepting: boolean;isDeclining: boolean;- requiresUpgrade: boolean;- onUpgrade: () => void;}) {return (<div class="flex items-center justify-between gap-3 px-6 py-3 bg-surface">@@ -516,8 +505,6 @@ function TeamInvites() {const userInvitesQuery = useUserInvitesQuery();const joinTeamMutation = useJoinTeamMutation();const rejectMutation = useRejectInvitationMutation();- const requiresUpgrade = useRequiresPaidUpgrade();- const { showPaywall } = usePaywallState();const invites = () => userInvitesQuery.data?.invites ?? [];@@ -548,8 +535,6 @@ function TeamInvites() {}isAccepting={isAccepting(invite.id)}isDeclining={isDeclining(invite.id)}- requiresUpgrade={requiresUpgrade()}- onUpgrade={() => showPaywall()}/>)}</For>@@ -584,7 +569,6 @@ function CreateTeamDialog(props: { open: boolean; onClose: () => void }) {);const createTeamMutation = useCreateTeamWithInvitesMutation();- const requiresUpgrade = useRequiresPaidUpgrade();const charCountColor = () => {const len = teamName().trim().length;@@ -681,19 +665,17 @@ function CreateTeamDialog(props: { open: boolean; onClose: () => void }) {<p class="text-xs text-failure-ink">{teamNameError()}</p></Show></div>- <Show when={!requiresUpgrade()}>- <div class="flex flex-col gap-1">- <label class="text-sm text-ink-muted">- Invite members (optional)- </label>- <InviteEmailsInput- invites={invites()}- onChange={setInvites}- errors={inviteErrors()}- onErrorsChange={setInviteErrors}- />- </div>- </Show>+ <div class="flex flex-col gap-1">+ <label class="text-sm text-ink-muted">+ Invite members (optional)+ </label>+ <InviteEmailsInput+ invites={invites()}+ onChange={setInvites}+ errors={inviteErrors()}+ onErrorsChange={setInviteErrors}+ />+ </div><div class="flex justify-end gap-1 pt-2"><Buttonvariant="ghost"@@ -726,8 +708,6 @@ function CreateTeamDialog(props: { open: boolean; onClose: () => void }) {function EmptyTeamState() {const [showCreateModal, setShowCreateModal] = createSignal(false);- const hasPaidAccess = useHasPaidAccess();- const { showPaywall } = usePaywallState();return (<SettingsPage title="Team">@@ -738,37 +718,18 @@ function EmptyTeamState() {<UsersIcon class="size-6 text-accent" /></div><h3 class="text-sm font-medium text-ink mb-1">No team yet</h3>- <Show- when={hasPaidAccess()}- fallback={- <>- <p class="text-xs text-ink-muted max-w-xs mb-4">- Teams are available on paid plans. Upgrade to create and- manage teams.- </p>- <Button- variant="active"- class="rounded-xs"- onClick={() => showPaywall(PaywallKey.TEAMS)}- >- Upgrade- </Button>- </>- }+ <p class="text-xs text-ink-muted max-w-xs mb-4">+ Create a team to collaborate with others and manage access+ together.+ </p>+ <Button+ variant="active"+ class="rounded-xs"+ onClick={() => setShowCreateModal(true)}>- <p class="text-xs text-ink-muted max-w-xs mb-4">- Create a team to collaborate with others and manage access- together.- </p>- <Button- variant="active"- class="rounded-xs"- onClick={() => setShowCreateModal(true)}- >- <PlusIcon class="size-4" />- Create Team- </Button>- </Show>+ <PlusIcon class="size-4" />+ Create Team+ </Button></div></SettingsCard></SettingsSection>@@ -858,8 +819,6 @@ function TeamManagement(props: {const inviteToTeamMutation = useInviteToTeamMutation();const deleteTeamMutation = useDeleteTeamMutation();const toggleAutoJoinMutation = useToggleAutoJoinDomainMutation();- const requiresUpgrade = useRequiresPaidUpgrade();- const { showPaywall } = usePaywallState();const [showDeleteTeamModal, setShowDeleteTeamModal] = createSignal(false);const [deleteConfirmation, setDeleteConfirmation] = createSignal('');@@ -1303,24 +1262,16 @@ function TeamManagement(props: {<SettingsSectiontitle="Members"actions={- <Show when={canManageMemberRemovals()}>- <Button- variant="base"- size="sm"- class="rounded-xs"- tooltip={- requiresUpgrade()- ? 'Inviting members requires a paid plan'- : undefined- }- onClick={() =>- requiresUpgrade() ? showPaywall() : setShowInviteModal(true)- }- >- <PlusIcon class="size-4" />- Invite- </Button>- </Show>+ // Any team member can invite; removals stay admin-only.+ <Button+ variant="base"+ size="sm"+ class="rounded-xs"+ onClick={() => setShowInviteModal(true)}+ >+ <PlusIcon class="size-4" />+ Invite+ </Button>}><Show when={showMemberSearch()}>diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rsindex 6d2c8f9c76..c001e2eb20 100644--- a/crates/teams/src/domain/model.rs+++ b/crates/teams/src/domain/model.rs@@ -51,6 +51,11 @@ impl TeamPlan {}}+/// Maximum number of members (including the owner) a team may have without a+/// Stripe subscription. Teams at or under this size are free; growing past it+/// requires the owner to subscribe.+pub const FREE_TEAM_MAX_MEMBERS: i32 = 5;+#[derive(Eq,PartialEq,@@ -641,6 +646,9 @@ pub enum JoinTeamError {#[error("Underlying user roles and permissions error")]/// Underlying user roles and permissions errorAddRolesToUserError(#[from] UserRolesAndPermissionsError),+ /// The team has no subscription and is already at the free member limit+ #[error("Team is at the free member limit of {FREE_TEAM_MAX_MEMBERS}")]+ FreeTeamLimitReached,}/// Errors for toggling a team's auto-join domaindiff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rsindex c710799725..23042c3c5f 100644--- a/crates/teams/src/domain/team_repo.rs+++ b/crates/teams/src/domain/team_repo.rs@@ -64,12 +64,13 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {team_id: &uuid::Uuid,) -> impl Future<Output = Result<bool, TeamError>> + Send;- /// Creates a new team+ /// Creates a new team. `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,- subscription_id: &stripe::SubscriptionId,+ subscription_id: Option<&stripe::SubscriptionId>,) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;/// Moves any user-owned GitHub App installation rows to the given team.@@ -318,12 +319,13 @@ pub trait TeamMembersService: Clone + Send + Sync + 'static {/// The TeamService defines a set of actions to perform on the teamspub trait TeamService: Clone + Send + Sync + 'static {- /// Creates a new team+ /// Creates a new team. `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,- subscription_id: &stripe::SubscriptionId,+ subscription_id: Option<&stripe::SubscriptionId>,) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;/// Returns the user's active stripe subscription id when the user is premium.@@ -334,10 +336,11 @@ pub trait TeamService: Clone + Send + Sync + 'static {/// Invites users to a team/// This will also handle the teams subscription.+ /// Any team member may invite; removals stay admin-only./// Returns the team invites created.fn invite_users_to_team(&self,- entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,+ entity_access_receipt: EntityAccessReceipt<MemberTeamRole>,invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rsindex a3c7a2e4a7..fe049d9f3c 100644--- a/crates/teams/src/domain/team_service.rs+++ b/crates/teams/src/domain/team_service.rs@@ -5,12 +5,14 @@ mod test;use std::{collections::HashSet, sync::Arc};-use anyhow::Context;use entity_access::domain::models::{AdminTeamRole, EntityAccessReceipt, MemberTeamRole, OwnerTeamRole,};use macro_user_id::{- cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,+ cowlike::CowLike,+ email::{Email, ReadEmailParts},+ lowercased::Lowercase,+ user_id::MacroUserIdStr,};use roles_and_permissions::domain::{model::RoleId, port::UserRolesAndPermissionsService};@@ -26,12 +28,12 @@ use crate::domain::{crm_enqueuer::CrmEnqueuer,customer_repo::CustomerRepository,model::{- CreateTeamError, CustomerError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,- PatchTeamCrmSettingsResponse, PatchTeamRequest, RemoveTeamInviteError,- RemoveUserFromTeamError, RestorePermissionsForTeamMembersError,+ CreateTeamError, CustomerError, DeleteTeamError, FREE_TEAM_MAX_MEMBERS,+ InviteUsersToTeamError, JoinTeamError, PatchTeamCrmSettingsResponse, PatchTeamRequest,+ RemoveTeamInviteError, RemoveUserFromTeamError, RestorePermissionsForTeamMembersError,RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,TeamMember, TeamMembers, TeamRole, TeamWithMembers, ToggleAutoJoinDomainError,- TryJoinTeamByDomainError,+ TryJoinTeamByDomainError, is_generic_email_domain,},team_analytics::{NoOpTeamAnalytics, TeamAnalytics, TeamAnalyticsEvent},team_crm_settings_repo::TeamCrmSettingsRepository,@@ -289,62 +291,6 @@ where.ok();}- /// Gets the teams subscription id- /// If the team doesn't have a subscription yet, it will convert the owners personal subscription into a team subscription- #[tracing::instrument(skip(self), err)]- async fn get_team_subscription(- &self,- team_id: &uuid::Uuid,- ) -> Result<stripe::SubscriptionId, GetTeamSubscriptionError> {- let subscription_id = self- .team_repository- .get_team_subscription_id(team_id)- .await- .map_err(GetTeamSubscriptionError::Team)?;-- // stripe subscription is already tracked for team- if let Some(subscription_id) = subscription_id {- return Ok(subscription_id);- }-- tracing::info!("no subscription found for team");-- // Get the team to get owner- let team = self- .team_repository- .get_team_by_id(team_id)- .await- .map_err(GetTeamSubscriptionError::Team)?;-- let customer_id = self- .team_repository- .get_stripe_customer_id(&team.team.owner_id)- .await- .map_err(GetTeamSubscriptionError::Team)?- .context("expected customer id")?;-- let customer_subscription_id = self- .customer_repository- .get_subscription_id_for_customer(&customer_id)- .await- .map_err(GetTeamSubscriptionError::Customer)?;-- // Convert the customer's subscription to a team subscription before storing it locally,- // so a customer failure cannot leave a local subscription_id pointing at an unconverted- // personal subscription.- self.customer_repository- .convert_subscription_to_team(&customer_subscription_id, team_id, &team.team.owner_id)- .await- .map_err(GetTeamSubscriptionError::Customer)?;-- self.team_repository- .update_team_subscription(team_id, &customer_subscription_id)- .await- .map_err(GetTeamSubscriptionError::Team)?;-- Ok(customer_subscription_id)- }-/// Backfills legacy teams that were created without a team subscription id.#[tracing::instrument(skip(self), err)]async fn backfill_legacy_team_subscription(@@ -391,6 +337,23 @@ whereOk(())}+ /// Runs [`Self::backfill_legacy_team_subscription`], treating "the owner+ /// simply has no active subscription" as a benign outcome: the team is a+ /// free team (capped at [`FREE_TEAM_MAX_MEMBERS`]) rather than an error.+ /// Every other failure still propagates.+ async fn backfill_legacy_team_subscription_or_free(+ &self,+ team_id: &uuid::Uuid,+ ) -> Result<(), GetTeamSubscriptionError> {+ match self.backfill_legacy_team_subscription(team_id).await {+ Ok(()) => Ok(()),+ Err(GetTeamSubscriptionError::Customer(+ CustomerError::NoStripeCustomerId | CustomerError::SubscriptionNotActive,+ )) => Ok(()),+ Err(e) => Err(e),+ }+ }+/// Best-effort rollback of a direct team add (from/// `try_join_team_by_domain`): removes the membership again and undoes/// the team seat count bump. Failures are logged and swallowed, like@@ -469,14 +432,6 @@ impl GetTeamSubscriptionError {Self::Storage(e) => JoinTeamError::StorageLayerError(e),}}-- fn into_remove_user_from_team_error(self) -> RemoveUserFromTeamError {- match self {- Self::Team(e) => RemoveUserFromTeamError::TeamError(e),- Self::Customer(e) => RemoveUserFromTeamError::CustomerError(e),- Self::Storage(e) => RemoveUserFromTeamError::StorageLayerError(e),- }- }}impl<TR, CR, TCR, URPS, NI, CE, TCRMS, TA, CNE> TeamMembersService@@ -525,7 +480,7 @@ where&self,user_id: &MacroUserIdStr<'_>,team_name: &str,- subscription_id: &stripe::SubscriptionId,+ subscription_id: Option<&stripe::SubscriptionId>,) -> Result<Team, CreateTeamError> {// New teams start with `team_crm_settings.crm_enabled = false`// (seeded by `team_repository.create_team`), so there's nothing@@ -536,14 +491,29 @@ where.team_repository.create_team(user_id, team_name, subscription_id).await?;- self.customer_repository- .convert_subscription_to_team(subscription_id, team.id(), user_id)- .await- .map_err(|e| CreateTeamError::StorageLayerError(e.into()))?;+ if let Some(subscription_id) = subscription_id {+ self.customer_repository+ .convert_subscription_to_team(subscription_id, team.id(), user_id)+ .await+ .map_err(|e| CreateTeamError::StorageLayerError(e.into()))?;+ }self.team_repository.move_github_app_installation_to_team_if_exists(user_id, team.id()).await?;+ // Auto-join is on by default for corporate domains: colleagues who+ // sign up with the same domain are added to the team automatically.+ // Owners can turn it off in settings. Best-effort — creation+ // succeeds even if this fails.+ let owner_email = user_id.email_part().lowercase();+ if !is_generic_email_domain(owner_email.domain_part()) {+ self.team_repository+ .toggle_auto_join_domain(team.id())+ .await+ .inspect_err(|e| tracing::error!(error=?e, "unable to default auto-join domain on"))+ .ok();+ }+self.track_team_analytics_event(TeamAnalyticsEvent::TeamCreated {team_id: *team.id(),owner_id: user_id.clone().into_owned(),@@ -579,7 +549,7 @@ where#[tracing::instrument(skip(self), err)]async fn invite_users_to_team(&self,- entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,+ entity_access_receipt: EntityAccessReceipt<MemberTeamRole>,invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {let team_id =@@ -606,7 +576,7 @@ wherereturn Err(InviteUsersToTeamError::TeamError(TeamError::TeamNotPaying));}- self.backfill_legacy_team_subscription(&team_id)+ self.backfill_legacy_team_subscription_or_free(&team_id).await.map_err(GetTeamSubscriptionError::into_invite_users_to_team_error)?;}@@ -629,6 +599,19 @@ wherereturn Err(InviteUsersToTeamError::NotEnoughOpenSeats);}+ // Free teams (no subscription) are capped at FREE_TEAM_MAX_MEMBERS.+ if !enterprise+ && team_plan.is_none()+ && self+ .team_repository+ .get_team_subscription_id(&team_id)+ .await?+ .is_none()+ && seat_count + new_invites.len() as i32 > FREE_TEAM_MAX_MEMBERS+ {+ return Err(InviteUsersToTeamError::NotEnoughOpenSeats);+ }+let new_invite_emails: HashSet<String> = new_invites.iter().map(|email| email.as_ref().to_owned())@@ -728,7 +711,12 @@ wherelet subscription_id = if enterprise {None} else {- let subscription_id = match self.get_team_subscription(&team_id).await {+ // Free teams have no linked subscription — nothing to decrement.+ match self+ .team_repository+ .get_team_subscription_id(&team_id)+ .await+ {Ok(subscription_id) => subscription_id,Err(e) => {self.team_repository@@ -741,10 +729,9 @@ where);}).ok();- return Err(e.into_remove_user_from_team_error());+ return Err(RemoveUserFromTeamError::TeamError(e));}- };- Some(subscription_id)+ }};if let Some(subscription_id) = subscription_id.as_ref()@@ -1054,7 +1041,7 @@ where}if let Err(e) = self- .backfill_legacy_team_subscription(&accepted_invite.member.team_id)+ .backfill_legacy_team_subscription_or_free(&accepted_invite.member.team_id).await{self.team_repository@@ -1071,9 +1058,13 @@ where}}- let subscription_id = match self.get_team_subscription(&team_member.team_id).await {- Ok(subscription_id) => subscription_id,- Err(e) => {+ let team_subscription_id = match self+ .team_repository+ .get_team_subscription_id(&team_member.team_id)+ .await+ {+ Ok(team_subscription_id) => team_subscription_id,+ Err(error) => {self.team_repository.rollback_accept_team_invite(&accepted_invite).await@@ -1084,81 +1075,134 @@ where);}).ok();- return Err(e.into_join_team_error());+ return Err(JoinTeamError::TeamError(error));}};+ match team_subscription_id {+ // Free team: no seat billing, but the member count (which+ // already includes this newly accepted member) must stay+ // within the free limit.+ None => {+ let seat_count = match self+ .team_repository+ .get_team_seat_count(&team_member.team_id)+ .await+ {+ Ok(seat_count) => seat_count,+ Err(error) => {+ self.team_repository+ .rollback_accept_team_invite(&accepted_invite)+ .await+ .inspect_err(|rollback_err| {+ tracing::error!(+ error=?rollback_err,+ "unable to rollback accepted team invite after getting team seat count failed"+ );+ })+ .ok();+ return Err(JoinTeamError::TeamError(error));+ }+ };++ if seat_count > FREE_TEAM_MAX_MEMBERS {+ self.team_repository+ .rollback_accept_team_invite(&accepted_invite)+ .await+ .inspect_err(|rollback_err| {+ tracing::error!(+ error=?rollback_err,+ "unable to rollback accepted team invite after the free member limit check"+ );+ })+ .ok();+ return Err(JoinTeamError::FreeTeamLimitReached);+ }++ None+ }+ Some(subscription_id) => {+ if let Err(e) = self+ .customer_repository+ .increment_seat_count(&subscription_id, 1)+ .await+ {+ self.team_repository+ .rollback_accept_team_invite(&accepted_invite)+ .await+ .inspect_err(|rollback_err| {+ tracing::error!(+ error=?rollback_err,+ "unable to rollback accepted team invite after incrementing seat count failed"+ );+ })+ .ok();+ return Err(JoinTeamError::CustomerError(e));+ }++ Some(subscription_id)+ }+ }+ };++ // Premium roles come with a paid or enterprise team; free-team+ // members keep their existing (free) entitlements.+ let grants_premium = enterprise || subscription_id.is_some();+ let roles_to_add = vec![RoleId::TeamSubscriber, RoleId::SubOpus];++ if grants_premium {+ // subscribe the user to professional features from the TeamSubscriber role and the role associated with their tier+ let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();+if let Err(e) = self- .customer_repository- .increment_seat_count(&subscription_id, 1)+ .user_roles_and_permissions_service+ .dangerous_upsert_roles_for_user(user_id, roles).await{+ if let Some(subscription_id) = subscription_id.as_ref() {+ self.customer_repository+ .decrement_seat_count(subscription_id, 1)+ .await+ .inspect_err(|rollback_err| {+ tracing::error!(+ error=?rollback_err,+ "unable to rollback customer seat count after adding team member roles failed"+ );+ })+ .ok();+ }self.team_repository.rollback_accept_team_invite(&accepted_invite).await.inspect_err(|rollback_err| {tracing::error!(error=?rollback_err,- "unable to rollback accepted team invite after incrementing seat count failed"+ "unable to rollback accepted team invite after adding team member roles failed");}).ok();- return Err(JoinTeamError::CustomerError(e));+ return Err(JoinTeamError::AddRolesToUserError(e));}-- Some(subscription_id)- };-- // subscribe the user to professional features from the TeamSubscriber role and the role associated with their tier- let roles_to_add = vec![RoleId::TeamSubscriber, RoleId::SubOpus];- let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();+ }if let Err(e) = self- .user_roles_and_permissions_service- .dangerous_upsert_roles_for_user(user_id, roles)+ .team_channels_repository+ .add_team_member_to_channels(&team_member.team_id, user_id).await{- if let Some(subscription_id) = subscription_id.as_ref() {- self.customer_repository- .decrement_seat_count(subscription_id, 1)+ if grants_premium {+ let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();+ self.user_roles_and_permissions_service+ .dangerous_remove_roles_from_user(user_id, &roles).await.inspect_err(|rollback_err| {tracing::error!(error=?rollback_err,- "unable to rollback customer seat count after adding team member roles failed"+ "unable to rollback team member roles after adding team member to channels failed");}).ok();}- self.team_repository- .rollback_accept_team_invite(&accepted_invite)- .await- .inspect_err(|rollback_err| {- tracing::error!(- error=?rollback_err,- "unable to rollback accepted team invite after adding team member roles failed"- );- })- .ok();- return Err(JoinTeamError::AddRolesToUserError(e));- }-- if let Err(e) = self- .team_channels_repository- .add_team_member_to_channels(&team_member.team_id, user_id)- .await- {- let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();- self.user_roles_and_permissions_service- .dangerous_remove_roles_from_user(user_id, &roles)- .await- .inspect_err(|rollback_err| {- tracing::error!(- error=?rollback_err,- "unable to rollback team member roles after adding team member to channels failed"- );- })- .ok();if let Some(subscription_id) = subscription_id.as_ref() {self.customer_repository.decrement_seat_count(subscription_id, 1)@@ -1547,7 +1591,10 @@ wherereturn Err(JoinTeamError::TeamError(TeamError::TeamNotPaying).into());}- if let Err(e) = self.backfill_legacy_team_subscription(&team_id).await {+ if let Err(e) = self+ .backfill_legacy_team_subscription_or_free(&team_id)+ .await+ {self.rollback_add_user_to_team(&team_id,user_id,@@ -1558,70 +1605,122 @@ where}}- let subscription_id = match self.get_team_subscription(&team_id).await {- Ok(subscription_id) => subscription_id,- Err(e) => {+ let team_subscription_id = match self+ .team_repository+ .get_team_subscription_id(&team_id)+ .await+ {+ Ok(team_subscription_id) => team_subscription_id,+ Err(error) => {self.rollback_add_user_to_team(&team_id, user_id, "getting team subscription").await;- return Err(e.into_join_team_error().into());+ return Err(error.into());}};+ match team_subscription_id {+ // Free team: no seat billing. The member count (already+ // bumped by add_user_to_team) must stay within the free+ // limit — over the cap, skip the auto-join silently like+ // the plan seat-cap check above.+ None => {+ let seat_count = match self.team_repository.get_team_seat_count(&team_id).await+ {+ Ok(seat_count) => seat_count,+ Err(error) => {+ self.rollback_add_user_to_team(+ &team_id,+ user_id,+ "getting team seat count",+ )+ .await;+ return Err(error.into());+ }+ };++ if seat_count > FREE_TEAM_MAX_MEMBERS {+ tracing::info!(%team_id, %user_id, "skipping team auto-join: free team is at its member limit");+ self.rollback_add_user_to_team(+ &team_id,+ user_id,+ "the free member limit check",+ )+ .await;+ return Ok(None);+ }++ None+ }+ Some(subscription_id) => {+ if let Err(e) = self+ .customer_repository+ .increment_seat_count(&subscription_id, 1)+ .await+ {+ self.rollback_add_user_to_team(+ &team_id,+ user_id,+ "incrementing seat count",+ )+ .await;+ return Err(JoinTeamError::CustomerError(e).into());+ }++ Some(subscription_id)+ }+ }+ };++ // Premium roles come with a paid or enterprise team; free-team+ // members keep their existing (free) entitlements.+ let grants_premium = enterprise || subscription_id.is_some();+ let roles_to_add = vec![RoleId::TeamSubscriber, RoleId::SubOpus];++ if grants_premium {+ // subscribe the user to professional features from the TeamSubscriber role and the role associated with their tier+ let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();+if let Err(e) = self- .customer_repository- .increment_seat_count(&subscription_id, 1)+ .user_roles_and_permissions_service+ .dangerous_upsert_roles_for_user(user_id, roles).await{- self.rollback_add_user_to_team(&team_id, user_id, "incrementing seat count")+ if let Some(subscription_id) = subscription_id.as_ref() {+ self.customer_repository+ .decrement_seat_count(subscription_id, 1)+ .await+ .inspect_err(|rollback_err| {+ tracing::error!(+ error=?rollback_err,+ "unable to rollback customer seat count after adding team member roles failed"+ );+ })+ .ok();+ }+ self.rollback_add_user_to_team(&team_id, user_id, "adding team member roles").await;- return Err(JoinTeamError::CustomerError(e).into());+ return Err(JoinTeamError::AddRolesToUserError(e).into());}-- Some(subscription_id)- };-- // subscribe the user to professional features from the TeamSubscriber role and the role associated with their tier- let roles_to_add = vec![RoleId::TeamSubscriber, RoleId::SubOpus];- let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();+ }if let Err(e) = self- .user_roles_and_permissions_service- .dangerous_upsert_roles_for_user(user_id, roles)+ .team_channels_repository+ .add_team_member_to_channels(&team_id, user_id).await{- if let Some(subscription_id) = subscription_id.as_ref() {- self.customer_repository- .decrement_seat_count(subscription_id, 1)+ if grants_premium {+ let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();+ self.user_roles_and_permissions_service+ .dangerous_remove_roles_from_user(user_id, &roles).await.inspect_err(|rollback_err| {tracing::error!(error=?rollback_err,- "unable to rollback customer seat count after adding team member roles failed"+ "unable to rollback team member roles after adding team member to channels failed");}).ok();}- self.rollback_add_user_to_team(&team_id, user_id, "adding team member roles")- .await;- return Err(JoinTeamError::AddRolesToUserError(e).into());- }-- if let Err(e) = self- .team_channels_repository- .add_team_member_to_channels(&team_id, user_id)- .await- {- let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();- self.user_roles_and_permissions_service- .dangerous_remove_roles_from_user(user_id, &roles)- .await- .inspect_err(|rollback_err| {- tracing::error!(- error=?rollback_err,- "unable to rollback team member roles after adding team member to channels failed"- );- })- .ok();if let Some(subscription_id) = subscription_id.as_ref() {self.customer_repository.decrement_seat_count(subscription_id, 1)diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rsindex fb03948256..ba2815f03f 100644--- a/crates/teams/src/domain/team_service/test.rs+++ b/crates/teams/src/domain/team_service/test.rs@@ -93,6 +93,7 @@ struct MockTeamRepository {add_user_to_team_result: Option<TeamMember<'static>>,add_user_to_team_calls: Arc<Mutex<usize>>,remove_user_calls: Arc<Mutex<usize>>,+ auto_join_toggle_calls: Arc<Mutex<Vec<uuid::Uuid>>>,}impl MockTeamRepository {@@ -150,6 +151,7 @@ impl MockTeamRepository {add_user_to_team_result: None,add_user_to_team_calls: Arc::new(Mutex::new(0)),remove_user_calls: Arc::new(Mutex::new(0)),+ auto_join_toggle_calls: Arc::new(Mutex::new(Vec::new())),}}@@ -249,7 +251,7 @@ impl TeamRepository for MockTeamRepository {&self,_: &MacroUserIdStr<'_>,_: &str,- _: &stripe::SubscriptionId,+ _: Option<&stripe::SubscriptionId>,) -> impl Future<Output = Result<Team, CreateTeamError>> + Send {let team = self.created_team.clone();async move { Ok(team) }@@ -563,9 +565,10 @@ impl TeamRepository for MockTeamRepository {fn toggle_auto_join_domain(&self,- _: &uuid::Uuid,+ team_id: &uuid::Uuid,) -> impl Future<Output = Result<Option<String>, ToggleAutoJoinDomainError>> + Send {- async { unimplemented!() }+ self.auto_join_toggle_calls.lock().unwrap().push(*team_id);+ async { Ok(Some("example.com".to_string())) }}fn get_team_id_by_domain(@@ -1327,7 +1330,7 @@ async fn test_create_team_moves_github_installation_to_created_team() {);let created_team = service- .create_team(&user_id, "New Team", &"sub_test".parse().unwrap())+ .create_team(&user_id, "New Team", Some(&"sub_test".parse().unwrap())).await.unwrap();@@ -1366,7 +1369,7 @@ async fn test_create_team_propagates_github_installation_move_failure() {);let err = service- .create_team(&user_id, "New Team", &"sub_test".parse().unwrap())+ .create_team(&user_id, "New Team", Some(&"sub_test".parse().unwrap())).await.err().unwrap();@@ -1404,7 +1407,11 @@ async fn team_analytics_create_team_emits_created_event_with_team_id() {);service- .create_team(&user_id, "Analytics Team", &"sub_test".parse().unwrap())+ .create_team(+ &user_id,+ "Analytics Team",+ Some(&"sub_test".parse().unwrap()),+ ).await.unwrap();@@ -1450,7 +1457,11 @@ async fn team_analytics_failure_is_swallowed_by_create_team() {);let result = service- .create_team(&user_id, "Analytics Team", &"sub_test".parse().unwrap())+ .create_team(+ &user_id,+ "Analytics Team",+ Some(&"sub_test".parse().unwrap()),+ ).await;assert!(result.is_ok());@@ -1483,7 +1494,11 @@ async fn team_analytics_create_team_does_not_emit_when_side_effect_fails() {);let err = service- .create_team(&user_id, "Analytics Team", &"sub_test".parse().unwrap())+ .create_team(+ &user_id,+ "Analytics Team",+ Some(&"sub_test".parse().unwrap()),+ ).await.err().unwrap();@@ -1588,7 +1603,7 @@ async fn invite_users_to_team_enterprise_bypasses_billing_and_preserves_side_eff.lowercase(),];let invites = non_empty::NonEmpty::new(invite_emails.as_slice()).unwrap();- let receipt = test_team_receipt::<AdminTeamRole>(team_id, &invited_by);+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let result = service.invite_users_to_team(receipt, invites)@@ -1670,7 +1685,7 @@ async fn invite_users_to_team_enterprise_enforces_team_plan_seat_cap() {.lowercase(),];let invites = non_empty::NonEmpty::new(invite_emails.as_slice()).unwrap();- let receipt = test_team_receipt::<AdminTeamRole>(team_id, &invited_by);+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let error = service.invite_users_to_team(receipt, invites)@@ -1718,7 +1733,7 @@ async fn invite_users_to_team_enterprise_status_lookup_failure_precedes_persiste.lowercase(),];let invites = non_empty::NonEmpty::new(invite_emails.as_slice()).unwrap();- let receipt = test_team_receipt::<AdminTeamRole>(team_id, &invited_by);+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let error = service.invite_users_to_team(receipt, invites)@@ -1770,7 +1785,7 @@ async fn test_invite_marks_sent_only_for_successful_notifications() {];let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();- let receipt = test_team_receipt::<AdminTeamRole>(team_id, &invited_by);+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let result = service.invite_users_to_team(receipt, invites).await@@ -1812,7 +1827,7 @@ async fn test_invite_does_not_call_mark_sent_when_all_notifications_fail() {];let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();- let receipt = test_team_receipt::<AdminTeamRole>(team_id, &invited_by);+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);service.invite_users_to_team(receipt, invites).await@@ -1853,7 +1868,7 @@ async fn test_invite_marks_all_sent_when_all_notifications_succeed() {];let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();- let receipt = test_team_receipt::<AdminTeamRole>(team_id, &invited_by);+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);service.invite_users_to_team(receipt, invites).await@@ -1897,7 +1912,7 @@ async fn team_analytics_invite_users_emits_invited_events_with_team_id() {.lowercase(),];let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();- let receipt = test_team_receipt::<AdminTeamRole>(team_id, &invited_by);+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);service.invite_users_to_team(receipt, invites)@@ -1951,7 +1966,7 @@ async fn team_analytics_invite_users_does_not_emit_when_invite_creation_fails().lowercase(),];let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();- let receipt = test_team_receipt::<AdminTeamRole>(team_id, &invited_by);+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);let err = service.invite_users_to_team(receipt, invites)@@ -2361,7 +2376,7 @@ async fn test_invite_users_to_team_backfills_legacy_team_subscription() {.lowercase(),];let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();- let receipt = test_team_receipt::<AdminTeamRole>(team_id, &owner_id);+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &owner_id);service.invite_users_to_team(receipt, invites)@@ -2696,6 +2711,43 @@ async fn test_join_team_backfills_legacy_team_subscription() {async fn test_join_team_rolls_back_accept_when_backfill_fails() {let team_id = uuid::Uuid::from_u128(44);let invite_id = uuid::Uuid::from_u128(440);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));+ // No `.with_team(...)`: the backfill's team lookup fails hard, which —+ // unlike the owner simply having no subscription — must still roll the+ // accepted invite back.+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Legacy Team", mark_sent_calls);+ team_repo.team_payment_status = false;+ team_repo.team_subscription_id = None;+ team_repo.stripe_customer_id = Some("cus_backfill_join".parse().unwrap());+ team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));+ let rollback_accept_calls = team_repo.rollback_accept_calls.clone();++ let customer_repo = MockCustomerRepository::default();+ let increment_calls = customer_repo.increment_calls.clone();++ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let err = service.join_team(&invite_id, &user_id).await.err().unwrap();++ assert!(matches!(err, JoinTeamError::TeamError(_)));+ assert_eq!(*rollback_accept_calls.lock().unwrap(), 1);+ assert!(increment_calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn test_join_team_owner_without_subscription_joins_as_free_team() {+ let team_id = uuid::Uuid::from_u128(48);+ let invite_id = uuid::Uuid::from_u128(480);let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();@@ -2709,9 +2761,12 @@ async fn test_join_team_rolls_back_accept_when_backfill_fails() {false,false,));+ // Legacy team whose owner has no active subscription: joining now+ // degrades to a free team instead of failing.team_repo.team_payment_status = false;team_repo.team_subscription_id = None;team_repo.stripe_customer_id = Some("cus_backfill_join".parse().unwrap());+ team_repo.seat_count = FREE_TEAM_MAX_MEMBERS;team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));let rollback_accept_calls = team_repo.rollback_accept_calls.clone();@@ -2720,22 +2775,24 @@ async fn test_join_team_rolls_back_accept_when_backfill_fails() {..Default::default()};let increment_calls = customer_repo.increment_calls.clone();+ let roles_service = MockUserRolesAndPermissionsService::default();let service = TeamServiceImpl::new(team_repo,customer_repo,MockTeamChannelsRepository::default(),- MockUserRolesAndPermissionsService::default(),+ roles_service.clone(),Arc::new(MockNotificationIngress::new(HashSet::new())),NoOpCrmEnqueuer,NoOpTeamCrmSettingsRepository,);- let err = service.join_team(&invite_id, &user_id).await.err().unwrap();+ let member = service.join_team(&invite_id, &user_id).await.unwrap();- assert!(matches!(err, JoinTeamError::CustomerError(_)));- assert_eq!(*rollback_accept_calls.lock().unwrap(), 1);+ assert_eq!(member.team_id, team_id);+ assert_eq!(*rollback_accept_calls.lock().unwrap(), 0);assert!(increment_calls.lock().unwrap().is_empty());+ assert!(roles_service.upsert_calls.lock().unwrap().is_empty());}#[tokio::test]@@ -4297,3 +4354,319 @@ async fn try_join_team_by_domain_enterprise_status_read_precedes_membership_mutaassert!(crm_enqueuer.populated.lock().unwrap().is_empty());assert!(events.lock().unwrap().is_empty());}++#[tokio::test]+async fn create_team_without_subscription_skips_convert_and_defaults_auto_join() {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let team_repo = MockTeamRepository::new(Vec::new(), "Free Team", mark_sent_calls);+ let auto_join_toggle_calls = team_repo.auto_join_toggle_calls.clone();+ let created_team_id = *team_repo.created_team.id();++ let customer_repo = MockCustomerRepository::default();+ let convert_calls = customer_repo.convert_calls.clone();++ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let team = service+ .create_team(&user_id, "Free Team", None)+ .await+ .unwrap();++ assert_eq!(*team.id(), created_team_id);+ assert!(convert_calls.lock().unwrap().is_empty());+ // example.com is not a generic email domain, so auto-join defaults on.+ assert_eq!(+ *auto_join_toggle_calls.lock().unwrap(),+ vec![created_team_id]+ );+}++#[tokio::test]+async fn create_team_with_subscription_converts_and_defaults_auto_join() {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let team_repo = MockTeamRepository::new(Vec::new(), "Paid Team", mark_sent_calls);+ let auto_join_toggle_calls = team_repo.auto_join_toggle_calls.clone();+ let created_team_id = *team_repo.created_team.id();++ let customer_repo = MockCustomerRepository::default();+ let convert_calls = customer_repo.convert_calls.clone();++ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let subscription_id: stripe::SubscriptionId = "sub_test".parse().unwrap();+ service+ .create_team(&user_id, "Paid Team", Some(&subscription_id))+ .await+ .unwrap();++ assert_eq!(convert_calls.lock().unwrap().len(), 1);+ assert_eq!(+ *auto_join_toggle_calls.lock().unwrap(),+ vec![created_team_id]+ );+}++#[tokio::test]+async fn create_team_generic_domain_does_not_default_auto_join() {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let team_repo = MockTeamRepository::new(Vec::new(), "Personal Team", mark_sent_calls);+ let auto_join_toggle_calls = team_repo.auto_join_toggle_calls.clone();++ let service = TeamServiceImpl::new(+ team_repo,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ service+ .create_team(&user_id, "Personal Team", None)+ .await+ .unwrap();++ assert!(auto_join_toggle_calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn invite_users_to_team_free_team_under_cap_skips_billing() {+ let team_id = uuid::Uuid::from_u128(7000);+ let invite_id = uuid::Uuid::from_u128(7001);+ let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(+ vec![make_invite("[email protected]", invite_id, team_id)],+ "Free Team",+ mark_sent_calls.clone(),+ );+ // A free team: in good standing, no subscription linked.+ team_repo.team_payment_status = true;+ team_repo.team_subscription_id = None;+ team_repo.seat_count = FREE_TEAM_MAX_MEMBERS - 1;++ let invitation_persistence_calls = team_repo.invite_users_to_team_calls.clone();++ let customer_repo = MockCustomerRepository::default();+ let customer_subscription_lookup_calls = customer_repo.subscription_lookup_calls.clone();+ let increment_calls = customer_repo.increment_calls.clone();++ let notification_ingress = Arc::new(MockNotificationIngress::new(HashSet::new()));+ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ notification_ingress.clone(),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let invite_emails = vec![+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ ];+ let invites = non_empty::NonEmpty::new(invite_emails.as_slice()).unwrap();+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);++ let result = service+ .invite_users_to_team(receipt, invites)+ .await+ .unwrap();++ assert_eq!(result.len(), 1);+ assert_eq!(*invitation_persistence_calls.lock().unwrap(), 1);+ assert_eq!(*customer_subscription_lookup_calls.lock().unwrap(), 0);+ assert!(increment_calls.lock().unwrap().is_empty());+ assert_eq!(*mark_sent_calls.lock().unwrap(), vec![vec![invite_id]]);+}++#[tokio::test]+async fn invite_users_to_team_free_team_enforces_member_cap() {+ let team_id = uuid::Uuid::from_u128(7010);+ let invite_id = uuid::Uuid::from_u128(7011);+ let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(+ vec![make_invite("[email protected]", invite_id, team_id)],+ "Free Team",+ mark_sent_calls,+ );+ team_repo.team_payment_status = true;+ team_repo.team_subscription_id = None;+ team_repo.seat_count = FREE_TEAM_MAX_MEMBERS;++ let invitation_persistence_calls = team_repo.invite_users_to_team_calls.clone();++ let service = TeamServiceImpl::new(+ team_repo,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let invite_emails = vec![+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ ];+ let invites = non_empty::NonEmpty::new(invite_emails.as_slice()).unwrap();+ let receipt = test_team_receipt::<MemberTeamRole>(team_id, &invited_by);++ let result = service.invite_users_to_team(receipt, invites).await;++ assert!(matches!(+ result,+ Err(InviteUsersToTeamError::NotEnoughOpenSeats)+ ));+ assert_eq!(*invitation_persistence_calls.lock().unwrap(), 0);+}++#[tokio::test]+async fn join_team_free_team_skips_billing_and_premium_roles() {+ let team_id = uuid::Uuid::from_u128(7020);+ let invite_id = uuid::Uuid::from_u128(7021);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Free Team", mark_sent_calls);+ team_repo.team_payment_status = true;+ team_repo.team_subscription_id = None;+ // Seat count already includes the newly accepted member.+ team_repo.seat_count = FREE_TEAM_MAX_MEMBERS;+ team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));+ let rollback_accept_calls = team_repo.rollback_accept_calls.clone();++ let customer_repo = MockCustomerRepository::default();+ let increment_calls = customer_repo.increment_calls.clone();+ let channels_repo = MockTeamChannelsRepository::default();+ let roles_service = MockUserRolesAndPermissionsService::default();+ let events = Arc::new(Mutex::new(Vec::new()));++ let service = TeamServiceImpl::new_with_analytics(+ team_repo,+ customer_repo,+ channels_repo.clone(),+ roles_service.clone(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ MockTeamAnalytics::new(events.clone()),+ );++ let member = service.join_team(&invite_id, &user_id).await.unwrap();++ assert_eq!(member.team_id, team_id);+ assert_eq!(*rollback_accept_calls.lock().unwrap(), 0);+ assert!(increment_calls.lock().unwrap().is_empty());+ // Free teams do not grant premium roles.+ assert!(roles_service.upsert_calls.lock().unwrap().is_empty());+ assert_eq!(+ *channels_repo.add_calls.lock().unwrap(),+ vec![(team_id, user_id.as_ref().to_string())]+ );+ assert_eq!(events.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn join_team_free_team_over_cap_rolls_back() {+ let team_id = uuid::Uuid::from_u128(7030);+ let invite_id = uuid::Uuid::from_u128(7031);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Free Team", mark_sent_calls);+ team_repo.team_payment_status = true;+ team_repo.team_subscription_id = None;+ team_repo.seat_count = FREE_TEAM_MAX_MEMBERS + 1;+ team_repo.accepted_invite = Some(make_accepted_invite(team_id, invite_id, &user_id));+ let rollback_accept_calls = team_repo.rollback_accept_calls.clone();++ let customer_repo = MockCustomerRepository::default();+ let increment_calls = customer_repo.increment_calls.clone();+ let channels_repo = MockTeamChannelsRepository::default();+ let roles_service = MockUserRolesAndPermissionsService::default();++ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ channels_repo.clone(),+ roles_service.clone(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let result = service.join_team(&invite_id, &user_id).await;++ assert!(matches!(result, Err(JoinTeamError::FreeTeamLimitReached)));+ assert_eq!(*rollback_accept_calls.lock().unwrap(), 1);+ assert!(increment_calls.lock().unwrap().is_empty());+ assert!(roles_service.upsert_calls.lock().unwrap().is_empty());+ assert!(channels_repo.add_calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn try_join_team_by_domain_free_team_at_cap_skips() {+ let team_id = uuid::Uuid::from_u128(7040);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let member = TeamMember {+ team_id,+ user_id: user_id.clone().into_owned(),+ role: TeamRole::Member,+ };+ let mut team_repo = MockTeamRepository::new(Vec::new(), "Free Team", mark_sent_calls);+ team_repo.team_id_for_domain = Some(team_id);+ team_repo.team_payment_status = true;+ team_repo.team_subscription_id = None;+ team_repo.seat_count = FREE_TEAM_MAX_MEMBERS + 1;+ team_repo.add_user_to_team_result = Some(member.clone());+ team_repo.removed_member = Some(member);+ let add_user_calls = team_repo.add_user_to_team_calls.clone();+ let remove_user_calls = team_repo.remove_user_calls.clone();++ let customer_repo = MockCustomerRepository::default();+ let increment_calls = customer_repo.increment_calls.clone();+ let roles_service = MockUserRolesAndPermissionsService::default();++ let service = TeamServiceImpl::new(+ team_repo,+ customer_repo,+ MockTeamChannelsRepository::default(),+ roles_service.clone(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let result = service.try_join_team_by_domain(&user_id).await.unwrap();++ assert!(result.is_none());+ assert_eq!(*add_user_calls.lock().unwrap(), 1);+ assert_eq!(*remove_user_calls.lock().unwrap(), 1);+ assert!(increment_calls.lock().unwrap().is_empty());+ assert!(roles_service.upsert_calls.lock().unwrap().is_empty());+}diff --git a/crates/teams/src/inbound/axum_router/create_team.rs b/crates/teams/src/inbound/axum_router/create_team.rsindex 9d810317c6..cdec284eda 100644--- a/crates/teams/src/inbound/axum_router/create_team.rs+++ b/crates/teams/src/inbound/axum_router/create_team.rs@@ -1,10 +1,13 @@use axum::{Json, extract::State};use entity_access::domain::ports::EntityAccessService;-use macro_authorization::MacroAuthorizationService;+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};-use crate::domain::{model::Team, team_repo::TeamService};+use crate::domain::{+ model::{CreateTeamError, Team},+ team_repo::TeamService,+};-use super::{TeamRouterState, premium_user::PremiumUserExtractor};+use super::TeamRouterState;/// The request body to create a new team#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]@@ -28,12 +31,20 @@ pub struct CreateTeamRequest {#[tracing::instrument(skip_all, err)]pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(State(state): State<TeamRouterState<T, Eas, Auth>>,- user: PremiumUserExtractor<Auth>,+ user: MacroAuthorizationExtractor<Auth>,Json(req): Json<CreateTeamRequest>,-) -> Result<Json<Team>, crate::domain::model::CreateTeamError> {+) -> Result<Json<Team>, CreateTeamError> {+ // Teams are free up to FREE_TEAM_MAX_MEMBERS members — a subscription is+ // linked when the owner has one, but is no longer required to create.+ let subscription_id = state+ .service+ .is_user_premium(&user.macro_user_id)+ .await+ .map_err(|e| CreateTeamError::StorageLayerError(e.into()))?;+let team = state.service- .create_team(&user.macro_user_id, &req.name, &user.subscription_id)+ .create_team(&user.macro_user_id, &req.name, subscription_id.as_ref()).await?;Ok(Json(team))diff --git a/crates/teams/src/inbound/axum_router/invite_to_team.rs b/crates/teams/src/inbound/axum_router/invite_to_team.rsindex 547368979b..0cf2a10084 100644--- a/crates/teams/src/inbound/axum_router/invite_to_team.rs+++ b/crates/teams/src/inbound/axum_router/invite_to_team.rs@@ -1,6 +1,6 @@use axum::{Json, extract::State, http::StatusCode};use entity_access::{- domain::{models::AdminTeamRole, ports::EntityAccessService},+ domain::{models::MemberTeamRole, ports::EntityAccessService},inbound::axum_extractors::MacroUserTeamExtractorV2,};use macro_authorization::MacroAuthorizationService;@@ -61,6 +61,13 @@ impl axum::response::IntoResponse for InviteToTeamError {message: "too many emails".into(),}),),+ InviteUsersToTeamError::NotEnoughOpenSeats => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "free team member limit reached; upgrade to invite more members"+ .into(),+ }),+ ),InviteUsersToTeamError::CustomerError(_) => (StatusCode::INTERNAL_SERVER_ERROR,Json(ErrorResponse {@@ -96,7 +103,7 @@ impl axum::response::IntoResponse for InviteToTeamError {)]#[tracing::instrument(skip_all, err)]pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(- access: MacroUserTeamExtractorV2<AdminTeamRole, Eas, Auth>,+ access: MacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,State(state): State<TeamRouterState<T, Eas, Auth>>,Json(req): Json<InviteToTeamRequest>,) -> Result<StatusCode, InviteToTeamError> {diff --git a/crates/teams/src/inbound/axum_router/mod.rs b/crates/teams/src/inbound/axum_router/mod.rsindex 7619b7f96c..14e55d50a7 100644--- a/crates/teams/src/inbound/axum_router/mod.rs+++ b/crates/teams/src/inbound/axum_router/mod.rs@@ -272,6 +272,13 @@ impl IntoResponse for JoinTeamError {message: "internal server error".into(),}),),+ JoinTeamError::FreeTeamLimitReached => (+ StatusCode::FORBIDDEN,+ Json(ErrorResponse {+ message: "team is at the free member limit — upgrade to add more members"+ .into(),+ }),+ ),_ => (StatusCode::INTERNAL_SERVER_ERROR,Json(ErrorResponse {diff --git a/crates/teams/src/inbound/axum_router/test.rs b/crates/teams/src/inbound/axum_router/test.rsindex f243a15908..a991f01173 100644--- a/crates/teams/src/inbound/axum_router/test.rs+++ b/crates/teams/src/inbound/axum_router/test.rs@@ -12,7 +12,7 @@ use axum::{use entity_access::domain::{models::{AccessError, AccessLevel, AdminTeamRole, BotId, CallChannelInfo, EntityAccessReceipt,- EntityPermission, EntityType, RequiredPermission, TeamRole, UserTeamInfo,+ EntityPermission, EntityType, MemberTeamRole, RequiredPermission, TeamRole, UserTeamInfo,},ports::EntityAccessService,};@@ -122,6 +122,19 @@ async fn invite_to_team_validation_error_response_is_preserved() {assert_eq!(body_text, r#"{"message":"invalid emails detected"}"#);}+#[tokio::test]+async fn invite_to_free_team_at_capacity_returns_bad_request() {+ let error =+ InviteToTeamError::InviteUsersToTeamError(InviteUsersToTeamError::NotEnoughOpenSeats);+ let (status, body_text, _) = response_parts(error).await;++ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert_eq!(+ body_text,+ r#"{"message":"free team member limit reached; upgrade to invite more members"}"#+ );+}+#[tokio::test]async fn remove_team_invite_not_found_response_is_preserved() {let (status, body_text, _) =@@ -212,7 +225,7 @@ impl TeamService for FakeTeamService {&self,_user_id: &MacroUserIdStr<'_>,_team_name: &str,- _subscription_id: &stripe::SubscriptionId,+ _subscription_id: Option<&stripe::SubscriptionId>,) -> Result<Team, CreateTeamError> {panic!("unexpected create_team call")}@@ -226,7 +239,7 @@ impl TeamService for FakeTeamService {async fn invite_users_to_team(&self,- _entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,+ _entity_access_receipt: EntityAccessReceipt<MemberTeamRole>,_invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {panic!("unexpected invite_users_to_team call")diff --git a/crates/teams/src/outbound/team_repo.rs b/crates/teams/src/outbound/team_repo.rsindex 98cd2fcb41..7dca1dfbf4 100644--- a/crates/teams/src/outbound/team_repo.rs+++ b/crates/teams/src/outbound/team_repo.rs@@ -138,7 +138,7 @@ impl TeamRepositoryImpl {&self,user_id: &MacroUserIdStr<'_>,team_name: &str,- subscription_id: &stripe::SubscriptionId,+ subscription_id: Option<&stripe::SubscriptionId>,) -> Result<Team, sqlx::Error> {let mut transaction = self.pool.begin().await?;@@ -153,7 +153,7 @@ impl TeamRepositoryImpl {id,team_name,user_id.as_ref(),- subscription_id.to_string(),+ subscription_id.map(|s| s.to_string()),).try_map(|row| {Ok(Team {@@ -376,7 +376,7 @@ impl TeamRepository for TeamRepositoryImpl {&self,user_id: &MacroUserIdStr<'_>,team_name: &str,- subscription_id: &stripe::SubscriptionId,+ 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()));diff --git a/crates/teams/src/outbound/team_repo/test.rs b/crates/teams/src/outbound/team_repo/test.rsindex 92c2084537..6558bfc88f 100644--- a/crates/teams/src/outbound/team_repo/test.rs+++ b/crates/teams/src/outbound/team_repo/test.rs@@ -170,7 +170,7 @@ 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", &"sub_test".parse().unwrap())+ .create_team(&user_id, "team1", Some(&"sub_test".parse().unwrap())).await?;assert!(!result.id.to_string().is_empty());@@ -181,7 +181,7 @@ async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {// Create team with too large a namelet err = team_repo- .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", &"sub_test".parse().unwrap())+ .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", Some(&"sub_test".parse().unwrap())).await.err().unwrap();@@ -220,7 +220,11 @@ async fn test_move_github_app_installation_to_team_moves_existing_user_rows(.await?;let team = team_repo- .create_team(&user_id, "GitHub Owner Team", &"sub_test".parse().unwrap())+ .create_team(+ &user_id,+ "GitHub Owner Team",+ Some(&"sub_test".parse().unwrap()),+ ).await?;let team_id = team.id().to_string();@@ -337,7 +341,11 @@ async fn test_move_github_app_installation_to_team_noops_when_user_has_no_rows(.await?;let team = team_repo- .create_team(&user_id, "GitHub Owner Team", &"sub_test".parse().unwrap())+ .create_team(+ &user_id,+ "GitHub Owner Team",+ Some(&"sub_test".parse().unwrap()),+ ).await?;team_repo