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): admin toggle to restrict inviting to admins (#5032)
Jacob Beckermanaf70306fcea9
diff --git a/.sqlx/query-58e9a0467f6c0795abbf9ebba05ee30f28de0dee4cc6d1c7a84b0c55ca05d27c.json b/.sqlx/query-05f7a9a439044165e4523a2b25261b11f805ba2dcf3f0b0a03422502ee73f304.jsonsimilarity index 78%rename from .sqlx/query-58e9a0467f6c0795abbf9ebba05ee30f28de0dee4cc6d1c7a84b0c55ca05d27c.jsonrename to .sqlx/query-05f7a9a439044165e4523a2b25261b11f805ba2dcf3f0b0a03422502ee73f304.jsonindex 6aecbc1243..c4591d50a4 100644--- a/.sqlx/query-58e9a0467f6c0795abbf9ebba05ee30f28de0dee4cc6d1c7a84b0c55ca05d27c.json+++ b/.sqlx/query-05f7a9a439044165e4523a2b25261b11f805ba2dcf3f0b0a03422502ee73f304.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO team (id, name, owner_id, seat_count, subscription_id, paying)\n VALUES ($1, $2, $3, 1, $4, TRUE)\n RETURNING id, name, slug, owner_id, enterprise\n ",+ "query": "\n INSERT INTO team (id, name, owner_id, seat_count, subscription_id, paying)\n VALUES ($1, $2, $3, 1, $4, TRUE)\n RETURNING id, name, slug, owner_id, enterprise, allow_non_admin_invites\n ","describe": {"columns": [{@@ -27,6 +27,11 @@"ordinal": 4,"name": "enterprise","type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "allow_non_admin_invites",+ "type_info": "Bool"}],"parameters": {@@ -42,8 +47,9 @@false,false,false,+ false,false]},- "hash": "58e9a0467f6c0795abbf9ebba05ee30f28de0dee4cc6d1c7a84b0c55ca05d27c"+ "hash": "05f7a9a439044165e4523a2b25261b11f805ba2dcf3f0b0a03422502ee73f304"}diff --git a/.sqlx/query-210d2b138dfaed6974dad7ee5cdbf00b90b65abddda29eab93d816e453371bf4.json b/.sqlx/query-210d2b138dfaed6974dad7ee5cdbf00b90b65abddda29eab93d816e453371bf4.jsonnew file mode 100644index 0000000000..70e5e3805a--- /dev/null+++ b/.sqlx/query-210d2b138dfaed6974dad7ee5cdbf00b90b65abddda29eab93d816e453371bf4.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT allow_non_admin_invites\n FROM team\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "allow_non_admin_invites",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "210d2b138dfaed6974dad7ee5cdbf00b90b65abddda29eab93d816e453371bf4"+}diff --git a/.sqlx/query-9c06e7ff3bf17ac4951964b0b9b4c191b8a66e46b15c1b19f93416650f8ea1ea.json b/.sqlx/query-5d5cf55d5b9dc0b138684b01620b30dc5908a951020368af47cbbe6ca1052e79.jsonsimilarity index 64%rename from .sqlx/query-9c06e7ff3bf17ac4951964b0b9b4c191b8a66e46b15c1b19f93416650f8ea1ea.jsonrename to .sqlx/query-5d5cf55d5b9dc0b138684b01620b30dc5908a951020368af47cbbe6ca1052e79.jsonindex 35be07381c..5e0c98cb29 100644--- a/.sqlx/query-9c06e7ff3bf17ac4951964b0b9b4c191b8a66e46b15c1b19f93416650f8ea1ea.json+++ b/.sqlx/query-5d5cf55d5b9dc0b138684b01620b30dc5908a951020368af47cbbe6ca1052e79.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain, t.enterprise,\n COALESCE(tcs.crm_enabled, FALSE) AS \"crm_enabled!\"\n FROM team t\n JOIN team_user tu ON t.id = tu.team_id\n LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id\n WHERE tu.user_id = $1\n ",+ "query": "\n SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain, t.enterprise,\n t.allow_non_admin_invites,\n COALESCE(tcs.crm_enabled, FALSE) AS \"crm_enabled!\"\n FROM team t\n JOIN team_user tu ON t.id = tu.team_id\n LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id\n WHERE tu.user_id = $1\n ","describe": {"columns": [{@@ -35,6 +35,11 @@},{"ordinal": 6,+ "name": "allow_non_admin_invites",+ "type_info": "Bool"+ },+ {+ "ordinal": 7,"name": "crm_enabled!","type_info": "Bool"}@@ -51,8 +56,9 @@false,true,false,+ false,null]},- "hash": "9c06e7ff3bf17ac4951964b0b9b4c191b8a66e46b15c1b19f93416650f8ea1ea"+ "hash": "5d5cf55d5b9dc0b138684b01620b30dc5908a951020368af47cbbe6ca1052e79"}diff --git a/.sqlx/query-8412cb4e4925bf7d8ff2ebf5ece3a13570a0df3f222d81e7ff90a1e27c564697.json b/.sqlx/query-8b1e8ff98b7b6cfc0d18fc32bcba5f41392f2f716d7c3ba7c7d50044981a322e.jsonsimilarity index 66%rename from .sqlx/query-8412cb4e4925bf7d8ff2ebf5ece3a13570a0df3f222d81e7ff90a1e27c564697.jsonrename to .sqlx/query-8b1e8ff98b7b6cfc0d18fc32bcba5f41392f2f716d7c3ba7c7d50044981a322e.jsonindex 7e1647365b..1f91ca6f25 100644--- a/.sqlx/query-8412cb4e4925bf7d8ff2ebf5ece3a13570a0df3f222d81e7ff90a1e27c564697.json+++ b/.sqlx/query-8b1e8ff98b7b6cfc0d18fc32bcba5f41392f2f716d7c3ba7c7d50044981a322e.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain, t.enterprise,\n COALESCE(tcs.crm_enabled, FALSE) AS \"crm_enabled!\"\n FROM team t\n LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id\n WHERE t.id = $1\n ",+ "query": "\n SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain, t.enterprise,\n t.allow_non_admin_invites,\n COALESCE(tcs.crm_enabled, FALSE) AS \"crm_enabled!\"\n FROM team t\n LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id\n WHERE t.id = $1\n ","describe": {"columns": [{@@ -35,6 +35,11 @@},{"ordinal": 6,+ "name": "allow_non_admin_invites",+ "type_info": "Bool"+ },+ {+ "ordinal": 7,"name": "crm_enabled!","type_info": "Bool"}@@ -51,8 +56,9 @@false,true,false,+ false,null]},- "hash": "8412cb4e4925bf7d8ff2ebf5ece3a13570a0df3f222d81e7ff90a1e27c564697"+ "hash": "8b1e8ff98b7b6cfc0d18fc32bcba5f41392f2f716d7c3ba7c7d50044981a322e"}diff --git a/.sqlx/query-edb000afe8b8359996a3623dd495bcc6b3b39fe98fb76bcbccb176ba9e06aaef.json b/.sqlx/query-edb000afe8b8359996a3623dd495bcc6b3b39fe98fb76bcbccb176ba9e06aaef.jsonnew file mode 100644index 0000000000..8936bc5608--- /dev/null+++ b/.sqlx/query-edb000afe8b8359996a3623dd495bcc6b3b39fe98fb76bcbccb176ba9e06aaef.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE team\n SET allow_non_admin_invites = NOT allow_non_admin_invites\n WHERE id = $1\n RETURNING allow_non_admin_invites\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "allow_non_admin_invites",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "edb000afe8b8359996a3623dd495bcc6b3b39fe98fb76bcbccb176ba9e06aaef"+}diff --git a/apps/web/src/features/settings/Team.tsx b/apps/web/src/features/settings/Team.tsxindex 7ed91e3c60..6c26ab9499 100644--- a/apps/web/src/features/settings/Team.tsx+++ b/apps/web/src/features/settings/Team.tsx@@ -37,6 +37,7 @@ import {usePatchTeamMutation,useTeamQuery,useToggleAutoJoinDomainMutation,+ useToggleNonAdminInvitesMutation,useUserTeamsQuery,} from '@queries/team/teams';import type { TeamInviteDetails } from '@service-auth/generated/schemas/teamInviteDetails';@@ -819,6 +820,7 @@ function TeamManagement(props: {const inviteToTeamMutation = useInviteToTeamMutation();const deleteTeamMutation = useDeleteTeamMutation();const toggleAutoJoinMutation = useToggleAutoJoinDomainMutation();+ const toggleNonAdminInvitesMutation = useToggleNonAdminInvitesMutation();const [showDeleteTeamModal, setShowDeleteTeamModal] = createSignal(false);const [deleteConfirmation, setDeleteConfirmation] = createSignal('');@@ -967,6 +969,16 @@ function TeamManagement(props: {toggleAutoJoinMutation.mutate({ teamId: props.teamId });};+ // Whether non-admin members may invite. Teams default to true; only the+ // backend response flips it, so missing data reads as the default.+ const allowNonAdminInvites = () =>+ teamQuery.data?.team.allow_non_admin_invites ?? true;++ const handleToggleNonAdminInvites = () => {+ if (!props.teamId || toggleNonAdminInvitesMutation.isPending) return;+ toggleNonAdminInvitesMutation.mutate({ teamId: props.teamId });+ };+const handleSaveTeamName = () => {const newName = editingTeamName()?.trim();if (!props.teamId || !newName) return;@@ -1235,6 +1247,22 @@ function TeamManagement(props: {onChange={handleToggleAutoJoin}/></SettingsRow>++ <SettingsRow+ label="Members can invite"+ description="Let every team member invite people. When off, only admins and the owner can send invites."+ hideDescriptionOnMobile+ >+ <ToggleSwitch+ size="md"+ checked={allowNonAdminInvites()}+ disabled={+ toggleNonAdminInvitesMutation.isPending ||+ teamQuery.isLoading+ }+ onChange={handleToggleNonAdminInvites}+ />+ </SettingsRow></Show></SettingsCard></SettingsSection>@@ -1262,16 +1290,19 @@ function TeamManagement(props: {<SettingsSectiontitle="Members"actions={- // 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>+ // Members can invite unless the team has restricted inviting+ // to admins; removals stay admin-only.+ <Show when={isAdminOrOwner() || allowNonAdminInvites()}>+ <Button+ variant="base"+ size="sm"+ class="rounded-xs"+ onClick={() => setShowInviteModal(true)}+ >+ <PlusIcon class="size-4" />+ Invite+ </Button>+ </Show>}><Show when={showMemberSearch()}>diff --git a/apps/web/src/lib/queries/team/teams.ts b/apps/web/src/lib/queries/team/teams.tsindex 7477946d9e..0dc58b0bac 100644--- a/apps/web/src/lib/queries/team/teams.ts+++ b/apps/web/src/lib/queries/team/teams.ts@@ -11,6 +11,7 @@ import type { Team } from '@service-auth/generated/schemas/team';import { TeamRole } from '@service-auth/generated/schemas/teamRole';import type { TeamWithMembers } from '@service-auth/generated/schemas/teamWithMembers';import type { ToggleAutoJoinDomainResponse } from '@service-auth/generated/schemas/toggleAutoJoinDomainResponse';+import type { ToggleNonAdminInvitesResponse } from '@service-auth/generated/schemas/toggleNonAdminInvitesResponse';import { useMutation, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';@@ -209,6 +210,67 @@ export function useToggleAutoJoinDomainMutation(}));}+type ToggleNonAdminInvitesArgs = { teamId: string };+type ToggleNonAdminInvitesCallbacks = MutationCallbacks<+ ToggleNonAdminInvitesResponse,+ Error,+ ToggleNonAdminInvitesArgs+>;++export function useToggleNonAdminInvitesMutation(+ callbacks?: ToggleNonAdminInvitesCallbacks+) {+ return useMutation(() => ({+ mutationFn: async (_args: ToggleNonAdminInvitesArgs) =>+ await throwOnErr(() => authServiceClient.toggleTeamNonAdminInvites()),++ ...withCallbacks<+ ToggleNonAdminInvitesResponse,+ Error,+ ToggleNonAdminInvitesArgs+ >(+ {+ onSuccess: (data, { teamId }) => {+ // The response carries the authoritative new value - reflect it+ // in the cached team right away so the switch doesn't lag behind+ // the refetch, then invalidate as usual.+ const applySetting = (old: TeamWithMembers | null | undefined) =>+ old+ ? {+ ...old,+ team: {+ ...old.team,+ allow_non_admin_invites: data.allow_non_admin_invites,+ },+ }+ : old;+ queryClient.setQueryData<TeamWithMembers | null>(+ teamKeys.detail(teamId).queryKey,+ applySetting+ );+ queryClient.setQueryData<TeamWithMembers | null>(+ teamKeys.currentTeam.queryKey,+ applySetting+ );+ invalidateTeam(teamId);+ invalidateUserTeams();+ toast.success(+ data.allow_non_admin_invites+ ? 'All members can now invite'+ : 'Inviting is now limited to admins'+ );+ },++ onError: (error) => {+ console.error('Failed to toggle member invites', error);+ toast.failure('Failed to update member invites');+ },+ },+ callbacks+ ),+ }));+}+type DeleteTeamArgs = { teamId: string };type DeleteTeamContext = { previousTeams: Team[] | undefined };type DeleteTeamCallbacks = MutationCallbacks<@@ -321,6 +383,7 @@ export function useCreateTeamWithInvitesMutation(crm_enabled: false,auto_join_domain: null,enterprise: false,+ allow_non_admin_invites: true,};queryClient.setQueryData<Team[]>(diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.tsindex 3e2d3bc218..cb0e3125f8 100644--- a/apps/web/src/lib/service-clients/service-auth/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.ts@@ -45,6 +45,7 @@ import type { Team } from './generated/schemas/team';import type { TeamInvitesResponse } from './generated/schemas/teamInvitesResponse';import type { TeamWithMembers } from './generated/schemas/teamWithMembers';import type { ToggleAutoJoinDomainResponse } from './generated/schemas/toggleAutoJoinDomainResponse';+import type { ToggleNonAdminInvitesResponse } from './generated/schemas/toggleNonAdminInvitesResponse';import type { UserLinkResponse } from './generated/schemas/userLinkResponse';import type { UserName } from './generated/schemas/userName';import type { UserNames } from './generated/schemas/userNames';@@ -758,6 +759,22 @@ export const authServiceClient = {).map((result) => result);},+ /**+ * Toggles whether non-admin members may invite users to the caller's+ * team. Teams start with this on (any member can invite); turning it+ * off restricts inviting to team admins and owners. Admin/Owner only.+ */+ async toggleTeamNonAdminInvites() {+ return (+ await fetchWithAuth<ToggleNonAdminInvitesResponse>(+ `${authHost}/team/non-admin-invites/toggle`,+ {+ method: 'POST',+ }+ )+ ).map((result) => result);+ },+async deleteTeamInvite(teamInviteId: string) {return (await fetchWithAuth<{}>(`${authHost}/team/invite/${teamInviteId}`, {diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.tsindex ae333faee2..dd1b18d4cb 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts@@ -57,6 +57,7 @@ import type {TeamInvitesResponse,TeamWithMembers,ToggleAutoJoinDomainResponse,+ ToggleNonAdminInvitesResponse,UserLinkResponse,UserName,UserNames,@@ -2733,6 +2734,78 @@ export const rejectInvitation = async (} as rejectInvitationResponse;};+/**+ * @summary Toggles whether non-admin members may invite users to the team. Teams+start with this on (any member can invite); turning it off restricts+inviting to team admins and owners. Requires the caller to be an Admin+or Owner of the team.+ */+export type toggleTeamNonAdminInvitesResponse200 = {+ data: ToggleNonAdminInvitesResponse;+ status: 200;+};++export type toggleTeamNonAdminInvitesResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type toggleTeamNonAdminInvitesResponse403 = {+ data: ErrorResponse;+ status: 403;+};++export type toggleTeamNonAdminInvitesResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type toggleTeamNonAdminInvitesResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type toggleTeamNonAdminInvitesResponseSuccess =+ toggleTeamNonAdminInvitesResponse200 & {+ headers: Headers;+ };+export type toggleTeamNonAdminInvitesResponseError = (+ | toggleTeamNonAdminInvitesResponse401+ | toggleTeamNonAdminInvitesResponse403+ | toggleTeamNonAdminInvitesResponse404+ | toggleTeamNonAdminInvitesResponse500+) & {+ headers: Headers;+};++export type toggleTeamNonAdminInvitesResponse =+ | toggleTeamNonAdminInvitesResponseSuccess+ | toggleTeamNonAdminInvitesResponseError;++export const getToggleTeamNonAdminInvitesUrl = () => {+ return `/team/non-admin-invites/toggle`;+};++export const toggleTeamNonAdminInvites = async (+ options?: RequestInit+): Promise<toggleTeamNonAdminInvitesResponse> => {+ const res = await fetch(getToggleTeamNonAdminInvitesUrl(), {+ ...options,+ method: 'POST',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: toggleTeamNonAdminInvitesResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as toggleTeamNonAdminInvitesResponse;+};+/*** @summary Removes a user from a team.*/diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.tsindex decb544443..8a6264195f 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts@@ -107,6 +107,7 @@ export * from './teamRole';export * from './teamWithMembers';export * from './toggleAutoJoinDomainResponse';export * from './toggleAutoJoinDomainResponseAutoJoinDomain';+export * from './toggleNonAdminInvitesResponse';export * from './userLinkResponse';export * from './userName';export * from './userNameFirstName';diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/team.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/team.tsindex a771316922..c5bbcaef73 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/team.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/team.ts@@ -10,6 +10,9 @@ import type { TeamAutoJoinDomain } from './teamAutoJoinDomain';* The Team struct*/export interface Team {+ /** Whether non-admin members may invite users to the team. Defaults to+true; admins can turn it off so only admins/owners may invite. */+ allow_non_admin_invites: boolean;/** The email domain new users are automatically joined to this teamwith, when automatic domain joining is enabled (None otherwise). */auto_join_domain?: TeamAutoJoinDomain;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/toggleNonAdminInvitesResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/toggleNonAdminInvitesResponse.tsnew file mode 100644index 0000000000..aefc367852--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/toggleNonAdminInvitesResponse.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Response for the toggle non-admin invites endpoint.+ */+export interface ToggleNonAdminInvitesResponse {+ /** Whether non-admin members may invite users to the team after the+toggle. */+ allow_non_admin_invites: boolean;+}diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 6c798ba3f5..5f1d01d7ed 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -2312,6 +2312,65 @@}}},+ "/team/non-admin-invites/toggle": {+ "post": {+ "tags": ["teams::inbound::axum_router::toggle_non_admin_invites"],+ "summary": "Toggles whether non-admin members may invite users to the team. Teams\nstart with this on (any member can invite); turning it off restricts\ninviting to team admins and owners. Requires the caller to be an Admin\nor Owner of the team.",+ "operationId": "toggle_team_non_admin_invites",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ToggleNonAdminInvitesResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/team/remove/{remove_user_id}": {"delete": {"tags": ["teams::inbound::axum_router::remove_user_from_team"],@@ -4287,9 +4346,14 @@"slug","owner_id","crm_enabled",- "enterprise"+ "enterprise",+ "allow_non_admin_invites"],"properties": {+ "allow_non_admin_invites": {+ "type": "boolean",+ "description": "Whether non-admin members may invite users to the team. Defaults to\ntrue; admins can turn it off so only admins/owners may invite."+ },"auto_join_domain": {"type": ["string", "null"],"description": "The email domain new users are automatically joined to this team\nwith, when automatic domain joining is enabled (None otherwise)."@@ -4436,6 +4500,17 @@}}},+ "ToggleNonAdminInvitesResponse": {+ "type": "object",+ "description": "Response for the toggle non-admin invites endpoint.",+ "required": ["allow_non_admin_invites"],+ "properties": {+ "allow_non_admin_invites": {+ "type": "boolean",+ "description": "Whether non-admin members may invite users to the team after the\ntoggle."+ }+ }+ },"UserLinkResponse": {"type": "object","required": ["link_exists"],diff --git a/crates/macro_db_client/migrations/20260720145727_add_team_allow_non_admin_invites.sql b/crates/macro_db_client/migrations/20260720145727_add_team_allow_non_admin_invites.sqlnew file mode 100644index 0000000000..4c3be51cea--- /dev/null+++ b/crates/macro_db_client/migrations/20260720145727_add_team_allow_non_admin_invites.sql@@ -0,0 +1,5 @@+-- Whether non-admin members may invite users to the team. Defaults to+-- true (any member can invite); team admins can turn it off so that only+-- admins/owners may send invites.+ALTER TABLE team+ ADD COLUMN allow_non_admin_invites BOOLEAN NOT NULL DEFAULT TRUE;diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rsindex c001e2eb20..e8632fbe90 100644--- a/crates/teams/src/domain/model.rs+++ b/crates/teams/src/domain/model.rs@@ -339,6 +339,9 @@ pub struct Team {/// billed out-of-band; membership changes skip all Stripe subscription/// bookkeeping (no seat counts, no subscription backfill, no paying check).pub(crate) enterprise: bool,+ /// Whether non-admin members may invite users to the team. Defaults to+ /// true; admins can turn it off so only admins/owners may invite.+ pub(crate) allow_non_admin_invites: bool,}impl Team {@@ -360,6 +363,7 @@ impl Team {crm_enabled,auto_join_domain: None,enterprise,+ allow_non_admin_invites: true,}}}@@ -399,6 +403,11 @@ impl Team {pub fn enterprise(&self) -> bool {self.enterprise}++ /// Whether non-admin members may invite users to the team+ pub fn allow_non_admin_invites(&self) -> bool {+ self.allow_non_admin_invites+ }}/// Request to create a new team@@ -520,6 +529,9 @@ pub enum InviteUsersToTeamError {/// Not enough open seats#[error("Not enough open seats")]NotEnoughOpenSeats,+ /// The team only allows admins to invite and the caller is not an admin+ #[error("only team admins may invite users to this team")]+ NonAdminInvitesDisabled,/// Underlying team error#[error("Underlying team error {0}")]TeamError(#[from] TeamError),diff --git a/crates/teams/src/domain/team_repo.rs b/crates/teams/src/domain/team_repo.rsindex 23042c3c5f..841d5ea484 100644--- a/crates/teams/src/domain/team_repo.rs+++ b/crates/teams/src/domain/team_repo.rs@@ -287,6 +287,20 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {team_id: &uuid::Uuid,) -> impl Future<Output = Result<Option<String>, ToggleAutoJoinDomainError>> + Send;+ /// Whether non-admin members may invite users to the team.+ fn get_team_allow_non_admin_invites(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<bool, TeamError>> + Send;++ /// Flips whether non-admin members may invite users to the team.+ ///+ /// Returns the setting's value after the toggle.+ fn toggle_allow_non_admin_invites(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<bool, TeamError>> + Send;+/// Gets the id of the team whose auto-join domain matches the email/// domain of the provided user id, if any.fn get_team_id_by_domain(@@ -336,7 +350,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.+ /// Any team member may invite by default; admins can restrict+ /// inviting to admins/owners via `toggle_allow_non_admin_invites`+ /// (a non-admin caller then gets+ /// [`InviteUsersToTeamError::NonAdminInvitesDisabled`]). Removals+ /// stay admin-only./// Returns the team invites created.fn invite_users_to_team(&self,@@ -475,6 +493,17 @@ pub trait TeamService: Clone + Send + Sync + 'static {entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,) -> impl Future<Output = Result<Option<String>, ToggleAutoJoinDomainError>> + Send;+ /// Flips whether non-admin members may invite users to the team.+ /// Defaults to true (any member can invite); when off, only team+ /// admins and above may invite. Only team admins and above may+ /// toggle this.+ ///+ /// Returns the setting's value after the toggle.+ fn toggle_allow_non_admin_invites(+ &self,+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,+ ) -> impl Future<Output = Result<bool, TeamError>> + Send;+/// Automatically joins the user to the team whose auto-join domain/// matches the user's email domain, if such a team exists. The user is/// added to the team directly (no invite), with the same billing /diff --git a/crates/teams/src/domain/team_service.rs b/crates/teams/src/domain/team_service.rsindex fe049d9f3c..b650d54823 100644--- a/crates/teams/src/domain/team_service.rs+++ b/crates/teams/src/domain/team_service.rs@@ -503,7 +503,7 @@ where// 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+ // 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()) {@@ -585,6 +585,22 @@ where.get_authenticated_user().map_err(|e| InviteUsersToTeamError::TeamError(TeamError::AccessError(e)))?;+ // Inviting is member-level by default; when the team has turned+ // `allow_non_admin_invites` off, only admins/owners may invite.+ if !self+ .team_repository+ .get_team_allow_non_admin_invites(&team_id)+ .await?+ {+ let role = self+ .team_repository+ .get_team_role(&team_id, invited_by)+ .await?;+ if !matches!(role, Some(TeamRole::Admin | TeamRole::Owner)) {+ return Err(InviteUsersToTeamError::NonAdminInvitesDisabled);+ }+ }+let team_plan = self.team_repository.get_team_plan(&team_id).await?;let seat_count = self.team_repository.get_team_seat_count(&team_id).await?;@@ -711,7 +727,7 @@ wherelet subscription_id = if enterprise {None} else {- // Free teams have no linked subscription — nothing to decrement.+ // Free teams have no linked subscription - nothing to decrement.match self.team_repository.get_team_subscription_id(&team_id)@@ -828,7 +844,7 @@ where// Best-effort: ask the email service to tear down CRM rows// sourced from this user's email link. Log and swallow failures- // — the removal is already committed and the email-service+ // - the removal is already committed and the email-service// handler is idempotent, so a missed enqueue can be retried// without leaving the system in an inconsistent state. Team// deletion is handled separately via the@@ -1229,7 +1245,7 @@ where}// Best-effort: ask the email service to seed CRM tables from this- // user's historical sent mail. Log and swallow failures — the join+ // user's historical sent mail. Log and swallow failures - the join// is already committed and the email-service consumer is idempotent,// so a missed enqueue can be retried (or covered by per-message CRM// fan-out) without leaving the system in an inconsistent state.@@ -1431,7 +1447,7 @@ whereif enabled {// Fetch the members *before* flipping the flag so a member-list- // failure leaves the flag untouched — a retry will then re-run+ // failure leaves the flag untouched - a retry will then re-run// the full backfill instead of hitting the early-return below.let members = if backfill {self.team_repository.get_team_members(&team_id).await?@@ -1513,6 +1529,19 @@ whereself.team_repository.toggle_auto_join_domain(&team_id).await}+ #[tracing::instrument(skip(self), err)]+ async fn toggle_allow_non_admin_invites(+ &self,+ entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,+ ) -> Result<bool, TeamError> {+ let team_id =+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();++ self.team_repository+ .toggle_allow_non_admin_invites(&team_id)+ .await+ }+#[tracing::instrument(skip(self), err)]async fn try_join_team_by_domain(&self,@@ -1527,7 +1556,7 @@ where.get_team_enterprise_status(&team_id).await?;- // Mirror the seat-cap check from invite_users_to_team — an+ // Mirror the seat-cap check from invite_users_to_team - an// auto-join must not push the team past its plan's seat cap.if let Some(team_plan) = self.team_repository.get_team_plan(&team_id).await? {let seat_count = self.team_repository.get_team_seat_count(&team_id).await?;@@ -1621,7 +1650,7 @@ wherematch 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+ // 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@@ -1755,7 +1784,7 @@ whereself.enqueue_joining_user_contacts(&team_id, user_id).await;- // NOTE: no TeamJoined analytics event here — that event is tied to+ // NOTE: no TeamJoined analytics event here - that event is tied to// the team invite that was accepted, and a domain auto-join has none.Ok(Some(team_member))diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rsindex ba2815f03f..4a9deff228 100644--- a/crates/teams/src/domain/team_service/test.rs+++ b/crates/teams/src/domain/team_service/test.rs@@ -94,6 +94,9 @@ struct MockTeamRepository {add_user_to_team_calls: Arc<Mutex<usize>>,remove_user_calls: Arc<Mutex<usize>>,auto_join_toggle_calls: Arc<Mutex<Vec<uuid::Uuid>>>,+ allow_non_admin_invites: bool,+ caller_team_role: Option<TeamRole>,+ non_admin_invites_toggle_calls: Arc<Mutex<Vec<uuid::Uuid>>>,}impl MockTeamRepository {@@ -152,6 +155,9 @@ impl MockTeamRepository {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())),+ allow_non_admin_invites: true,+ caller_team_role: Some(TeamRole::Member),+ non_admin_invites_toggle_calls: Arc::new(Mutex::new(Vec::new())),}}@@ -169,6 +175,16 @@ impl MockTeamRepository {self.team_members = members;self}++ fn with_allow_non_admin_invites(mut self, allow: bool) -> Self {+ self.allow_non_admin_invites = allow;+ self+ }++ fn with_caller_team_role(mut self, role: Option<TeamRole>) -> Self {+ self.caller_team_role = role;+ self+ }}impl TeamRepository for MockTeamRepository {@@ -514,7 +530,8 @@ impl TeamRepository for MockTeamRepository {_: &uuid::Uuid,_: &MacroUserIdStr<'_>,) -> impl Future<Output = Result<Option<TeamRole>, TeamError>> + Send {- async { unimplemented!() }+ let role = self.caller_team_role;+ async move { Ok(role) }}fn get_team_member(@@ -571,6 +588,26 @@ impl TeamRepository for MockTeamRepository {async { Ok(Some("example.com".to_string())) }}+ fn get_team_allow_non_admin_invites(+ &self,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<bool, TeamError>> + Send {+ let allow = self.allow_non_admin_invites;+ async move { Ok(allow) }+ }++ fn toggle_allow_non_admin_invites(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<bool, TeamError>> + Send {+ self.non_admin_invites_toggle_calls+ .lock()+ .unwrap()+ .push(*team_id);+ let toggled = !self.allow_non_admin_invites;+ async move { Ok(toggled) }+ }+fn get_team_id_by_domain(&self,_: &MacroUserIdStr<'_>,@@ -1646,6 +1683,129 @@ async fn invite_users_to_team_enterprise_bypasses_billing_and_preserves_side_eff}}+#[tokio::test]+async fn invite_users_to_team_blocked_for_member_when_non_admin_invites_disabled() {+ let team_id = uuid::Uuid::from_u128(6100);+ let invite_id = uuid::Uuid::from_u128(6101);+ let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let team_repo = MockTeamRepository::new(+ vec![make_invite("[email protected]", invite_id, team_id)],+ "Locked Down Team",+ mark_sent_calls.clone(),+ )+ .with_enterprise(true)+ .with_allow_non_admin_invites(false)+ .with_caller_team_role(Some(TeamRole::Member));++ 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 error = service+ .invite_users_to_team(receipt, invites)+ .await+ .unwrap_err();++ assert!(matches!(+ error,+ InviteUsersToTeamError::NonAdminInvitesDisabled+ ));+ assert_eq!(*invitation_persistence_calls.lock().unwrap(), 0);+ assert!(mark_sent_calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn invite_users_to_team_allowed_for_admin_when_non_admin_invites_disabled() {+ let team_id = uuid::Uuid::from_u128(6110);+ let invite_id = uuid::Uuid::from_u128(6111);+ let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let team_repo = MockTeamRepository::new(+ vec![make_invite("[email protected]", invite_id, team_id)],+ "Locked Down Team",+ mark_sent_calls.clone(),+ )+ .with_enterprise(true)+ .with_allow_non_admin_invites(false)+ .with_caller_team_role(Some(TeamRole::Admin));++ 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+ .unwrap();++ assert_eq!(result.len(), 1);+ assert_eq!(result[0].team_invite_id, invite_id);+ assert_eq!(*invitation_persistence_calls.lock().unwrap(), 1);+}++#[tokio::test]+async fn toggle_allow_non_admin_invites_delegates_to_repository() {+ let team_id = uuid::Uuid::from_u128(6120);+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));+ let team_repo = MockTeamRepository::new(vec![], "Team", mark_sent_calls);+ let toggle_calls = team_repo.non_admin_invites_toggle_calls.clone();++ let service = TeamServiceImpl::new(+ team_repo,+ MockCustomerRepository::default(),+ MockTeamChannelsRepository::default(),+ MockUserRolesAndPermissionsService::default(),+ Arc::new(MockNotificationIngress::new(HashSet::new())),+ NoOpCrmEnqueuer,+ NoOpTeamCrmSettingsRepository,+ );++ let receipt = test_team_receipt::<AdminTeamRole>(team_id, &owner);++ // Mock defaults to allow=true, so a toggle returns false.+ let allow = service+ .toggle_allow_non_admin_invites(receipt)+ .await+ .unwrap();++ assert!(!allow);+ assert_eq!(*toggle_calls.lock().unwrap(), vec![team_id]);+}+#[tokio::test]async fn invite_users_to_team_enterprise_enforces_team_plan_seat_cap() {let team_id = uuid::Uuid::from_u128(6010);@@ -2715,7 +2875,7 @@ async fn test_join_team_rolls_back_accept_when_backfill_fails() {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+ // 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;diff --git a/crates/teams/src/inbound/axum_router/create_team.rs b/crates/teams/src/inbound/axum_router/create_team.rsindex cdec284eda..bf63550e01 100644--- a/crates/teams/src/inbound/axum_router/create_team.rs+++ b/crates/teams/src/inbound/axum_router/create_team.rs@@ -34,7 +34,7 @@ pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthoruser: MacroAuthorizationExtractor<Auth>,Json(req): Json<CreateTeamRequest>,) -> Result<Json<Team>, CreateTeamError> {- // Teams are free up to FREE_TEAM_MAX_MEMBERS members — a subscription is+ // 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.servicediff --git a/crates/teams/src/inbound/axum_router/invite_to_team.rs b/crates/teams/src/inbound/axum_router/invite_to_team.rsindex 0cf2a10084..be64a304b3 100644--- a/crates/teams/src/inbound/axum_router/invite_to_team.rs+++ b/crates/teams/src/inbound/axum_router/invite_to_team.rs@@ -54,33 +54,9 @@ impl axum::response::IntoResponse for InviteToTeamError {message: "no emails provided".into(),}),),- InviteToTeamError::InviteUsersToTeamError(e) => match e {- InviteUsersToTeamError::TooManyEmails => (- StatusCode::BAD_REQUEST,- Json(ErrorResponse {- 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 {- message: "internal server error".into(),- }),- ),- _ => (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to invite users to team".into(),- }),- ),- },+ // Domain errors share one mapping - see the IntoResponse impl+ // for InviteUsersToTeamError in this crate's axum_router module.+ InviteToTeamError::InviteUsersToTeamError(e) => return e.into_response(),}.into_response()}diff --git a/crates/teams/src/inbound/axum_router/mod.rs b/crates/teams/src/inbound/axum_router/mod.rsindex 14e55d50a7..012a77232e 100644--- a/crates/teams/src/inbound/axum_router/mod.rs+++ b/crates/teams/src/inbound/axum_router/mod.rs@@ -30,6 +30,8 @@ pub mod reject_invitation;pub mod remove_user_from_team;/// Toggle automatic domain joining for a team.pub mod toggle_auto_join_domain;+/// Toggle whether non-admin members may invite users to a team.+pub mod toggle_non_admin_invites;#[cfg(test)]mod test;@@ -118,6 +120,10 @@ where"/auto-join-domain/toggle",post(toggle_auto_join_domain::handler::<T, Eas, Auth>),)+ .route(+ "/non-admin-invites/toggle",+ post(toggle_non_admin_invites::handler::<T, Eas, Auth>),+ ).route("/invites", get(get_team_invites::handler::<T, Eas, Auth>)).route("/invite", post(invite_to_team::handler::<T, Eas, Auth>)).route(@@ -246,6 +252,19 @@ impl IntoResponse for InviteUsersToTeamError {message: "too many emails".into(),}),),+ InviteUsersToTeamError::NonAdminInvitesDisabled => (+ StatusCode::FORBIDDEN,+ Json(ErrorResponse {+ message: "only team admins may invite users to this team".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 {@@ -275,7 +294,7 @@ impl IntoResponse for JoinTeamError {JoinTeamError::FreeTeamLimitReached => (StatusCode::FORBIDDEN,Json(ErrorResponse {- message: "team is at the free member limit — upgrade to add more members"+ message: "team is at the free member limit - upgrade to add more members".into(),}),),diff --git a/crates/teams/src/inbound/axum_router/test.rs b/crates/teams/src/inbound/axum_router/test.rsindex a991f01173..5845a7b6dc 100644--- a/crates/teams/src/inbound/axum_router/test.rs+++ b/crates/teams/src/inbound/axum_router/test.rs@@ -389,6 +389,13 @@ impl TeamService for FakeTeamService {panic!("unexpected toggle_auto_join_domain call")}+ async fn toggle_allow_non_admin_invites(+ &self,+ _entity_access_receipt: EntityAccessReceipt<AdminTeamRole>,+ ) -> Result<bool, TeamError> {+ panic!("unexpected toggle_allow_non_admin_invites call")+ }+async fn try_join_team_by_domain(&self,_user_id: &MacroUserIdStr<'_>,diff --git a/crates/teams/src/inbound/axum_router/toggle_non_admin_invites.rs b/crates/teams/src/inbound/axum_router/toggle_non_admin_invites.rsnew file mode 100644index 0000000000..13ba1c3434--- /dev/null+++ b/crates/teams/src/inbound/axum_router/toggle_non_admin_invites.rs@@ -0,0 +1,49 @@+use axum::{Json, extract::State};+use entity_access::{+ domain::{models::AdminTeamRole, ports::EntityAccessService},+ inbound::axum_extractors::MacroUserTeamExtractorV2,+};+use macro_authorization::MacroAuthorizationService;+use model_error_response::ErrorResponse;++use crate::domain::team_repo::TeamService;++use super::TeamRouterState;++/// Response for the toggle non-admin invites endpoint.+#[derive(serde::Serialize, utoipa::ToSchema)]+pub struct ToggleNonAdminInvitesResponse {+ /// Whether non-admin members may invite users to the team after the+ /// toggle.+ pub allow_non_admin_invites: bool,+}++/// Toggles whether non-admin members may invite users to the team. Teams+/// start with this on (any member can invite); turning it off restricts+/// inviting to team admins and owners. Requires the caller to be an Admin+/// or Owner of the team.+#[utoipa::path(+ post,+ path = "/team/non-admin-invites/toggle",+ operation_id = "toggle_team_non_admin_invites",+ responses(+ (status = 200, body = ToggleNonAdminInvitesResponse),+ (status = 401, body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(+ access: MacroUserTeamExtractorV2<AdminTeamRole, Eas, Auth>,+ State(state): State<TeamRouterState<T, Eas, Auth>>,+) -> Result<Json<ToggleNonAdminInvitesResponse>, crate::domain::model::TeamError> {+ let allow_non_admin_invites = state+ .service+ .toggle_allow_non_admin_invites(access.entity_access_receipt)+ .await?;+ Ok(Json(ToggleNonAdminInvitesResponse {+ allow_non_admin_invites,+ }))+}diff --git a/crates/teams/src/outbound/team_repo.rs b/crates/teams/src/outbound/team_repo.rsindex 7dca1dfbf4..082a33165b 100644--- a/crates/teams/src/outbound/team_repo.rs+++ b/crates/teams/src/outbound/team_repo.rs@@ -148,7 +148,7 @@ impl TeamRepositoryImpl {r#"INSERT INTO team (id, name, owner_id, seat_count, subscription_id, paying)VALUES ($1, $2, $3, 1, $4, TRUE)- RETURNING id, name, slug, owner_id, enterprise+ RETURNING id, name, slug, owner_id, enterprise, allow_non_admin_invites"#,id,team_name,@@ -168,6 +168,7 @@ impl TeamRepositoryImpl {// New teams start without an auto-join domain.auto_join_domain: None,enterprise: row.enterprise,+ allow_non_admin_invites: row.allow_non_admin_invites,})}).fetch_one(&mut *transaction)@@ -1080,6 +1081,7 @@ impl TeamRepository for TeamRepositoryImpl {let team = sqlx::query!(r#"SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain, t.enterprise,+ t.allow_non_admin_invites,COALESCE(tcs.crm_enabled, FALSE) AS "crm_enabled!"FROM team tLEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id@@ -1098,6 +1100,7 @@ impl TeamRepository for TeamRepositoryImpl {crm_enabled: row.crm_enabled,auto_join_domain: row.auto_join_domain,enterprise: row.enterprise,+ allow_non_admin_invites: row.allow_non_admin_invites,})}).fetch_one(&self.pool)@@ -1136,6 +1139,7 @@ impl TeamRepository for TeamRepositoryImpl {let teams = sqlx::query!(r#"SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain, t.enterprise,+ t.allow_non_admin_invites,COALESCE(tcs.crm_enabled, FALSE) AS "crm_enabled!"FROM team tJOIN team_user tu ON t.id = tu.team_id@@ -1155,6 +1159,7 @@ impl TeamRepository for TeamRepositoryImpl {crm_enabled: row.crm_enabled,auto_join_domain: row.auto_join_domain,enterprise: row.enterprise,+ allow_non_admin_invites: row.allow_non_admin_invites,})}).fetch_all(&self.pool)@@ -1481,6 +1486,43 @@ impl TeamRepository for TeamRepositoryImpl {Ok(new_domain)}+ #[tracing::instrument(skip(self), err)]+ async fn get_team_allow_non_admin_invites(+ &self,+ team_id: &uuid::Uuid,+ ) -> Result<bool, TeamError> {+ sqlx::query_scalar!(+ r#"+ SELECT allow_non_admin_invites+ FROM team+ WHERE id = $1+ "#,+ team_id,+ )+ .fetch_optional(&self.pool)+ .await?+ .ok_or(TeamError::TeamDoesNotExist)+ }++ #[tracing::instrument(skip(self), err)]+ async fn toggle_allow_non_admin_invites(+ &self,+ team_id: &uuid::Uuid,+ ) -> Result<bool, TeamError> {+ sqlx::query_scalar!(+ r#"+ UPDATE team+ SET allow_non_admin_invites = NOT allow_non_admin_invites+ WHERE id = $1+ RETURNING allow_non_admin_invites+ "#,+ team_id,+ )+ .fetch_optional(&self.pool)+ .await?+ .ok_or(TeamError::TeamDoesNotExist)+ }+#[tracing::instrument(skip(self), err)]async fn add_user_to_team(&self,diff --git a/crates/teams/src/outbound/team_repo/test.rs b/crates/teams/src/outbound/team_repo/test.rsindex 6558bfc88f..3abdbdb3fe 100644--- a/crates/teams/src/outbound/team_repo/test.rs+++ b/crates/teams/src/outbound/team_repo/test.rs@@ -1733,3 +1733,38 @@ async fn test_add_user_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_allow_non_admin_invites_defaults_true_and_toggles(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool);+ let team_id = uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;++ // Teams default to allowing non-admin invites.+ assert!(team_repo.get_team_allow_non_admin_invites(&team_id).await?);++ // Toggling flips it off, and the getter agrees.+ assert!(!team_repo.toggle_allow_non_admin_invites(&team_id).await?);+ assert!(!team_repo.get_team_allow_non_admin_invites(&team_id).await?);++ // Toggling again flips it back on.+ assert!(team_repo.toggle_allow_non_admin_invites(&team_id).await?);+ assert!(team_repo.get_team_allow_non_admin_invites(&team_id).await?);++ // Missing teams surface TeamDoesNotExist from both methods.+ let missing = uuid::Uuid::parse_str("99999999-9999-9999-9999-999999999999")?;+ assert!(matches!(+ team_repo.get_team_allow_non_admin_invites(&missing).await,+ Err(TeamError::TeamDoesNotExist)+ ));+ assert!(matches!(+ team_repo.toggle_allow_non_admin_invites(&missing).await,+ Err(TeamError::TeamDoesNotExist)+ ));++ Ok(())+}diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rsindex e466e2ead2..6b34c941a4 100644--- a/services/authentication_service/src/api/swagger.rs+++ b/services/authentication_service/src/api/swagger.rs@@ -11,6 +11,7 @@ use teams::domain::model::{use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;use teams::inbound::axum_router::toggle_auto_join_domain::ToggleAutoJoinDomainResponse;+use teams::inbound::axum_router::toggle_non_admin_invites::ToggleNonAdminInvitesResponse;use teams::inbound::axum_router::{create_team::CreateTeamRequest, invite_to_team::InviteToTeamRequest,};@@ -133,6 +134,7 @@ use model::user::{teams::inbound::axum_router::patch_team::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,teams::inbound::axum_router::patch_team_crm_settings::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,teams::inbound::axum_router::toggle_auto_join_domain::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,+ teams::inbound::axum_router::toggle_non_admin_invites::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,teams::inbound::axum_router::reject_invitation::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,teams::inbound::axum_router::get_user_invites::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,teams::inbound::axum_router::get_user_teams::handler::<crate::api::context::TeamsServiceType, crate::api::context::EntityAccessServiceType, crate::api::context::AuthorizationService>,@@ -217,6 +219,7 @@ use model::user::{PatchTeamCrmSettingsRequest,PatchTeamCrmSettingsResponse,ToggleAutoJoinDomainResponse,+ ToggleNonAdminInvitesResponse,TeamTeamInvitesResponse,UserTeamInvitesResponse,