Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(teams): remove team user tier and default team users to Opus tier (#3278)

Will Hutchinson3c6a7679295c
diff --git a/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx b/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx
index b5a6bab218..181c0c93da 100644
--- a/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx
+++ b/js/app/packages/app/component/interactive-onboarding/lessons/review-pay.tsx
@@ -4,6 +4,7 @@ import {
PLAN_FEATURES,
PLANS,
} from '@app/component/paywall/plans';
+import { analytics } from '@app/lib/analytics/analytics';
import { useIsAuthenticated } from '@core/auth';
import { toast } from '@core/component/Toast/Toast';
import { throwOnErr } from '@core/util/maybeResult';
@@ -12,8 +13,7 @@ import InfoIcon from '@icon/regular/info.svg';
import LockIcon from '@icon/regular/lock.svg';
import { invalidateUserTeams } from '@queries/team';
import { authServiceClient } from '@service-auth/client';
-import { TeamUserTier } from '@service-auth/generated/schemas/teamUserTier';
-import { Button, cn } from '@ui';
+import { Button, cn, Tooltip } from '@ui';
import { createMemo, createSignal, For, Show } from 'solid-js';
import { useOnboarding } from '../onboarding-context';
import type { LessonContentProps, LessonDefinition } from '../types';
@@ -24,18 +24,6 @@ import {
useOnboardingCheckoutMutation,
} from '../use-onboarding-checkout';
-function toTeamUserTier(tier: PaidPlanTier): TeamUserTier {
- const map: Record<PaidPlanTier, TeamUserTier> = {
- haiku: TeamUserTier.Haiku,
- sonnet: TeamUserTier.Sonnet,
- opus: TeamUserTier.Opus,
- };
- return map[tier];
-}
-
-import { analytics } from '@app/lib/analytics/analytics';
-import { Tooltip } from '@ui';
-
function ReviewPayContent() {
return (
<div class="flex flex-col gap-3 onboarding-stagger">
@@ -355,7 +343,7 @@ async function createPendingTeamOnReturn(): Promise<boolean> {
const invites = pendingTeam.members
.filter((m) => m.email.trim())
- .map((m) => ({ email: m.email, tier: toTeamUserTier(m.tier) }));
+ .map((m) => ({ email: m.email }));
if (invites.length > 0) {
await throwOnErr(() => authServiceClient.inviteToTeam({ invites }));
diff --git a/js/app/packages/app/component/settings/Team.tsx b/js/app/packages/app/component/settings/Team.tsx
index df4e24473a..1165dbd5fa 100644
--- a/js/app/packages/app/component/settings/Team.tsx
+++ b/js/app/packages/app/component/settings/Team.tsx
@@ -1,5 +1,4 @@
import { UserIcon } from '@core/component/UserIcon';
-import { PLAN_FEATURES } from '../paywall/plans';
import PlusIcon from '@icon/regular/plus.svg';
import UsersIcon from '@icon/regular/users.svg';
import TrashIcon from '@icon/regular/trash.svg';
@@ -9,7 +8,6 @@ import XIcon from '@icon/regular/x.svg';
import CaretDownIcon from '@icon/regular/caret-down.svg';
import CheckIcon from '@icon/regular/check.svg';
-import { toast } from '@core/component/Toast/Toast';
import { Tooltip } from '@ui';
import { Button } from '@ui';
import { Dialog, Panel } from '@ui';
@@ -26,7 +24,6 @@ import {
Show,
Suspense,
Switch,
- type ValidComponent,
} from 'solid-js';
import type { CollectionNode } from '@kobalte/core';
import {
@@ -46,17 +43,11 @@ import {
useJoinTeamMutation,
useRejectInvitationMutation,
} from '@queries/team/invitations';
-import {
- useRemoveUserFromTeamMutation,
- usePatchTeamUserTierMutation,
-} from '@queries/team/members';
+import { useRemoveUserFromTeamMutation } from '@queries/team/members';
import { TeamRole } from '@service-auth/generated/schemas/teamRole';
-import { TeamUserTier } from '@service-auth/generated/schemas/teamUserTier';
import type { TeamMember } from '@service-auth/generated/schemas/teamMember';
import type { TeamInviteDetails } from '@service-auth/generated/schemas/teamInviteDetails';
import { formatRelativeTimestamp } from '@entity';
-import { ENABLE_TEAM_INVITE_TIERS_OVERRIDE } from '@core/constant/featureFlags';
-import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useHasPaidAccess } from '@core/auth/license';
import { usePaywallState } from '@core/constant/PaywallState';
import { z } from 'zod';
@@ -67,21 +58,6 @@ const roleOrder: Record<string, number> = {
[TeamRole.member]: 2,
};
-type TierOption = { value: TeamUserTier; label: string; description: string };
-
-const getTierDescription = (tier: 'haiku' | 'sonnet' | 'opus'): string => {
- const aiAgent = PLAN_FEATURES.find((f) => f.label === 'AI Agent')?.values[tier] ?? '';
- const aiCalls = PLAN_FEATURES.find((f) => f.label === 'AI tool calls')?.values[tier] ?? '';
- const storage = PLAN_FEATURES.find((f) => f.label === 'Storage')?.values[tier] ?? '';
- return `${aiAgent} · ${aiCalls} calls · ${storage}`;
-};
-
-const tierOptions: TierOption[] = [
- { value: TeamUserTier.Haiku, label: 'Level 1', description: getTierDescription('haiku') },
- { value: TeamUserTier.Sonnet, label: 'Level 2', description: getTierDescription('sonnet') },
- { value: TeamUserTier.Opus, label: 'Level 3', description: getTierDescription('opus') },
-];
-
type RoleOption = { value: TeamRole; label: string };
const roleOptions: RoleOption[] = [
@@ -138,71 +114,17 @@ function RoleSelect(props: {
);
}
-function TierSelect(props: {
- value: string;
- onChange: (tier: TeamUserTier) => void;
- triggerClass?: string;
- triggerAs?: ValidComponent;
-}) {
- const selectedOption = () =>
- tierOptions.find((o) => o.value === props.value) ?? tierOptions[0];
-
- return (
- <Select<TierOption>
- options={tierOptions}
- value={selectedOption()}
- onChange={(opt) => opt && props.onChange(opt.value)}
- optionValue="value"
- optionTextValue="label"
- gutter={4}
- placement="bottom-end"
- itemComponent={(itemProps: { item: CollectionNode<TierOption> }) => (
- <Select.Item
- item={itemProps.item}
- class="flex items-center justify-between gap-2 px-2 py-1.5 text-sm rounded-xs hover:bg-hover outline-none data-highlighted:bg-hover"
- >
- <div class="flex flex-col">
- <Select.ItemLabel>{itemProps.item.rawValue.label}</Select.ItemLabel>
- <span class="text-xs text-ink/50">{itemProps.item.rawValue.description}</span>
- </div>
- <Select.ItemIndicator>
- <CheckIcon class="size-3" />
- </Select.ItemIndicator>
- </Select.Item>
- )}
- >
- <Select.Trigger
- as={props.triggerAs}
- tabIndex={0}
- class={props.triggerClass ?? 'rounded-xs px-2 py-1 text-xs data-expanded:bg-ink/10'}
- >
- <Select.Value<TierOption>>
- {(state) => state.selectedOption().label}
- </Select.Value>
- <CaretDownIcon class="size-3 text-ink-muted shrink-0" />
- </Select.Trigger>
- <Select.Portal>
- <Select.Content class="z-50 bg-surface border border-edge rounded shadow-lg min-w-55 p-1">
- <Select.Listbox />
- </Select.Content>
- </Select.Portal>
- </Select>
- );
-}
-
const emailSchema = z.string().email();
-type InviteEntry = { email: string; tier: TeamUserTier };
+type InviteEntry = { email: string };
-const EMPTY_INVITE: InviteEntry = { email: '', tier: TeamUserTier.Haiku };
+const EMPTY_INVITE: InviteEntry = { email: '' };
function InviteEntryRow(props: {
entry: InviteEntry;
onEmailChange: (email: string) => void;
onBlur: () => void;
- onTierChange: (tier: TeamUserTier) => void;
onRemove: () => void;
- showTier: boolean;
showRemove: boolean;
error?: string;
}) {
@@ -222,13 +144,6 @@ function InviteEntryRow(props: {
: 'border-edge-muted focus:border-accent/50'
)}
/>
- <Show when={props.showTier}>
- <TierSelect
- value={props.entry.tier}
- onChange={props.onTierChange}
- triggerClass="flex items-center justify-between w-24 px-3 py-2 text-sm border border-edge-muted rounded-xs bg-surface text-ink outline-none focus:border-accent/50 shrink-0"
- />
- </Show>
<Show when={props.showRemove}>
<Tooltip label="Remove">
<Button
@@ -280,13 +195,7 @@ function InviteEmailsInput(props: {
onChange: (invites: InviteEntry[]) => void;
errors: (string | undefined)[];
onErrorsChange: (errors: (string | undefined)[]) => void;
- defaultTier?: TeamUserTier;
}) {
- const tierFlag = useFeatureFlag('enable-team-invite-tiers', {
- enabledOverride: ENABLE_TEAM_INVITE_TIERS_OVERRIDE,
- });
- const showTier = () => tierFlag().enabled;
-
const existingEmails = () => props.invites.map((i) => i.email);
const validateEmail = (index: number) => {
@@ -312,19 +221,10 @@ function InviteEmailsInput(props: {
}
};
- const updateTier = (index: number, tier: TeamUserTier) => {
- const updated = [...props.invites];
- updated[index] = { ...updated[index], tier };
- props.onChange(updated);
- };
-
let containerRef: HTMLDivElement | undefined;
const addRow = () => {
- props.onChange([
- ...props.invites,
- { email: '', tier: props.defaultTier ?? TeamUserTier.Haiku },
- ]);
+ props.onChange([...props.invites, { email: '' }]);
requestAnimationFrame(() => {
const inputs = containerRef?.querySelectorAll('input[type="text"]');
const lastInput = inputs?.[inputs.length - 1] as HTMLInputElement | undefined;
@@ -354,9 +254,7 @@ function InviteEmailsInput(props: {
entry={entry()}
onEmailChange={(email) => updateEmail(index, email)}
onBlur={() => validateEmail(index)}
- onTierChange={(tier) => updateTier(index, tier)}
onRemove={() => removeRow(index)}
- showTier={showTier()}
showRemove={props.invites.length > 1}
error={props.errors[index]}
/>
@@ -383,7 +281,6 @@ function MemberRow(props: {
isOwner: boolean;
isCurrentUser: boolean;
onRemove: () => void;
- onTierChange: (tier: TeamUserTier) => void;
onRoleChange: (role: TeamRole) => void;
}) {
const [displayName] = useDisplayName(tryMacroId(props.member.user_id));
@@ -418,14 +315,6 @@ function MemberRow(props: {
</div>
</div>
<div class="flex items-center gap-2 shrink-0">
- <Show
- when={props.isOwner}
- fallback={
- <span class="text-xs text-ink-muted py-1">{props.member.tier}</span>
- }
- >
- <TierSelect value={props.member.tier} onChange={props.onTierChange} triggerAs={Button} />
- </Show>
<Show when={props.isOwner}>
<Show
when={!props.isCurrentUser && !isMemberOwner()}
@@ -668,7 +557,7 @@ function CreateTeamDialog(props: { open: boolean; onClose: () => void }) {
const inviteEntries = invites()
.filter((i) => i.email.trim() !== '')
- .map((i) => ({ email: i.email.trim(), tier: i.tier }));
+ .map((i) => ({ email: i.email.trim() }));
createTeamMutation.mutate(
{ name: result.data, invites: inviteEntries.length > 0 ? inviteEntries : undefined },
@@ -836,7 +725,6 @@ function TeamManagement(props: {
const deleteInviteMutation = useDeleteTeamInviteMutation();
const removeUserMutation = useRemoveUserFromTeamMutation();
const patchTeamMutation = usePatchTeamMutation();
- const patchTierMutation = usePatchTeamUserTierMutation();
const inviteToTeamMutation = useInviteToTeamMutation();
const deleteTeamMutation = useDeleteTeamMutation();
@@ -959,7 +847,7 @@ function TeamManagement(props: {
const inviteEntries = currentInvites
.filter((i) => i.email.trim() !== '')
- .map((i) => ({ email: i.email.trim(), tier: i.tier }));
+ .map((i) => ({ email: i.email.trim() }));
inviteToTeamMutation.mutate(
{ teamId: props.teamId, request: { invites: inviteEntries } },
@@ -1080,23 +968,6 @@ function TeamManagement(props: {
isOwner={isOwner()}
isCurrentUser={member.user_id === userId()}
onRemove={() => setShowRemoveModal(member)}
- onTierChange={(newTier) => {
- if (!props.teamId) return;
- void toast.promise(
- patchTierMutation.mutateAsync({
- teamId: props.teamId,
- request: {
- team_user_id: member.user_id,
- new_tier: newTier,
- },
- }),
- {
- loading: 'Updating member tier...',
- success: 'Member tier updated',
- error: 'Failed to update member tier',
- }
- );
- }}
onRoleChange={(newRole) => {
if (!props.teamId) return;
patchTeamMutation.mutate({
diff --git a/js/app/packages/queries/team/index.ts b/js/app/packages/queries/team/index.ts
index 7dac9fbad9..ed594866c5 100644
--- a/js/app/packages/queries/team/index.ts
+++ b/js/app/packages/queries/team/index.ts
@@ -11,10 +11,7 @@ export {
useTeamInvitesQuery,
} from './invites';
export { teamKeys } from './keys';
-export {
- usePatchTeamUserTierMutation,
- useRemoveUserFromTeamMutation,
-} from './members';
+export { useRemoveUserFromTeamMutation } from './members';
export {
invalidateTeam,
invalidateUserTeams,
diff --git a/js/app/packages/queries/team/members.ts b/js/app/packages/queries/team/members.ts
index 6e979ddf42..b739721702 100644
--- a/js/app/packages/queries/team/members.ts
+++ b/js/app/packages/queries/team/members.ts
@@ -1,103 +1,15 @@
import { toast } from '@core/component/Toast/Toast';
import { throwOnErr } from '@core/util/maybeResult';
import { authServiceClient } from '@service-auth/client';
-import type { PatchTeamUserTierRequest } from '@service-auth/generated/schemas/patchTeamUserTierRequest';
import type { TeamWithMembers } from '@service-auth/generated/schemas/teamWithMembers';
import { useMutation } from '@tanstack/solid-query';
-import { authKeys } from '../auth';
import { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
import { teamKeys } from './keys';
import { invalidateTeam } from './teams';
-type PatchTeamUserTierArgs = {
- teamId: string;
- request: PatchTeamUserTierRequest;
-};
-type PatchTeamUserTierContext = { previousTeam: TeamWithMembers | undefined };
-type PatchTeamUserTierCallbacks = MutationCallbacks<
- void,
- Error,
- PatchTeamUserTierArgs,
- PatchTeamUserTierContext
->;
-
-export function usePatchTeamUserTierMutation(
- callbacks?: PatchTeamUserTierCallbacks
-) {
- return useMutation(() => ({
- mutationFn: async ({ request }: PatchTeamUserTierArgs) => {
- await throwOnErr(() => authServiceClient.patchTeamUserTier(request));
- },
-
- ...withCallbacks<
- void,
- Error,
- PatchTeamUserTierArgs,
- PatchTeamUserTierContext
- >(
- {
- onMutate: async ({ teamId, request }) => {
- const queryKey = teamKeys.detail(teamId).queryKey;
- await queryClient.cancelQueries({ queryKey });
-
- const previousTeam =
- queryClient.getQueryData<TeamWithMembers>(queryKey);
-
- queryClient.setQueryData<TeamWithMembers>(queryKey, (old) =>
- old
- ? {
- ...old,
- members: old.members.map((member) =>
- member.user_id === request.team_user_id
- ? { ...member, tier: request.new_tier }
- : member
- ),
- }
- : undefined
- );
-
- return { previousTeam };
- },
-
- onSuccess: (_data, { teamId, request }) => {
- invalidateTeam(teamId);
-
- const userInfo = queryClient.getQueryData<{
- userId: string;
- id: string;
- }>(authKeys.userInfo.queryKey);
- if (
- userInfo?.id === request.team_user_id ||
- userInfo?.userId === request.team_user_id
- ) {
- queryClient.invalidateQueries({
- queryKey: authKeys.userInfo.queryKey,
- });
- queryClient.invalidateQueries({
- queryKey: authKeys.userQuota.queryKey,
- });
- }
- },
-
- onError: (error, { teamId }, context) => {
- console.error('Failed to update team member tier', error);
-
- if (context?.previousTeam) {
- queryClient.setQueryData(
- teamKeys.detail(teamId).queryKey,
- context.previousTeam
- );
- }
- },
- },
- callbacks
- ),
- }));
-}
-
type RemoveUserFromTeamArgs = { teamId: string; userId: string };
type RemoveUserFromTeamContext = { previousTeam: TeamWithMembers | undefined };
type RemoveUserFromTeamCallbacks = MutationCallbacks<
diff --git a/js/app/packages/queries/team/teams.ts b/js/app/packages/queries/team/teams.ts
index a4444d4699..963daa930e 100644
--- a/js/app/packages/queries/team/teams.ts
+++ b/js/app/packages/queries/team/teams.ts
@@ -4,7 +4,6 @@ import { authServiceClient } from '@service-auth/client';
import type { CreateTeamRequest } from '@service-auth/generated/schemas/createTeamRequest';
import type { PatchTeamRequest } from '@service-auth/generated/schemas/patchTeamRequest';
import type { Team } from '@service-auth/generated/schemas/team';
-import type { TeamUserTier } from '@service-auth/generated/schemas/teamUserTier';
import { useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
@@ -151,7 +150,7 @@ export function useDeleteTeamMutation(callbacks?: DeleteTeamCallbacks) {
type CreateTeamWithInvitesArgs = {
name: string;
- invites?: { email: string; tier: TeamUserTier }[];
+ invites?: { email: string }[];
};
type CreateTeamWithInvitesContext = { previousTeams: Team[] | undefined };
type CreateTeamWithInvitesCallbacks = MutationCallbacks<
diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.ts
index 80e53f4834..ae2b4011f2 100644
--- a/js/app/packages/service-clients/service-auth/client.ts
+++ b/js/app/packages/service-clients/service-auth/client.ts
@@ -32,7 +32,6 @@ import type { InviteToTeamRequest } from './generated/schemas/inviteToTeamReques
import type { MacroApiTokenResponse } from './generated/schemas/macroApiTokenResponse';
import type { PasswordRequest } from './generated/schemas/passwordRequest';
import type { PatchTeamRequest } from './generated/schemas/patchTeamRequest';
-import type { PatchTeamUserTierRequest } from './generated/schemas/patchTeamUserTierRequest';
import type { PatchUserGroupRequest } from './generated/schemas/patchUserGroupRequest';
import type { PatchUserOnboardingRequest } from './generated/schemas/patchUserOnboardingRequest';
import type { PostGetNamesRequestBody } from './generated/schemas/postGetNamesRequestBody';
@@ -659,16 +658,6 @@ export const authServiceClient = {
);
},
- async patchTeamUserTier(args: PatchTeamUserTierRequest) {
- return mapOk(
- await fetchWithAuth<{}>(`${authHost}/team/tier`, {
- method: 'PATCH',
- body: JSON.stringify(args),
- }),
- () => undefined
- );
- },
-
async inviteToTeam(args: InviteToTeamRequest) {
return mapOk(
await fetchWithAuth<{}>(`${authHost}/team/invite`, {
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.ts
index 64806d847f..36c00de24f 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -31,7 +31,6 @@ import type {
PasswordRequest,
PatchSubscriptionTierRequest,
PatchTeamRequest,
- PatchTeamUserTierRequest,
PatchUserGroupRequest,
PatchUserOnboardingRequest,
PatchUserTutorialRequest,
@@ -2313,75 +2312,6 @@ export const removeUserFromTeam = async (
} as removeUserFromTeamResponse;
};
-/**
- * @summary Updates a team.
- */
-export type patchTeamUserTierResponse200 = {
- data: void;
- status: 200;
-};
-
-export type patchTeamUserTierResponse400 = {
- data: ErrorResponse;
- status: 400;
-};
-
-export type patchTeamUserTierResponse401 = {
- data: ErrorResponse;
- status: 401;
-};
-
-export type patchTeamUserTierResponse404 = {
- data: ErrorResponse;
- status: 404;
-};
-
-export type patchTeamUserTierResponse500 = {
- data: ErrorResponse;
- status: 500;
-};
-
-export type patchTeamUserTierResponseSuccess = patchTeamUserTierResponse200 & {
- headers: Headers;
-};
-export type patchTeamUserTierResponseError = (
- | patchTeamUserTierResponse400
- | patchTeamUserTierResponse401
- | patchTeamUserTierResponse404
- | patchTeamUserTierResponse500
-) & {
- headers: Headers;
-};
-
-export type patchTeamUserTierResponse =
- | patchTeamUserTierResponseSuccess
- | patchTeamUserTierResponseError;
-
-export const getPatchTeamUserTierUrl = () => {
- return `/team/tier`;
-};
-
-export const patchTeamUserTier = async (
- patchTeamUserTierRequest: PatchTeamUserTierRequest,
- options?: RequestInit
-): Promise<patchTeamUserTierResponse> => {
- const res = await fetch(getPatchTeamUserTierUrl(), {
- ...options,
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchTeamUserTierRequest),
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: patchTeamUserTierResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as patchTeamUserTierResponse;
-};
-
/**
* @summary Gets all teams for the authenticated user.
*/
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
index d43742d3fd..89c9a2428a 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
@@ -45,7 +45,6 @@ export * from './patchTeamRequest';
export * from './patchTeamRequestName';
export * from './patchTeamRequestUserRoleUpdates';
export * from './patchTeamUserRole';
-export * from './patchTeamUserTierRequest';
export * from './patchUserGroupRequest';
export * from './patchUserOnboardingRequest';
export * from './patchUserTutorialRequest';
@@ -71,7 +70,6 @@ export * from './teamInviteDetails';
export * from './teamInvitesResponse';
export * from './teamMember';
export * from './teamRole';
-export * from './teamUserTier';
export * from './teamWithMembers';
export * from './userLinkResponse';
export * from './userName';
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/inviteEntry.ts b/js/app/packages/service-clients/service-auth/generated/schemas/inviteEntry.ts
index e66a911163..629064987e 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/inviteEntry.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/inviteEntry.ts
@@ -4,7 +4,6 @@
* authentication_service
* OpenAPI spec version: 0.1.0
*/
-import type { TeamUserTier } from './teamUserTier';
/**
* A single invite entry with email and tier
@@ -12,6 +11,4 @@ import type { TeamUserTier } from './teamUserTier';
export interface InviteEntry {
/** The email of the user to invite */
email: string;
- /** The tier for this user (defaults to Haiku if not provided) */
- tier?: TeamUserTier;
}
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamUserTierRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamUserTierRequest.ts
deleted file mode 100644
index c9da46db81..0000000000
--- a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamUserTierRequest.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * authentication_service
- * OpenAPI spec version: 0.1.0
- */
-import type { TeamUserTier } from './teamUserTier';
-
-/**
- * Request to update a team user's tier
- */
-export interface PatchTeamUserTierRequest {
- /** The new tier of the team user */
- new_tier: TeamUserTier;
- /** The team user you are updating */
- team_user_id: string;
-}
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamMember.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamMember.ts
index 8fc970be98..20a382405f 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamMember.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamMember.ts
@@ -14,8 +14,6 @@ export interface TeamMember {
role: TeamRole;
/** The id of the team */
team_id: string;
- /** The tier of the team member */
- tier: string;
/** The user id of the team member */
user_id: string;
}
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamUserTier.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamUserTier.ts
deleted file mode 100644
index 9a5de267bd..0000000000
--- a/js/app/packages/service-clients/service-auth/generated/schemas/teamUserTier.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * authentication_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Ordered from lowest to highest tier top -> bottom
- */
-export type TeamUserTier = (typeof TeamUserTier)[keyof typeof TeamUserTier];
-
-// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const TeamUserTier = {
- Haiku: 'Haiku',
- Sonnet: 'Sonnet',
- Opus: 'Opus',
-} as const;
diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.json
index 4cffd83007..c8b9b5eeb5 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -1937,68 +1937,6 @@
}
}
},
- "/team/tier": {
- "patch": {
- "tags": ["teams::inbound::axum_router::patch_team_user_tier"],
- "summary": "Updates a team.",
- "operationId": "patch_team_user_tier",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/PatchTeamUserTierRequest"
- }
- }
- },
- "required": true
- },
- "responses": {
- "200": {
- "description": ""
- },
- "400": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
- "401": {
- "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/user": {
"get": {
"tags": ["teams::inbound::axum_router::get_user_teams"],
@@ -3386,10 +3324,6 @@
"email": {
"type": "string",
"description": "The email of the user to invite"
- },
- "tier": {
- "$ref": "#/components/schemas/TeamUserTier",
- "description": "The tier for this user (defaults to Haiku if not provided)"
}
}
},
@@ -3491,21 +3425,6 @@
}
}
},
- "PatchTeamUserTierRequest": {
- "type": "object",
- "description": "Request to update a team user's tier",
- "required": ["team_user_id", "new_tier"],
- "properties": {
- "new_tier": {
- "$ref": "#/components/schemas/TeamUserTier",
- "description": "The new tier of the team user"
- },
- "team_user_id": {
- "type": "string",
- "description": "The team user you are updating"
- }
- }
- },
"PatchUserGroupRequest": {
"type": "object",
"required": ["group"],
@@ -3755,7 +3674,7 @@
"TeamMember": {
"type": "object",
"description": "The team member struct",
- "required": ["team_id", "user_id", "role", "tier"],
+ "required": ["team_id", "user_id", "role"],
"properties": {
"role": {
"$ref": "#/components/schemas/TeamRole",
@@ -3766,10 +3685,6 @@
"format": "uuid",
"description": "The id of the team"
},
- "tier": {
- "type": "string",
- "description": "The tier of the team member"
- },
"user_id": {
"type": "string",
"description": "The user id of the team member"
@@ -3781,11 +3696,6 @@
"description": "Ordered from least to most access top -> bottom",
"enum": ["member", "admin", "owner"]
},
- "TeamUserTier": {
- "type": "string",
- "description": "Ordered from lowest to highest tier top -> bottom",
- "enum": ["Haiku", "Sonnet", "Opus"]
- },
"TeamWithMembers": {
"type": "object",
"description": "A team with its members",
diff --git a/rust/cloud-storage/.sqlx/query-135a74cbd3480afc65012e82671f258a103985e6d52efd23886669872d9cf26a.json b/rust/cloud-storage/.sqlx/query-135a74cbd3480afc65012e82671f258a103985e6d52efd23886669872d9cf26a.json
deleted file mode 100644
index f677d3af24..0000000000
--- a/rust/cloud-storage/.sqlx/query-135a74cbd3480afc65012e82671f258a103985e6d52efd23886669872d9cf26a.json
+++ /dev/null
@@ -1,69 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at, tier)\n SELECT\n t.id,\n $1::uuid,\n t.email,\n $2,\n $3::text,\n NOW(),\n NOW(),\n t.tier\n FROM UNNEST($4::uuid[], $5::text[], $6::text[], $7::\"team_user_tier\"[]) AS t(id, email, user_id, tier)\n WHERE NOT EXISTS (\n SELECT 1 FROM team_invite ti\n WHERE ti.team_id = $1 AND ti.email = t.email\n )\n AND NOT EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = $1 AND tu.user_id = t.user_id\n )\n RETURNING id, team_id, email\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "team_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "email",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- {
- "Custom": {
- "name": "team_role",
- "kind": {
- "Enum": [
- "member",
- "admin",
- "owner"
- ]
- }
- }
- },
- "Text",
- "UuidArray",
- "TextArray",
- "TextArray",
- {
- "Custom": {
- "name": "team_user_tier[]",
- "kind": {
- "Array": {
- "Custom": {
- "name": "team_user_tier",
- "kind": {
- "Enum": [
- "haiku",
- "sonnet",
- "opus"
- ]
- }
- }
- }
- }
- }
- }
- ]
- },
- "nullable": [
- false,
- false,
- false
- ]
- },
- "hash": "135a74cbd3480afc65012e82671f258a103985e6d52efd23886669872d9cf26a"
-}
diff --git a/rust/cloud-storage/.sqlx/query-1bf9b2bf67d4780b41454d87c4a1995677a162dd11af0b9d77df947b657cd651.json b/rust/cloud-storage/.sqlx/query-1bf9b2bf67d4780b41454d87c4a1995677a162dd11af0b9d77df947b657cd651.json
new file mode 100644
index 0000000000..8c916fcea0
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-1bf9b2bf67d4780b41454d87c4a1995677a162dd11af0b9d77df947b657cd651.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team_user (team_id, user_id, team_role)\n VALUES ($1, $2, 'owner')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1bf9b2bf67d4780b41454d87c4a1995677a162dd11af0b9d77df947b657cd651"
+}
diff --git a/rust/cloud-storage/.sqlx/query-4f26a2f6044225dd1019390579a3652eafdf1db2ae15212335ebd5ecbb3b4ebe.json b/rust/cloud-storage/.sqlx/query-4f26a2f6044225dd1019390579a3652eafdf1db2ae15212335ebd5ecbb3b4ebe.json
deleted file mode 100644
index eb4edb65d2..0000000000
--- a/rust/cloud-storage/.sqlx/query-4f26a2f6044225dd1019390579a3652eafdf1db2ae15212335ebd5ecbb3b4ebe.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO team_user (team_id, user_id, team_role, tier)\n VALUES ($1, $2, 'owner', $3)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- {
- "Custom": {
- "name": "team_user_tier",
- "kind": {
- "Enum": [
- "haiku",
- "sonnet",
- "opus"
- ]
- }
- }
- }
- ]
- },
- "nullable": []
- },
- "hash": "4f26a2f6044225dd1019390579a3652eafdf1db2ae15212335ebd5ecbb3b4ebe"
-}
diff --git a/rust/cloud-storage/.sqlx/query-32caedb3c1bd949d4c4cfec7a3f43a1403707f4e9126f51d33d7c3c3c82b7c8a.json b/rust/cloud-storage/.sqlx/query-500452d6337cfbc2d9a919268021835385045e45c20aaba40ed940cf3f25a07a.json
similarity index 53%
rename from rust/cloud-storage/.sqlx/query-32caedb3c1bd949d4c4cfec7a3f43a1403707f4e9126f51d33d7c3c3c82b7c8a.json
rename to rust/cloud-storage/.sqlx/query-500452d6337cfbc2d9a919268021835385045e45c20aaba40ed940cf3f25a07a.json
index bedfa7824c..494c00db71 100644
--- a/rust/cloud-storage/.sqlx/query-32caedb3c1bd949d4c4cfec7a3f43a1403707f4e9126f51d33d7c3c3c82b7c8a.json
+++ b/rust/cloud-storage/.sqlx/query-500452d6337cfbc2d9a919268021835385045e45c20aaba40ed940cf3f25a07a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT user_id, \n team_role as \"team_role!: TeamRole\",\n tier as \"tier!: TeamUserTier\"\n FROM team_user\n WHERE team_id = $1\n AND user_id = $2\n ",
+ "query": "\n SELECT user_id, \n team_role as \"team_role!: TeamRole\"\n FROM team_user\n WHERE team_id = $1\n AND user_id = $2\n ",
"describe": {
"columns": [
{
@@ -23,22 +23,6 @@
}
}
}
- },
- {
- "ordinal": 2,
- "name": "tier!: TeamUserTier",
- "type_info": {
- "Custom": {
- "name": "team_user_tier",
- "kind": {
- "Enum": [
- "haiku",
- "sonnet",
- "opus"
- ]
- }
- }
- }
}
],
"parameters": {
@@ -48,10 +32,9 @@
]
},
"nullable": [
- false,
false,
false
]
},
- "hash": "32caedb3c1bd949d4c4cfec7a3f43a1403707f4e9126f51d33d7c3c3c82b7c8a"
+ "hash": "500452d6337cfbc2d9a919268021835385045e45c20aaba40ed940cf3f25a07a"
}
diff --git a/rust/cloud-storage/.sqlx/query-61e82a1be0d1352b8a1147bbff2dc3bd8e945b75380f112bb1118491b3d03f96.json b/rust/cloud-storage/.sqlx/query-61e82a1be0d1352b8a1147bbff2dc3bd8e945b75380f112bb1118491b3d03f96.json
new file mode 100644
index 0000000000..d8e19e46a0
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-61e82a1be0d1352b8a1147bbff2dc3bd8e945b75380f112bb1118491b3d03f96.json
@@ -0,0 +1,50 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at)\n SELECT\n t.id,\n $1::uuid,\n t.email,\n $2,\n $3::text,\n NOW(),\n NOW()\n FROM UNNEST($4::uuid[], $5::text[], $6::text[]) AS t(id, email, user_id)\n WHERE NOT EXISTS (\n SELECT 1 FROM team_invite ti\n WHERE ti.team_id = $1 AND ti.email = t.email\n )\n AND NOT EXISTS (\n SELECT 1 FROM team_user tu\n WHERE tu.team_id = $1 AND tu.user_id = t.user_id\n )\n RETURNING id, team_id, email\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "email",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ },
+ "Text",
+ "UuidArray",
+ "TextArray",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "61e82a1be0d1352b8a1147bbff2dc3bd8e945b75380f112bb1118491b3d03f96"
+}
diff --git a/rust/cloud-storage/.sqlx/query-d1f79f2a50de2167f06ac49f52b134ccc3b8eeb070e7fd710b18dbbfc783aa1d.json b/rust/cloud-storage/.sqlx/query-71f0916419e122c5dba653bdc23114987bb800ba14658efaac7cafd0c16672c8.json
similarity index 53%
rename from rust/cloud-storage/.sqlx/query-d1f79f2a50de2167f06ac49f52b134ccc3b8eeb070e7fd710b18dbbfc783aa1d.json
rename to rust/cloud-storage/.sqlx/query-71f0916419e122c5dba653bdc23114987bb800ba14658efaac7cafd0c16672c8.json
index 12074b1ba2..51e00bbc86 100644
--- a/rust/cloud-storage/.sqlx/query-d1f79f2a50de2167f06ac49f52b134ccc3b8eeb070e7fd710b18dbbfc783aa1d.json
+++ b/rust/cloud-storage/.sqlx/query-71f0916419e122c5dba653bdc23114987bb800ba14658efaac7cafd0c16672c8.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT user_id, \n team_role as \"team_role!: TeamRole\",\n tier as \"tier!: TeamUserTier\"\n FROM team_user\n WHERE team_id = $1\n ",
+ "query": "\n SELECT user_id, \n team_role as \"team_role!: TeamRole\"\n FROM team_user\n WHERE team_id = $1\n ",
"describe": {
"columns": [
{
@@ -23,22 +23,6 @@
}
}
}
- },
- {
- "ordinal": 2,
- "name": "tier!: TeamUserTier",
- "type_info": {
- "Custom": {
- "name": "team_user_tier",
- "kind": {
- "Enum": [
- "haiku",
- "sonnet",
- "opus"
- ]
- }
- }
- }
}
],
"parameters": {
@@ -47,10 +31,9 @@
]
},
"nullable": [
- false,
false,
false
]
},
- "hash": "d1f79f2a50de2167f06ac49f52b134ccc3b8eeb070e7fd710b18dbbfc783aa1d"
+ "hash": "71f0916419e122c5dba653bdc23114987bb800ba14658efaac7cafd0c16672c8"
}
diff --git a/rust/cloud-storage/.sqlx/query-93e4b43a340a79ff7a4ebff7ae351893f605ea8a568a304968bec11a6c0cc2b6.json b/rust/cloud-storage/.sqlx/query-93e4b43a340a79ff7a4ebff7ae351893f605ea8a568a304968bec11a6c0cc2b6.json
deleted file mode 100644
index 07e69c222d..0000000000
--- a/rust/cloud-storage/.sqlx/query-93e4b43a340a79ff7a4ebff7ae351893f605ea8a568a304968bec11a6c0cc2b6.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE team_user\n SET tier = $3\n WHERE team_id = $1\n AND user_id = $2\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- {
- "Custom": {
- "name": "team_user_tier",
- "kind": {
- "Enum": [
- "haiku",
- "sonnet",
- "opus"
- ]
- }
- }
- }
- ]
- },
- "nullable": []
- },
- "hash": "93e4b43a340a79ff7a4ebff7ae351893f605ea8a568a304968bec11a6c0cc2b6"
-}
diff --git a/rust/cloud-storage/.sqlx/query-d5ffa82610d978dab83826ea1dfe5c5fdba0126759ea99c27f91555adab1480d.json b/rust/cloud-storage/.sqlx/query-bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04.json
similarity index 53%
rename from rust/cloud-storage/.sqlx/query-d5ffa82610d978dab83826ea1dfe5c5fdba0126759ea99c27f91555adab1480d.json
rename to rust/cloud-storage/.sqlx/query-bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04.json
index b3cca681f4..c645aa3823 100644
--- a/rust/cloud-storage/.sqlx/query-d5ffa82610d978dab83826ea1dfe5c5fdba0126759ea99c27f91555adab1480d.json
+++ b/rust/cloud-storage/.sqlx/query-bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT user_id,\n team_role as \"team_role!: TeamRole\",\n tier as \"tier!: TeamUserTier\"\n FROM team_user\n WHERE team_id = $1\n ",
+ "query": "\n SELECT user_id,\n team_role as \"team_role!: TeamRole\"\n FROM team_user\n WHERE team_id = $1\n ",
"describe": {
"columns": [
{
@@ -23,22 +23,6 @@
}
}
}
- },
- {
- "ordinal": 2,
- "name": "tier!: TeamUserTier",
- "type_info": {
- "Custom": {
- "name": "team_user_tier",
- "kind": {
- "Enum": [
- "haiku",
- "sonnet",
- "opus"
- ]
- }
- }
- }
}
],
"parameters": {
@@ -47,10 +31,9 @@
]
},
"nullable": [
- false,
false,
false
]
},
- "hash": "d5ffa82610d978dab83826ea1dfe5c5fdba0126759ea99c27f91555adab1480d"
+ "hash": "bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04"
}
diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rs
index 56872d3421..a7b0b96544 100644
--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs
+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs
@@ -1,7 +1,7 @@
use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};
use teams::domain::model::{
- PatchTeamRequest, PatchTeamUserRole, PatchTeamUserTierRequest, Team, TeamInviteDetails,
- TeamMember, TeamRole, TeamUserTier, TeamWithMembers,
+ PatchTeamRequest, PatchTeamUserRole, Team, TeamInviteDetails, TeamMember, TeamRole,
+ TeamWithMembers,
};
use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;
use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;
@@ -120,7 +120,6 @@ use model::user::{
teams::inbound::axum_router::invite_to_team::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::get_team_invites::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::patch_team::handler::<crate::api::context::TeamsServiceType>,
- teams::inbound::axum_router::patch_team_user_tier::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::reject_invitation::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::get_user_invites::handler::<crate::api::context::TeamsServiceType>,
teams::inbound::axum_router::get_user_teams::handler::<crate::api::context::TeamsServiceType>,
@@ -192,8 +191,6 @@ use model::user::{
PatchTeamUserRole,
TeamTeamInvitesResponse,
UserTeamInvitesResponse,
- PatchTeamUserTierRequest,
- TeamUserTier,
// Mobile welcome email
mobile_welcome_email::SendMobileWelcomeEmailRequest,
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260514170455_remove_team_user_tier.sql b/rust/cloud-storage/macro_db_client/migrations/20260514170455_remove_team_user_tier.sql
new file mode 100644
index 0000000000..ddacf10d1c
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260514170455_remove_team_user_tier.sql
@@ -0,0 +1,5 @@
+-- Remove the tier column from team_user
+ALTER TABLE "team_user" DROP COLUMN tier;
+
+-- Remove the tier from team_invite
+ALTER TABLE "team_invite" DROP COLUMN tier;
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260514170723_remove_team_user_tier_enum.sql b/rust/cloud-storage/macro_db_client/migrations/20260514170723_remove_team_user_tier_enum.sql
new file mode 100644
index 0000000000..8826a888e6
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260514170723_remove_team_user_tier_enum.sql
@@ -0,0 +1,3 @@
+-- Add migration script here
+DROP TYPE team_user_tier;
+
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260514174907_update_team_roles_to_opus.sql b/rust/cloud-storage/macro_db_client/migrations/20260514174907_update_team_roles_to_opus.sql
new file mode 100644
index 0000000000..a56700acd9
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260514174907_update_team_roles_to_opus.sql
@@ -0,0 +1,12 @@
+-- We are setting it so all team users have **opus** tier
+-- First we will remove the existing tier roles from all users in teams
+ DELETE FROM public."RolesOnUsers" rou
+ USING public.team_user tu
+ WHERE rou."userId" = tu.user_id
+ AND rou."roleId" IN ('sub_opus', 'sub_haiku', 'sub_sonnet');
+
+-- Then we will insert the sub_opus role for all the users
+ INSERT INTO public."RolesOnUsers" ("userId", "roleId")
+ SELECT DISTINCT tu.user_id, 'sub_opus'
+ FROM public.team_user tu
+ ON CONFLICT ("userId", "roleId") DO NOTHING;
diff --git a/rust/cloud-storage/teams/fixtures/teams.sql b/rust/cloud-storage/teams/fixtures/teams.sql
index f3efd463e9..9896a51cd2 100644
--- a/rust/cloud-storage/teams/fixtures/teams.sql
+++ b/rust/cloud-storage/teams/fixtures/teams.sql
@@ -15,9 +15,9 @@ INSERT INTO team(id, name, owner_id, subscription_id, seat_count)
VALUES ('11111111-1111-1111-1111-111111111111', 'team1', 'macro|[email protected]', 'sub_1', 3), -- seat count is 3 for 2 invites and 1 member
('22222222-2222-2222-2222-222222222222', 'team2', 'macro|[email protected]', NULL, 1);
-INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at, tier)
-VALUES ('11111111-1111-1111-1111-111111111111', '11111111-1111-1111-1111-111111111111', '[email protected]', 'member', 'macro|[email protected]', NOW(), NOW(), 'haiku'),
- ('22222222-2222-2222-2222-222222222222', '11111111-1111-1111-1111-111111111111', '[email protected]', 'member', 'macro|[email protected]', NOW(), NOW(), 'opus');
+INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at)
+VALUES ('11111111-1111-1111-1111-111111111111', '11111111-1111-1111-1111-111111111111', '[email protected]', 'member', 'macro|[email protected]', NOW(), NOW()),
+ ('22222222-2222-2222-2222-222222222222', '11111111-1111-1111-1111-111111111111', '[email protected]', 'member', 'macro|[email protected]', NOW(), NOW());
INSERT INTO team_user (team_id, user_id, team_role)
VALUES ('11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'owner'),
diff --git a/rust/cloud-storage/teams/fixtures/teams_remaining_tiers.sql b/rust/cloud-storage/teams/fixtures/teams_remaining_tiers.sql
index d36798d7ab..11bb0131e6 100644
--- a/rust/cloud-storage/teams/fixtures/teams_remaining_tiers.sql
+++ b/rust/cloud-storage/teams/fixtures/teams_remaining_tiers.sql
@@ -16,7 +16,7 @@ INSERT INTO team(id, name, owner_id, subscription_id, seat_count)
VALUES ('aaaa1111-1111-1111-1111-111111111111', 'Team A', 'macro|[email protected]', 'sub_a', 2),
('bbbb2222-2222-2222-2222-222222222222', 'Team B', 'macro|[email protected]', 'sub_b', 1);
-INSERT INTO team_user (team_id, user_id, team_role, tier)
+INSERT INTO team_user (team_id, user_id, team_role)
VALUES
- ('aaaa1111-1111-1111-1111-111111111111', 'macro|[email protected]', 'owner', 'haiku'),
- ('bbbb2222-2222-2222-2222-222222222222', 'macro|[email protected]', 'owner', 'sonnet');
+ ('aaaa1111-1111-1111-1111-111111111111', 'macro|[email protected]', 'owner'),
+ ('bbbb2222-2222-2222-2222-222222222222', 'macro|[email protected]', 'owner');
diff --git a/rust/cloud-storage/teams/src/domain/customer_repo.rs b/rust/cloud-storage/teams/src/domain/customer_repo.rs
index 4b7401b42c..d848d20f8e 100644
--- a/rust/cloud-storage/teams/src/domain/customer_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/customer_repo.rs
@@ -2,7 +2,7 @@
use macro_user_id::user_id::MacroUserIdStr;
-use crate::domain::model::{CreateSubscriptionArgs, CustomerError, TeamUserTier};
+use crate::domain::model::{CreateSubscriptionArgs, CustomerError};
/// The CustomerRepository defines a set of actions to perform on customer data
pub trait CustomerRepository: Clone + Send + Sync + 'static {
@@ -26,28 +26,6 @@ pub trait CustomerRepository: Clone + Send + Sync + 'static {
args: CreateSubscriptionArgs,
) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send;
- /// Increases the quantity of a subscription
- fn increase_subscription_quantity(
- &self,
- subscription_id: &stripe::SubscriptionId,
- tier: TeamUserTier,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send;
-
- /// Decrement the quantity of a subscription
- fn decrease_subscription_quantity(
- &self,
- subscription_id: &stripe::SubscriptionId,
- team_user_tier: TeamUserTier,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send;
-
- /// Updates the stripe subscription when a team members tier is changed
- fn update_subscription_tier(
- &self,
- subscription_id: &stripe::SubscriptionId,
- old_team_user_tier: TeamUserTier,
- new_team_user_tier: TeamUserTier,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send;
-
/// Cancels a subscription immediately.
fn cancel_subscription(
&self,
diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rs
index 596abe9932..a00e95208b 100644
--- a/rust/cloud-storage/teams/src/domain/model.rs
+++ b/rust/cloud-storage/teams/src/domain/model.rs
@@ -1,76 +1,10 @@
//! Contains the models for teams
-use std::collections::{HashMap, HashSet};
+use std::collections::HashMap;
use chrono::{DateTime, Utc};
use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};
-use roles_and_permissions::domain::model::{RoleId, UserRolesAndPermissionsError};
-
-#[derive(
- Eq,
- PartialEq,
- Debug,
- Clone,
- Hash,
- PartialOrd,
- Copy,
- std::cmp::Ord,
- serde::Serialize,
- serde::Deserialize,
- Default,
-)]
-#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
-#[cfg_attr(feature = "outbound", derive(sqlx::Type))]
-#[cfg_attr(
- feature = "outbound",
- sqlx(type_name = "\"team_user_tier\"", rename_all = "lowercase")
-)]
-/// Ordered from lowest to highest tier top -> bottom
-pub enum TeamUserTier {
- #[default]
- /// Haiku
- Haiku,
- /// Sonnet,
- Sonnet,
- /// Opus
- Opus,
-}
-
-impl std::fmt::Display for TeamUserTier {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- TeamUserTier::Haiku => write!(f, "haiku"),
- TeamUserTier::Sonnet => write!(f, "sonnet"),
- TeamUserTier::Opus => write!(f, "opus"),
- }
- }
-}
-
-impl From<TeamUserTier> for RoleId {
- fn from(value: TeamUserTier) -> Self {
- match value {
- TeamUserTier::Haiku => RoleId::SubHaiku,
- TeamUserTier::Sonnet => RoleId::SubSonnet,
- TeamUserTier::Opus => RoleId::SubOpus,
- }
- }
-}
-
-impl TeamUserTier {
- /// Given a list of a users roles, this will try to grab the users respective
- /// team tier
- pub fn try_from_roles(roles: HashSet<RoleId>) -> anyhow::Result<TeamUserTier> {
- if roles.contains(&RoleId::SubHaiku) {
- Ok(TeamUserTier::Haiku)
- } else if roles.contains(&RoleId::SubSonnet) {
- Ok(TeamUserTier::Sonnet)
- } else if roles.contains(&RoleId::SubOpus) {
- Ok(TeamUserTier::Opus)
- } else {
- anyhow::bail!("unable to extract team tier from user roles")
- }
- }
-}
+use roles_and_permissions::domain::model::UserRolesAndPermissionsError;
#[derive(
Eq,
@@ -121,9 +55,6 @@ pub struct TeamMember<'a> {
pub user_id: MacroUserIdStr<'a>,
/// The role of the team member
pub role: TeamRole,
- /// The tier of the team member
- #[cfg_attr(feature = "axum", schema(value_type = String))]
- pub tier: TeamUserTier,
}
/// A team with its members
@@ -177,17 +108,6 @@ pub struct PatchTeamUserRole {
pub role: TeamRole,
}
-/// Request to update a team user's tier
-#[derive(Debug, serde::Deserialize)]
-#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
-pub struct PatchTeamUserTierRequest {
- /// The team user you are updating
- #[cfg_attr(feature = "axum", schema(value_type = String))]
- pub team_user_id: MacroUserIdStr<'static>,
- /// The new tier of the team user
- pub new_tier: TeamUserTier,
-}
-
/// The Team struct
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
@@ -278,8 +198,6 @@ pub struct TeamInviteSnapshot<'a> {
pub created_at: DateTime<Utc>,
/// When the invite was last sent
pub last_sent_at: DateTime<Utc>,
- /// The tier being invited as
- pub tier: TeamUserTier,
}
/// Result of accepting a team invite, including the data needed to roll it back.
diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rs
index 6fc785cd71..44fc7140d3 100644
--- a/rust/cloud-storage/teams/src/domain/team_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs
@@ -9,9 +9,9 @@ use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr
use crate::domain::model::{
AcceptedTeamInvite, CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,
- PatchTeamRequest, PatchTeamUserTierRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
+ PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,
RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team, TeamError,
- TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamUserTier, TeamWithMembers,
+ TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamWithMembers,
};
/// The TeamChannelsRepository defines a set of actions related to team channels
@@ -50,7 +50,6 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
&self,
user_id: &MacroUserIdStr<'_>,
team_name: &str,
- team_user_tier: &TeamUserTier,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send;
/// Invites users to a team.
@@ -60,7 +59,7 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
&self,
team_id: &uuid::Uuid,
invited_by: &MacroUserIdStr<'_>,
- invites: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,
+ invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;
/// Marks the given team invites as sent by updating their last_sent_at timestamp.
@@ -203,14 +202,6 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<TeamMember<'_>, TeamError>> + Send;
- /// Patches the tier of the provided user id for the team
- fn patch_team_tier(
- &self,
- team_id: &uuid::Uuid,
- user_id: &MacroUserIdStr<'_>,
- team_tier: TeamUserTier,
- ) -> impl Future<Output = Result<(), TeamError>> + Send;
-
/// Patches the role of the provided user id for the team
fn patch_team_user_role(
&self,
@@ -235,7 +226,7 @@ pub trait TeamService: Clone + Send + Sync + 'static {
fn invite_users_to_team(
&self,
entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
- invites: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,
+ invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;
/// Remove user from a team.
@@ -326,11 +317,4 @@ pub trait TeamService: Clone + Send + Sync + 'static {
) -> impl Future<
Output = Result<HashSet<roles_and_permissions::domain::model::PermissionId>, TeamError>,
> + Send;
-
- /// Patches the team users tier and updates the stripe subscription accordingly
- fn patch_team_user_tier(
- &self,
- entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
- request: &PatchTeamUserTierRequest,
- ) -> impl Future<Output = Result<(), TeamError>> + Send;
}
diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rs
index 06f5d9e9e5..696a475997 100644
--- a/rust/cloud-storage/teams/src/domain/team_service.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service.rs
@@ -5,7 +5,6 @@ mod test;
use std::{collections::HashSet, sync::Arc};
-use anyhow::Context;
use entity_access::domain::models::{
AdminTeamRole, EntityAccessReceipt, MemberTeamRole, OwnerTeamRole,
};
@@ -24,51 +23,14 @@ use notification::domain::{models::SendNotificationRequestBuilder, service::Noti
use crate::domain::{
customer_repo::CustomerRepository,
model::{
- AcceptedTeamInvite, CreateTeamError, CustomerError, DeleteTeamError,
- InviteUsersToTeamError, JoinTeamError, PatchTeamRequest, PatchTeamUserTierRequest,
+ CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, PatchTeamRequest,
RemoveTeamInviteError, RemoveUserFromTeamError, RestorePermissionsForTeamMembersError,
RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,
- TeamMember, TeamRole, TeamUserTier, TeamWithMembers,
+ TeamMember, TeamRole, TeamWithMembers,
},
team_repo::{TeamChannelsRepository, TeamRepository, TeamService},
};
-#[derive(Debug, thiserror::Error)]
-enum GetTeamSubscriptionError {
- #[error(transparent)]
- Team(#[from] TeamError),
- #[error(transparent)]
- Customer(#[from] CustomerError),
- #[error(transparent)]
- Storage(#[from] anyhow::Error),
-}
-
-impl GetTeamSubscriptionError {
- fn into_join_team_error(self) -> JoinTeamError {
- match self {
- Self::Team(e) => JoinTeamError::TeamError(e),
- Self::Customer(e) => JoinTeamError::CustomerError(e),
- 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),
- }
- }
-
- fn into_team_error(self) -> TeamError {
- match self {
- Self::Team(e) => e,
- Self::Customer(e) => TeamError::StorageLayerError(e.into()),
- Self::Storage(e) => TeamError::StorageLayerError(e),
- }
- }
-}
-
/// Implementation of the TeamService using a TeamRepository
#[derive(Debug)]
pub struct TeamServiceImpl<TR, CR, TCR, URPS, NI>
@@ -144,62 +106,6 @@ where
URPS: UserRolesAndPermissionsService,
NI: NotificationIngress,
{
- /// 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)
- }
-
/// Sends an invite notification for a team invite
#[tracing::instrument(skip(self), err)]
async fn send_invite_notification(
@@ -225,67 +131,6 @@ where
Ok(())
}
-
- #[tracing::instrument(skip(self, accepted_invite))]
- async fn rollback_join_team(
- &self,
- accepted_invite: &AcceptedTeamInvite<'_>,
- roles_added: bool,
- channels_added: bool,
- ) {
- if channels_added {
- self.team_channels_repository
- .remove_team_member_from_channels(
- &accepted_invite.member.team_id,
- &accepted_invite.member.user_id,
- )
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to roll back team channel membership after customer error"))
- .ok();
- }
-
- if roles_added {
- let roles_to_remove = vec![
- RoleId::TeamSubscriber,
- RoleId::from(accepted_invite.member.tier),
- ];
- self.user_roles_and_permissions_service
- .dangerous_remove_roles_from_user(
- &accepted_invite.member.user_id,
- &non_empty::NonEmpty::new(roles_to_remove.as_slice()).unwrap(),
- )
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to roll back team roles after customer error"))
- .ok();
- }
-
- self.team_repository
- .rollback_accept_team_invite(accepted_invite)
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to roll back accepted team invite after customer error"))
- .ok();
- }
-
- #[tracing::instrument(skip(self, removed_member))]
- async fn rollback_remove_user_from_team(
- &self,
- removed_member: &TeamMember<'_>,
- channels_removed: bool,
- ) {
- self.team_repository
- .rollback_remove_user_from_team(removed_member)
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to roll back removed team member after customer error"))
- .ok();
-
- if channels_removed {
- self.team_channels_repository
- .add_team_member_to_channels(&removed_member.team_id, &removed_member.user_id)
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to restore team channel membership after customer error"))
- .ok();
- }
- }
}
impl<TR, CR, TCR, URPS, NI> TeamService for TeamServiceImpl<TR, CR, TCR, URPS, NI>
@@ -302,25 +147,14 @@ where
user_id: &MacroUserIdStr<'_>,
team_name: &str,
) -> Result<Team, CreateTeamError> {
- let user_roles = self
- .user_roles_and_permissions_service
- .get_user_roles(user_id)
- .await
- .map_err(|e| CreateTeamError::StorageLayerError(e.into()))?;
-
- let team_user_tier =
- TeamUserTier::try_from_roles(user_roles).map_err(CreateTeamError::StorageLayerError)?;
-
- self.team_repository
- .create_team(user_id, team_name, &team_user_tier)
- .await
+ self.team_repository.create_team(user_id, team_name).await
}
#[tracing::instrument(skip(self), err)]
async fn invite_users_to_team(
&self,
entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
- invites: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,
+ invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {
let team_id =
macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
@@ -389,38 +223,15 @@ where
let team_id =
macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
- let removed_member = self
- .team_repository
+ self.team_repository
.remove_user_from_team(&team_id, user_id)
.await?;
self.team_channels_repository
.remove_team_member_from_channels(&team_id, user_id)
.await?;
- let channels_removed = true;
-
- let subscription_id = match self.get_team_subscription(&team_id).await {
- Ok(subscription_id) => subscription_id,
- Err(GetTeamSubscriptionError::Customer(e)) => {
- self.rollback_remove_user_from_team(&removed_member, channels_removed)
- .await;
- return Err(RemoveUserFromTeamError::CustomerError(e));
- }
- Err(e) => return Err(e.into_remove_user_from_team_error()),
- };
- // Decrement the quantity of the subscription
- if let Err(e) = self
- .customer_repository
- .decrease_subscription_quantity(&subscription_id, removed_member.tier)
- .await
- {
- self.rollback_remove_user_from_team(&removed_member, channels_removed)
- .await;
- return Err(RemoveUserFromTeamError::CustomerError(e));
- }
-
- let roles_to_remove = vec![RoleId::TeamSubscriber, RoleId::from(removed_member.tier)];
+ let roles_to_remove = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
self.user_roles_and_permissions_service
.dangerous_remove_roles_from_user(
@@ -535,40 +346,17 @@ where
let team_member = accepted_invite.member.clone();
// 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::from(team_member.tier)];
+ let roles_to_add = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
let roles = non_empty::NonEmpty::new(roles_to_add.as_slice()).unwrap();
self.user_roles_and_permissions_service
.dangerous_upsert_roles_for_user(user_id, roles)
.await
.map_err(JoinTeamError::AddRolesToUserError)?;
- let roles_added = true;
self.team_channels_repository
.add_team_member_to_channels(&team_member.team_id, user_id)
.await?;
- let channels_added = true;
-
- let subscription_id = match self.get_team_subscription(&team_member.team_id).await {
- Ok(subscription_id) => subscription_id,
- Err(GetTeamSubscriptionError::Customer(e)) => {
- self.rollback_join_team(&accepted_invite, roles_added, channels_added)
- .await;
- return Err(JoinTeamError::CustomerError(e));
- }
- Err(e) => return Err(e.into_join_team_error()),
- };
-
- // Increment the quantity of the subscription by the number of emails
- if let Err(e) = self
- .customer_repository
- .increase_subscription_quantity(&subscription_id, team_member.tier)
- .await
- {
- self.rollback_join_team(&accepted_invite, roles_added, channels_added)
- .await;
- return Err(JoinTeamError::CustomerError(e));
- }
Ok(team_member)
}
@@ -585,7 +373,7 @@ where
}
for member in members {
- let roles_to_remove = vec![RoleId::TeamSubscriber, RoleId::from(member.tier)];
+ let roles_to_remove = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
self.user_roles_and_permissions_service
.dangerous_remove_roles_from_user(
@@ -611,7 +399,7 @@ where
}
for member in members {
- let roles = vec![RoleId::TeamSubscriber, RoleId::from(member.tier)];
+ let roles = vec![RoleId::TeamSubscriber, RoleId::SubOpus];
let roles = non_empty::NonEmpty::new(roles.as_slice()).unwrap();
self.user_roles_and_permissions_service
@@ -705,59 +493,4 @@ where
.await
.map_err(|e| TeamError::StorageLayerError(e.into()))
}
-
- #[tracing::instrument(skip(self), err)]
- async fn patch_team_user_tier(
- &self,
- entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,
- request: &PatchTeamUserTierRequest,
- ) -> Result<(), TeamError> {
- let team_id =
- macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();
- let team_member = self
- .team_repository
- .get_team_member(&team_id, &request.team_user_id)
- .await?;
-
- if team_member.tier == request.new_tier {
- return Err(TeamError::BadRequest(
- "team tier cannot be the same as before".to_string(),
- ));
- }
-
- let team_subscription_id = self
- .get_team_subscription(&team_id)
- .await
- .map_err(GetTeamSubscriptionError::into_team_error)?;
-
- self.team_repository
- .patch_team_tier(&team_id, &request.team_user_id, request.new_tier)
- .await?;
-
- // ensure team member has old tier removed
- self.user_roles_and_permissions_service
- .dangerous_remove_roles_from_user(
- &request.team_user_id,
- &non_empty::NonEmpty::new(vec![RoleId::from(team_member.tier)].as_slice()).unwrap(),
- )
- .await
- .map_err(|e| TeamError::StorageLayerError(e.into()))?;
-
- // ensure team member has new tier added
- self.user_roles_and_permissions_service
- .dangerous_upsert_roles_for_user(
- &request.team_user_id,
- non_empty::NonEmpty::new(vec![RoleId::from(request.new_tier)].as_slice()).unwrap(),
- )
- .await
- .map_err(|e| TeamError::StorageLayerError(e.into()))?;
-
- // TODO: handle fallback on stripe failure
- self.customer_repository
- .update_subscription_tier(&team_subscription_id, team_member.tier, request.new_tier)
- .await
- .map_err(|e| TeamError::StorageLayerError(e.into()))?;
-
- Ok(())
- }
}
diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rs
index 3e18c0cd80..66f50c3126 100644
--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs
@@ -37,8 +37,7 @@ use crate::domain::{
model::{
AcceptedTeamInvite, CreateSubscriptionArgs, CustomerError, PatchTeamRequest,
PatchTeamUserRole, RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError,
- TeamInvite, TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamRole, TeamUserTier,
- TeamWithMembers,
+ TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamWithMembers,
},
team_repo::{TeamChannelsRepository, TeamRepository},
};
@@ -91,34 +90,6 @@ impl MockTeamRepository {
self.team_for_get_by_id = Some(team);
self
}
-
- fn with_team_subscription_id(
- mut self,
- subscription_id: Option<stripe::SubscriptionId>,
- ) -> Self {
- self.team_subscription_id = subscription_id;
- self
- }
-
- fn with_stripe_customer_id(mut self, customer_id: stripe::CustomerId) -> Self {
- self.stripe_customer_id = Some(customer_id);
- self
- }
-
- fn with_accepted_invite(mut self, accepted_invite: AcceptedTeamInvite<'static>) -> Self {
- self.accepted_invite = Some(accepted_invite);
- self
- }
-
- fn with_removed_member(mut self, removed_member: TeamMember<'static>) -> Self {
- self.removed_member = Some(removed_member);
- self
- }
-
- fn with_fail_rollback_accept(mut self) -> Self {
- self.fail_rollback_accept = true;
- self
- }
}
impl TeamRepository for MockTeamRepository {
@@ -142,7 +113,6 @@ impl TeamRepository for MockTeamRepository {
&self,
_: &MacroUserIdStr<'_>,
_: &str,
- _: &TeamUserTier,
) -> impl Future<Output = Result<Team, CreateTeamError>> + Send {
async { unimplemented!() }
}
@@ -151,7 +121,7 @@ impl TeamRepository for MockTeamRepository {
&self,
_: &uuid::Uuid,
_: &MacroUserIdStr<'_>,
- _: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,
+ _: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send {
let invites = self.invites_to_return.clone();
async move { Ok(invites) }
@@ -347,15 +317,6 @@ impl TeamRepository for MockTeamRepository {
async { unimplemented!() }
}
- fn patch_team_tier(
- &self,
- _: &uuid::Uuid,
- _: &MacroUserIdStr<'_>,
- _: TeamUserTier,
- ) -> impl Future<Output = Result<(), TeamError>> + Send {
- async { unimplemented!() }
- }
-
fn patch_team_user_role(
&self,
team_id: &uuid::Uuid,
@@ -400,31 +361,6 @@ impl CustomerRepository for MockCustomerRepository {
async { unimplemented!() }
}
- fn increase_subscription_quantity(
- &self,
- _: &stripe::SubscriptionId,
- _: TeamUserTier,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send {
- async { unimplemented!() }
- }
-
- fn decrease_subscription_quantity(
- &self,
- _: &stripe::SubscriptionId,
- _: TeamUserTier,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send {
- async { unimplemented!() }
- }
-
- fn update_subscription_tier(
- &self,
- _: &stripe::SubscriptionId,
- _: TeamUserTier,
- _: TeamUserTier,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send {
- async { unimplemented!() }
- }
-
fn cancel_subscription(
&self,
_: &stripe::SubscriptionId,
@@ -549,177 +485,6 @@ impl NotificationIngress for MockNotificationIngress {
}
}
-// -- Rollback test mocks --
-
-#[derive(Clone, Default)]
-struct RecordingTeamChannelsRepository {
- add_calls: Arc<Mutex<usize>>,
- remove_calls: Arc<Mutex<usize>>,
-}
-
-impl TeamChannelsRepository for RecordingTeamChannelsRepository {
- fn add_team_member_to_channels(
- &self,
- _: &uuid::Uuid,
- _: &MacroUserIdStr<'_>,
- ) -> impl Future<Output = Result<(), TeamError>> + Send {
- *self.add_calls.lock().unwrap() += 1;
- async { Ok(()) }
- }
-
- fn remove_team_member_from_channels(
- &self,
- _: &uuid::Uuid,
- _: &MacroUserIdStr<'_>,
- ) -> impl Future<Output = Result<(), TeamError>> + Send {
- *self.remove_calls.lock().unwrap() += 1;
- async { Ok(()) }
- }
-}
-
-#[derive(Clone, Default)]
-struct RecordingUserRolesAndPermissionsService {
- upsert_calls: Arc<Mutex<usize>>,
- remove_calls: Arc<Mutex<usize>>,
-}
-
-impl UserRolesAndPermissionsService for RecordingUserRolesAndPermissionsService {
- fn get_user_roles(
- &self,
- _: &MacroUserIdStr<'_>,
- ) -> impl Future<Output = Result<HashSet<RoleId>, UserRolesAndPermissionsError>> + Send {
- async { unimplemented!() }
- }
-
- fn get_user_permissions(
- &self,
- _: &MacroUserIdStr<'_>,
- ) -> impl Future<Output = Result<HashSet<PermissionId>, UserRolesAndPermissionsError>> + Send
- {
- async { unimplemented!() }
- }
-
- fn update_user_roles_and_permissions_for_subscription(
- &self,
- _: Email<Lowercase<'_>>,
- _: roles_and_permissions::domain::model::SubscriptionStatus,
- _: roles_and_permissions::domain::model::ProductTier,
- ) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send {
- async { unimplemented!() }
- }
-
- fn dangerous_upsert_roles_for_user(
- &self,
- _: &MacroUserIdStr<'_>,
- _: non_empty::NonEmpty<&[RoleId]>,
- ) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send {
- *self.upsert_calls.lock().unwrap() += 1;
- async { Ok(()) }
- }
-
- fn dangerous_remove_roles_from_user(
- &self,
- _: &MacroUserIdStr<'_>,
- _: &non_empty::NonEmpty<&[RoleId]>,
- ) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send {
- *self.remove_calls.lock().unwrap() += 1;
- async { Ok(()) }
- }
-}
-
-#[derive(Clone, Default)]
-struct ConfigurableCustomerRepository {
- fail_get_subscription: bool,
- fail_convert: bool,
- fail_increase: bool,
- fail_decrease: bool,
-}
-
-impl CustomerRepository for ConfigurableCustomerRepository {
- fn convert_subscription_to_team(
- &self,
- _: &stripe::SubscriptionId,
- _: &uuid::Uuid,
- _: &MacroUserIdStr<'_>,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send {
- let fail = self.fail_convert;
- async move {
- if fail {
- Err(CustomerError::SubscriptionNotActive)
- } else {
- Ok(())
- }
- }
- }
-
- fn get_subscription_id_for_customer(
- &self,
- _: &stripe::CustomerId,
- ) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send {
- let fail = self.fail_get_subscription;
- async move {
- if fail {
- Err(CustomerError::SubscriptionNotActive)
- } else {
- Ok("sub_1".parse().unwrap())
- }
- }
- }
-
- fn create_subscription(
- &self,
- _: CreateSubscriptionArgs,
- ) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send {
- async { unimplemented!() }
- }
-
- fn increase_subscription_quantity(
- &self,
- _: &stripe::SubscriptionId,
- _: TeamUserTier,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send {
- let fail = self.fail_increase;
- async move {
- if fail {
- Err(CustomerError::SubscriptionNotActive)
- } else {
- Ok(())
- }
- }
- }
-
- fn decrease_subscription_quantity(
- &self,
- _: &stripe::SubscriptionId,
- _: TeamUserTier,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send {
- let fail = self.fail_decrease;
- async move {
- if fail {
- Err(CustomerError::SubscriptionNotActive)
- } else {
- Ok(())
- }
- }
- }
-
- fn update_subscription_tier(
- &self,
- _: &stripe::SubscriptionId,
- _: TeamUserTier,
- _: TeamUserTier,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send {
- async { unimplemented!() }
- }
-
- fn cancel_subscription(
- &self,
- _: &stripe::SubscriptionId,
- ) -> impl Future<Output = Result<(), CustomerError>> + Send {
- async { unimplemented!() }
- }
-}
-
// -- Helpers --
fn make_invite(email: &str, invite_id: uuid::Uuid, team_id: uuid::Uuid) -> TeamInvite<'static> {
@@ -776,24 +541,15 @@ async fn test_invite_marks_sent_only_for_successful_notifications() {
let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let invites = vec![
- (
- Email::parse_from_str("[email protected]")
- .unwrap()
- .lowercase(),
- TeamUserTier::Haiku,
- ),
- (
- Email::parse_from_str("[email protected]")
- .unwrap()
- .lowercase(),
- TeamUserTier::Haiku,
- ),
- (
- Email::parse_from_str("[email protected]")
- .unwrap()
- .lowercase(),
- TeamUserTier::Haiku,
- ),
+ Email::parse_from_str("[email protected]")
+ .unwrap()
+ .lowercase(),
+ Email::parse_from_str("[email protected]")
+ .unwrap()
+ .lowercase(),
+ Email::parse_from_str("[email protected]")
+ .unwrap()
+ .lowercase(),
];
let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();
@@ -832,12 +588,11 @@ async fn test_invite_does_not_call_mark_sent_when_all_notifications_fail() {
build_service(invites, fail_indices, mark_sent_calls.clone());
let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
- let invites = vec![(
+ let invites = vec![
Email::parse_from_str("[email protected]")
.unwrap()
.lowercase(),
- TeamUserTier::Haiku,
- )];
+ ];
let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();
let receipt = test_team_receipt::<OwnerTeamRole>(team_id, &invited_by);
@@ -872,18 +627,12 @@ async fn test_invite_marks_all_sent_when_all_notifications_succeed() {
let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let invites = vec![
- (
- Email::parse_from_str("[email protected]")
- .unwrap()
- .lowercase(),
- TeamUserTier::Haiku,
- ),
- (
- Email::parse_from_str("[email protected]")
- .unwrap()
- .lowercase(),
- TeamUserTier::Haiku,
- ),
+ Email::parse_from_str("[email protected]")
+ .unwrap()
+ .lowercase(),
+ Email::parse_from_str("[email protected]")
+ .unwrap()
+ .lowercase(),
];
let invites = non_empty::NonEmpty::new(invites.as_slice()).unwrap();
@@ -1055,253 +804,3 @@ async fn test_patch_team_empty_role_updates() {
assert_eq!(name_calls.len(), 1);
assert_eq!(name_calls[0], (team_id, Some("New Name".to_string())));
}
-
-fn make_member(team_id: uuid::Uuid, user_id: &str, tier: TeamUserTier) -> TeamMember<'static> {
- TeamMember {
- team_id,
- user_id: MacroUserIdStr::parse_from_str(user_id)
- .unwrap()
- .into_owned(),
- role: TeamRole::Member,
- tier,
- }
-}
-
-fn make_accepted_invite(team_id: uuid::Uuid, user_id: &str) -> AcceptedTeamInvite<'static> {
- let member = make_member(team_id, user_id, TeamUserTier::Opus);
- AcceptedTeamInvite {
- member,
- invite: TeamInviteSnapshot {
- id: uuid::Uuid::from_u128(999),
- team_id,
- email: Email::parse_from_str("[email protected]")
- .unwrap()
- .into_owned()
- .lowercase(),
- team_role: TeamRole::Member,
- invited_by: MacroUserIdStr::parse_from_str("macro|[email protected]")
- .unwrap()
- .into_owned(),
- created_at: chrono::Utc::now(),
- last_sent_at: chrono::Utc::now(),
- tier: TeamUserTier::Opus,
- },
- }
-}
-
-fn build_rollback_service(
- team_repo: MockTeamRepository,
- customer_repo: ConfigurableCustomerRepository,
-) -> (
- impl TeamService,
- Arc<Mutex<usize>>,
- Arc<Mutex<usize>>,
- Arc<Mutex<usize>>,
- Arc<Mutex<usize>>,
-) {
- let channel_repo = RecordingTeamChannelsRepository::default();
- let channel_add_calls = channel_repo.add_calls.clone();
- let channel_remove_calls = channel_repo.remove_calls.clone();
- let roles_service = RecordingUserRolesAndPermissionsService::default();
- let role_upsert_calls = roles_service.upsert_calls.clone();
- let role_remove_calls = roles_service.remove_calls.clone();
- let notification_ingress = Arc::new(MockNotificationIngress::new(HashSet::new()));
-
- let service = TeamServiceImpl::new(
- team_repo,
- customer_repo,
- channel_repo,
- roles_service,
- notification_ingress,
- );
-
- (
- service,
- channel_add_calls,
- channel_remove_calls,
- role_upsert_calls,
- role_remove_calls,
- )
-}
-
-#[tokio::test]
-async fn test_join_team_rolls_back_when_increase_subscription_quantity_fails() {
- let team_id = uuid::Uuid::from_u128(1);
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
- let accepted_invite = make_accepted_invite(team_id, user_id.as_ref());
- let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));
- let team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
- .with_team_subscription_id(Some("sub_1".parse().unwrap()))
- .with_accepted_invite(accepted_invite);
- let rollback_accept_calls = team_repo.rollback_accept_calls.clone();
-
- let (service, channel_add_calls, channel_remove_calls, role_upsert_calls, role_remove_calls) =
- build_rollback_service(
- team_repo,
- ConfigurableCustomerRepository {
- fail_increase: true,
- ..Default::default()
- },
- );
-
- let err = service
- .join_team(&uuid::Uuid::from_u128(999), &user_id)
- .await
- .err()
- .unwrap();
-
- assert!(matches!(err, JoinTeamError::CustomerError(_)));
- assert_eq!(*rollback_accept_calls.lock().unwrap(), 1);
- assert_eq!(*channel_add_calls.lock().unwrap(), 1);
- assert_eq!(*channel_remove_calls.lock().unwrap(), 1);
- assert_eq!(*role_upsert_calls.lock().unwrap(), 1);
- assert_eq!(*role_remove_calls.lock().unwrap(), 1);
-}
-
-#[tokio::test]
-async fn test_join_team_rolls_back_when_get_team_subscription_customer_call_fails() {
- let team_id = uuid::Uuid::from_u128(1);
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
- let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
- .unwrap()
- .into_owned();
- let accepted_invite = make_accepted_invite(team_id, user_id.as_ref());
- let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));
- let team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
- .with_team(Team::new(team_id, "Test Team".to_string(), owner_id))
- .with_team_subscription_id(None)
- .with_stripe_customer_id("cus_123".parse().unwrap())
- .with_accepted_invite(accepted_invite);
- let rollback_accept_calls = team_repo.rollback_accept_calls.clone();
-
- let (service, channel_add_calls, channel_remove_calls, role_upsert_calls, role_remove_calls) =
- build_rollback_service(
- team_repo,
- ConfigurableCustomerRepository {
- fail_get_subscription: true,
- ..Default::default()
- },
- );
-
- let err = service
- .join_team(&uuid::Uuid::from_u128(999), &user_id)
- .await
- .err()
- .unwrap();
-
- assert!(matches!(err, JoinTeamError::CustomerError(_)));
- assert_eq!(*rollback_accept_calls.lock().unwrap(), 1);
- assert_eq!(*channel_add_calls.lock().unwrap(), 1);
- assert_eq!(*channel_remove_calls.lock().unwrap(), 1);
- assert_eq!(*role_upsert_calls.lock().unwrap(), 1);
- assert_eq!(*role_remove_calls.lock().unwrap(), 1);
-}
-
-#[tokio::test]
-async fn test_remove_user_from_team_rolls_back_when_decrease_subscription_quantity_fails() {
- let team_id = uuid::Uuid::from_u128(1);
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
- let removed_member = make_member(team_id, user_id.as_ref(), TeamUserTier::Sonnet);
- let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));
- let team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
- .with_team_subscription_id(Some("sub_1".parse().unwrap()))
- .with_removed_member(removed_member);
- let rollback_remove_calls = team_repo.rollback_remove_calls.clone();
-
- let (service, channel_add_calls, channel_remove_calls, _role_upsert_calls, role_remove_calls) =
- build_rollback_service(
- team_repo,
- ConfigurableCustomerRepository {
- fail_decrease: true,
- ..Default::default()
- },
- );
-
- let receipt = test_team_receipt::<OwnerTeamRole>(team_id, &user_id);
- let err = service
- .remove_user_from_team(receipt, &user_id)
- .await
- .err()
- .unwrap();
-
- assert!(matches!(err, RemoveUserFromTeamError::CustomerError(_)));
- assert_eq!(*rollback_remove_calls.lock().unwrap(), 1);
- assert_eq!(*channel_remove_calls.lock().unwrap(), 1);
- assert_eq!(*channel_add_calls.lock().unwrap(), 1);
- assert_eq!(*role_remove_calls.lock().unwrap(), 0);
-}
-
-#[tokio::test]
-async fn test_remove_user_from_team_rolls_back_when_get_team_subscription_customer_call_fails() {
- let team_id = uuid::Uuid::from_u128(1);
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
- let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
- .unwrap()
- .into_owned();
- let removed_member = make_member(team_id, user_id.as_ref(), TeamUserTier::Sonnet);
- let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));
- let team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
- .with_team(Team::new(team_id, "Test Team".to_string(), owner_id))
- .with_team_subscription_id(None)
- .with_stripe_customer_id("cus_123".parse().unwrap())
- .with_removed_member(removed_member);
- let rollback_remove_calls = team_repo.rollback_remove_calls.clone();
-
- let (service, channel_add_calls, channel_remove_calls, _role_upsert_calls, role_remove_calls) =
- build_rollback_service(
- team_repo,
- ConfigurableCustomerRepository {
- fail_get_subscription: true,
- ..Default::default()
- },
- );
-
- let receipt = test_team_receipt::<OwnerTeamRole>(team_id, &user_id);
- let err = service
- .remove_user_from_team(receipt, &user_id)
- .await
- .err()
- .unwrap();
-
- assert!(matches!(err, RemoveUserFromTeamError::CustomerError(_)));
- assert_eq!(*rollback_remove_calls.lock().unwrap(), 1);
- assert_eq!(*channel_remove_calls.lock().unwrap(), 1);
- assert_eq!(*channel_add_calls.lock().unwrap(), 1);
- assert_eq!(*role_remove_calls.lock().unwrap(), 0);
-}
-
-#[tokio::test]
-async fn test_join_team_returns_original_customer_error_when_rollback_fails() {
- let team_id = uuid::Uuid::from_u128(1);
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
- let accepted_invite = make_accepted_invite(team_id, user_id.as_ref());
- let mark_sent_calls = Arc::new(Mutex::new(Vec::new()));
- let team_repo = MockTeamRepository::new(Vec::new(), "Test Team", mark_sent_calls)
- .with_team_subscription_id(Some("sub_1".parse().unwrap()))
- .with_accepted_invite(accepted_invite)
- .with_fail_rollback_accept();
- let rollback_accept_calls = team_repo.rollback_accept_calls.clone();
-
- let (
- service,
- _channel_add_calls,
- _channel_remove_calls,
- _role_upsert_calls,
- _role_remove_calls,
- ) = build_rollback_service(
- team_repo,
- ConfigurableCustomerRepository {
- fail_increase: true,
- ..Default::default()
- },
- );
-
- let err = service
- .join_team(&uuid::Uuid::from_u128(999), &user_id)
- .await
- .err()
- .unwrap();
-
- assert!(matches!(err, JoinTeamError::CustomerError(_)));
- assert_eq!(*rollback_accept_calls.lock().unwrap(), 1);
-}
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs
index 0515539f81..b438a0431b 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/invite_to_team.rs
@@ -6,10 +6,7 @@ use entity_access::{
use macro_user_id::{email::Email, lowercased::Lowercase};
use model_error_response::ErrorResponse;
-use crate::domain::{
- model::{InviteUsersToTeamError, TeamUserTier},
- team_repo::TeamService,
-};
+use crate::domain::{model::InviteUsersToTeamError, team_repo::TeamService};
use super::TeamRouterState;
@@ -18,9 +15,6 @@ use super::TeamRouterState;
pub struct InviteEntry {
/// The email of the user to invite
pub email: String,
- /// The tier for this user (defaults to Haiku if not provided)
- #[serde(default)]
- pub tier: TeamUserTier,
}
/// The request body to invite a user to a team
@@ -99,12 +93,10 @@ pub async fn handler<T: TeamService, Eas: EntityAccessService>(
State(state): State<TeamRouterState<T, Eas>>,
Json(req): Json<InviteToTeamRequest>,
) -> Result<StatusCode, InviteToTeamError> {
- let parsed: Vec<Result<(Email<Lowercase<'_>>, TeamUserTier), _>> = req
+ let parsed: Vec<Result<Email<Lowercase<'_>>, _>> = req
.invites
.iter()
- .map(|entry| {
- Email::parse_from_str(&entry.email).map(|email| (email.lowercase(), entry.tier))
- })
+ .map(|entry| Email::parse_from_str(&entry.email).map(|email| email.lowercase()))
.collect();
if parsed.iter().any(|e| e.is_err()) {
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
index 9af8a374ae..c780a0d503 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
@@ -22,8 +22,6 @@ pub mod join_team;
pub mod middleware;
/// Update a team.
pub mod patch_team;
-/// Patch a team users tier.
-pub mod patch_team_user_tier;
/// Reject a team invitation.
pub mod reject_invitation;
/// Remove a user from a team.
@@ -90,7 +88,6 @@ where
.route("/user/invites", get(get_user_invites::handler::<T, Eas>))
.route("/", get(get_team::handler::<T, Eas>))
.route("/", patch(patch_team::handler::<T, Eas>))
- .route("/tier", patch(patch_team_user_tier::handler::<T, Eas>))
.route("/", delete(delete_team::handler::<T, Eas>))
.route("/invites", get(get_team_invites::handler::<T, Eas>))
.route("/invite", post(invite_to_team::handler::<T, Eas>))
diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_user_tier.rs b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_user_tier.rs
deleted file mode 100644
index ed354bf5a1..0000000000
--- a/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_user_tier.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-use axum::{Json, extract::State};
-use entity_access::{
- domain::{models::OwnerTeamRole, ports::EntityAccessService},
- inbound::axum_extractors::MacroUserTeamExtractor,
-};
-use model_error_response::ErrorResponse;
-
-use crate::domain::{
- model::{PatchTeamUserTierRequest, TeamError},
- team_repo::TeamService,
-};
-
-use super::TeamRouterState;
-
-/// Updates a team.
-#[utoipa::path(
- patch,
- path = "/team/tier",
- operation_id = "patch_team_user_tier",
- request_body = PatchTeamUserTierRequest,
- responses(
- (status = 200),
- (status = 400, body = ErrorResponse),
- (status = 401, body = ErrorResponse),
- (status = 404, body = ErrorResponse),
- (status = 500, body = ErrorResponse),
- ),
-)]
-#[tracing::instrument(skip_all, err)]
-pub async fn handler<T: TeamService, Eas: EntityAccessService>(
- access: MacroUserTeamExtractor<OwnerTeamRole, Eas>,
- State(state): State<TeamRouterState<T, Eas>>,
- Json(req): Json<PatchTeamUserTierRequest>,
-) -> Result<(), TeamError> {
- state
- .service
- .patch_team_user_tier(access.entity_access_receipt, &req)
- .await?;
- Ok(())
-}
diff --git a/rust/cloud-storage/teams/src/outbound/customer_repo.rs b/rust/cloud-storage/teams/src/outbound/customer_repo.rs
index 1b4cb85dec..6157179e41 100644
--- a/rust/cloud-storage/teams/src/outbound/customer_repo.rs
+++ b/rust/cloud-storage/teams/src/outbound/customer_repo.rs
@@ -6,7 +6,7 @@ use stripe::{CreateSubscription, CreateSubscriptionItems, UpdateSubscription};
use crate::domain::{
customer_repo::CustomerRepository,
- model::{CreateSubscriptionArgs, CustomerError, TeamUserTier},
+ model::{CreateSubscriptionArgs, CustomerError},
};
/// The stripe price ids for all tiers
@@ -20,17 +20,6 @@ pub struct StripePriceIds {
pub opus: String,
}
-impl StripePriceIds {
- /// Convert the team user tier to the price id
- fn price_id_for_tier(&self, team_user_tier: &TeamUserTier) -> &str {
- match team_user_tier {
- TeamUserTier::Haiku => &self.haiku,
- TeamUserTier::Sonnet => &self.sonnet,
- TeamUserTier::Opus => &self.opus,
- }
- }
-}
-
/// The CustomerRepositoryImpl struct is a wrapper around a stripe::Client connected to stripe.
#[derive(Clone)]
pub struct CustomerRepositoryImpl {
@@ -73,140 +62,6 @@ impl CustomerRepository for CustomerRepositoryImpl {
Ok(subscription.id)
}
- #[tracing::instrument(skip(self), err)]
- async fn increase_subscription_quantity(
- &self,
- subscription_id: &stripe::SubscriptionId,
- team_user_tier: TeamUserTier,
- ) -> Result<(), CustomerError> {
- // Get existing subscription quantity
- let subscription = stripe::Subscription::retrieve(&self.client, subscription_id, &[])
- .await
- .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
-
- match subscription.status {
- stripe::SubscriptionStatus::Active => (),
- _ => {
- return Err(CustomerError::SubscriptionNotActive);
- }
- }
-
- let tier_price_id = self.stripe_price_ids.price_id_for_tier(&team_user_tier);
-
- // Find existing subscription item for this tier's price
- let existing_item = subscription.items.data.iter().find(|item| {
- item.price
- .as_ref()
- .map(|p| p.id == tier_price_id)
- .unwrap_or(false)
- });
-
- let items = match existing_item {
- // Tier line item exists — increment quantity
- Some(item) => {
- let current_quantity = item.quantity.unwrap_or(1);
- vec![stripe::UpdateSubscriptionItems {
- id: Some(item.id.to_string()),
- quantity: Some(current_quantity + 1),
- ..Default::default()
- }]
- }
- // Tier line item doesn't exist — create with quantity 1
- None => {
- vec![stripe::UpdateSubscriptionItems {
- price: Some(tier_price_id.to_string()),
- quantity: Some(1),
- ..Default::default()
- }]
- }
- };
-
- let update_params = UpdateSubscription {
- items: Some(items),
- proration_behavior: Some(
- stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice,
- ),
- ..Default::default()
- };
-
- stripe::Subscription::update(&self.client, subscription_id, update_params)
- .await
- .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
-
- Ok(())
- }
-
- #[tracing::instrument(skip(self), err)]
- async fn decrease_subscription_quantity(
- &self,
- subscription_id: &stripe::SubscriptionId,
- team_user_tier: TeamUserTier,
- ) -> Result<(), CustomerError> {
- let subscription = stripe::Subscription::retrieve(&self.client, subscription_id, &[])
- .await
- .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
-
- if subscription.status != stripe::SubscriptionStatus::Active {
- return Err(CustomerError::SubscriptionNotActive);
- }
-
- let tier_price_id = self.stripe_price_ids.price_id_for_tier(&team_user_tier);
-
- let item = subscription
- .items
- .data
- .iter()
- .find(|item| {
- item.price
- .as_ref()
- .map(|p| p.id == tier_price_id)
- .unwrap_or(false)
- })
- .ok_or_else(|| {
- CustomerError::StorageLayerError(anyhow::anyhow!(
- "No subscription item found for tier {:?}",
- team_user_tier
- ))
- })?;
-
- let current_quantity = item.quantity.unwrap_or(1);
-
- // If this is the last item across all tiers, cancel the subscription
- if current_quantity <= 1 && subscription.items.data.len() == 1 {
- return self.cancel_subscription(subscription_id).await;
- }
-
- let items = if current_quantity <= 1 {
- // Last seat on this tier — delete the line item
- vec![stripe::UpdateSubscriptionItems {
- id: Some(item.id.to_string()),
- deleted: Some(true),
- ..Default::default()
- }]
- } else {
- // Decrement quantity
- vec![stripe::UpdateSubscriptionItems {
- id: Some(item.id.to_string()),
- quantity: Some(current_quantity - 1),
- ..Default::default()
- }]
- };
-
- let update_params = UpdateSubscription {
- items: Some(items),
- proration_behavior: Some(
- stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice,
- ),
- ..Default::default()
- };
-
- stripe::Subscription::update(&self.client, subscription_id, update_params)
- .await
- .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
-
- Ok(())
- }
-
#[tracing::instrument(skip(self), err)]
async fn cancel_subscription(
&self,
@@ -263,107 +118,4 @@ impl CustomerRepository for CustomerRepositoryImpl {
.map(|sub| sub.id)
.ok_or(CustomerError::SubscriptionNotActive)
}
-
- #[tracing::instrument(skip(self), err)]
- async fn update_subscription_tier(
- &self,
- subscription_id: &stripe::SubscriptionId,
- old_team_user_tier: TeamUserTier,
- new_team_user_tier: TeamUserTier,
- ) -> Result<(), CustomerError> {
- if old_team_user_tier == new_team_user_tier {
- tracing::warn!("tried to update tier to the same tier");
- return Ok(());
- }
-
- let subscription = stripe::Subscription::retrieve(&self.client, subscription_id, &[])
- .await
- .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
-
- if subscription.status != stripe::SubscriptionStatus::Active {
- return Err(CustomerError::SubscriptionNotActive);
- }
-
- let old_price_id = self.stripe_price_ids.price_id_for_tier(&old_team_user_tier);
- let new_price_id = self.stripe_price_ids.price_id_for_tier(&new_team_user_tier);
-
- // Find old tier line item — must exist
- let old_item = subscription
- .items
- .data
- .iter()
- .find(|item| {
- item.price
- .as_ref()
- .map(|p| p.id == old_price_id)
- .unwrap_or(false)
- })
- .ok_or_else(|| {
- CustomerError::StorageLayerError(anyhow::anyhow!(
- "No subscription item found for old tier {:?}",
- old_team_user_tier
- ))
- })?;
-
- let old_quantity = old_item.quantity.unwrap_or(1);
-
- // Find new tier line item — may or may not exist
- let new_item = subscription.items.data.iter().find(|item| {
- item.price
- .as_ref()
- .map(|p| p.id == new_price_id)
- .unwrap_or(false)
- });
-
- let mut items = Vec::with_capacity(2);
-
- // Old tier: delete if last seat, otherwise decrement
- if old_quantity <= 1 {
- items.push(stripe::UpdateSubscriptionItems {
- id: Some(old_item.id.to_string()),
- deleted: Some(true),
- ..Default::default()
- });
- } else {
- items.push(stripe::UpdateSubscriptionItems {
- id: Some(old_item.id.to_string()),
- quantity: Some(old_quantity - 1),
- ..Default::default()
- });
- }
-
- // New tier: increment if exists, otherwise create with quantity 1
- match new_item {
- Some(item) => {
- let current_quantity = item.quantity.unwrap_or(1);
- items.push(stripe::UpdateSubscriptionItems {
- id: Some(item.id.to_string()),
- quantity: Some(current_quantity + 1),
- ..Default::default()
- });
- }
- None => {
- items.push(stripe::UpdateSubscriptionItems {
- price: Some(new_price_id.to_string()),
- quantity: Some(1),
- ..Default::default()
- });
- }
- }
-
- // Single atomic update — one prorated invoice for both changes
- let update_params = UpdateSubscription {
- items: Some(items),
- proration_behavior: Some(
- stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice,
- ),
- ..Default::default()
- };
-
- stripe::Subscription::update(&self.client, subscription_id, update_params)
- .await
- .map_err(|e| CustomerError::StorageLayerError(e.into()))?;
-
- Ok(())
- }
}
diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rs
index 19aef4637e..c533ac0581 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs
@@ -3,7 +3,7 @@ use crate::domain::{
model::{
AcceptedTeamInvite, CreateTeamError, InviteUsersToTeamError, PatchTeamRequest,
RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError, TeamInvite,
- TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamRole, TeamUserTier, TeamWithMembers,
+ TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamRole, TeamWithMembers,
},
team_repo::TeamRepository,
};
@@ -86,7 +86,6 @@ impl TeamRepositoryImpl {
&self,
user_id: &MacroUserIdStr<'_>,
team_name: &str,
- team_user_tier: &TeamUserTier,
) -> Result<Team, sqlx::Error> {
let mut transaction = self.pool.begin().await?;
@@ -116,12 +115,11 @@ impl TeamRepositoryImpl {
sqlx::query!(
r#"
- INSERT INTO team_user (team_id, user_id, team_role, tier)
- VALUES ($1, $2, 'owner', $3)
+ INSERT INTO team_user (team_id, user_id, team_role)
+ VALUES ($1, $2, 'owner')
"#,
&team.id,
user_id.as_ref(),
- team_user_tier as _,
)
.execute(&mut *transaction)
.await?;
@@ -230,13 +228,12 @@ impl TeamRepository for TeamRepositoryImpl {
&self,
user_id: &MacroUserIdStr<'_>,
team_name: &str,
- team_user_tier: &TeamUserTier,
) -> Result<Team, CreateTeamError> {
if team_name.is_empty() || team_name.len() > 50 {
return Err(CreateTeamError::InvalidTeamName(team_name.to_string()));
}
- self.create_team_inner(user_id, team_name, team_user_tier)
+ self.create_team_inner(user_id, team_name)
.await
.map_err(|e| e.into())
}
@@ -246,20 +243,18 @@ impl TeamRepository for TeamRepositoryImpl {
&self,
team_id: &uuid::Uuid,
invited_by: &MacroUserIdStr<'_>,
- invites: non_empty::NonEmpty<&[(Email<Lowercase<'_>>, TeamUserTier)]>,
+ invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {
let email_strings: Vec<String> = invites
.iter()
- .map(|(email, _)| email.as_ref().to_string())
+ .map(|email| email.as_ref().to_string())
.collect();
let macro_user_ids: Vec<String> = invites
.iter()
- .map(|(email, _)| format!("macro|{}", email.as_ref()))
+ .map(|email| format!("macro|{}", email.as_ref()))
.collect();
- let tiers: Vec<TeamUserTier> = invites.iter().map(|(_, tier)| *tier).collect();
-
let team_invite_ids: Vec<uuid::Uuid> = invites
.iter()
.map(|_| macro_uuid::generate_uuid_v7())
@@ -270,7 +265,7 @@ impl TeamRepository for TeamRepositoryImpl {
// Single query that filters out both already invited AND already on team
let created_invites: Vec<(uuid::Uuid, uuid::Uuid, String)> = sqlx::query!(
r#"
- INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at, tier)
+ INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at)
SELECT
t.id,
$1::uuid,
@@ -278,9 +273,8 @@ impl TeamRepository for TeamRepositoryImpl {
$2,
$3::text,
NOW(),
- NOW(),
- t.tier
- FROM UNNEST($4::uuid[], $5::text[], $6::text[], $7::"team_user_tier"[]) AS t(id, email, user_id, tier)
+ NOW()
+ FROM UNNEST($4::uuid[], $5::text[], $6::text[]) AS t(id, email, user_id)
WHERE NOT EXISTS (
SELECT 1 FROM team_invite ti
WHERE ti.team_id = $1 AND ti.email = t.email
@@ -297,7 +291,6 @@ impl TeamRepository for TeamRepositoryImpl {
&team_invite_ids[..],
&email_strings[..],
&macro_user_ids[..],
- &tiers[..] as _
)
.map(|r| (r.id, r.team_id, r.email))
.fetch_all(&mut *transaction)
@@ -375,7 +368,7 @@ impl TeamRepository for TeamRepositoryImpl {
r#"
DELETE FROM team_user
WHERE team_id = $1 AND user_id = $2
- RETURNING team_role, tier
+ RETURNING team_role
"#,
)
.bind(team_id)
@@ -391,7 +384,6 @@ impl TeamRepository for TeamRepositoryImpl {
team_id: *team_id,
user_id: user_id.clone().into_owned(),
role: row.try_get("team_role")?,
- tier: row.try_get("tier")?,
};
TeamRepositoryImpl::bump_seat_count(&mut transaction, team_id, -1).await?;
@@ -506,8 +498,7 @@ impl TeamRepository for TeamRepositoryImpl {
let members = sqlx::query!(
r#"
SELECT user_id,
- team_role as "team_role!: TeamRole",
- tier as "tier!: TeamUserTier"
+ team_role as "team_role!: TeamRole"
FROM team_user
WHERE team_id = $1
"#,
@@ -527,7 +518,6 @@ impl TeamRepository for TeamRepositoryImpl {
user_id,
role: row.team_role,
team_id: *team_id,
- tier: row.tier,
})
} else {
Err(anyhow::anyhow!("unable to parse user id"))
@@ -556,7 +546,7 @@ impl TeamRepository for TeamRepositoryImpl {
// Get invite data before deleting it so the accept can be rolled back later.
let invite = sqlx::query(
r#"
- SELECT id, email, team_role, team_id, invited_by, created_at, last_sent_at, tier
+ SELECT id, email, team_role, team_id, invited_by, created_at, last_sent_at
FROM team_invite
WHERE id = $1 AND email = $2
"#,
@@ -586,21 +576,19 @@ impl TeamRepository for TeamRepositoryImpl {
invite.try_get("last_sent_at")?,
chrono::Utc,
),
- tier: invite.try_get("tier")?,
};
// Assign user to team_user
let team_member = sqlx::query(
r#"
- INSERT INTO team_user (team_id, user_id, team_role, tier)
- VALUES ($1, $2, $3, $4)
- RETURNING user_id, team_role, tier, team_id
+ INSERT INTO team_user (team_id, user_id, team_role)
+ VALUES ($1, $2, $3)
+ RETURNING user_id, team_role, team_id
"#,
)
.bind(invite_snapshot.team_id)
.bind(user_id.as_ref())
.bind(invite_snapshot.team_role)
- .bind(invite_snapshot.tier)
.fetch_one(&mut *transaction)
.await?;
@@ -629,7 +617,6 @@ impl TeamRepository for TeamRepositoryImpl {
.map_err(|e| TeamError::StorageLayerError(e.into()))?,
role: team_member.try_get("team_role")?,
team_id,
- tier: team_member.try_get("tier")?,
};
Ok(AcceptedTeamInvite {
@@ -668,8 +655,8 @@ impl TeamRepository for TeamRepositoryImpl {
sqlx::query(
r#"
INSERT INTO team_invite
- (id, team_id, email, team_role, invited_by, created_at, last_sent_at, tier)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+ (id, team_id, email, team_role, invited_by, created_at, last_sent_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT DO NOTHING
"#,
)
@@ -680,7 +667,6 @@ impl TeamRepository for TeamRepositoryImpl {
.bind(accepted_invite.invite.invited_by.as_ref())
.bind(accepted_invite.invite.created_at.naive_utc())
.bind(accepted_invite.invite.last_sent_at.naive_utc())
- .bind(accepted_invite.invite.tier)
.execute(&mut *transaction)
.await?;
@@ -698,15 +684,14 @@ impl TeamRepository for TeamRepositoryImpl {
let inserted = sqlx::query(
r#"
- INSERT INTO team_user (team_id, user_id, team_role, tier)
- VALUES ($1, $2, $3, $4)
+ INSERT INTO team_user (team_id, user_id, team_role)
+ VALUES ($1, $2, $3)
ON CONFLICT DO NOTHING
"#,
)
.bind(removed_member.team_id)
.bind(removed_member.user_id.as_ref())
.bind(removed_member.role)
- .bind(removed_member.tier)
.execute(&mut *transaction)
.await?;
@@ -747,8 +732,7 @@ impl TeamRepository for TeamRepositoryImpl {
let members = sqlx::query!(
r#"
SELECT user_id,
- team_role as "team_role!: TeamRole",
- tier as "tier!: TeamUserTier"
+ team_role as "team_role!: TeamRole"
FROM team_user
WHERE team_id = $1
"#,
@@ -768,7 +752,6 @@ impl TeamRepository for TeamRepositoryImpl {
user_id,
role: row.team_role,
team_id: *team_id,
- tier: row.tier,
})
} else {
Err(anyhow::anyhow!("unable to parse user id"))
@@ -848,8 +831,7 @@ impl TeamRepository for TeamRepositoryImpl {
let members = sqlx::query!(
r#"
SELECT user_id,
- team_role as "team_role!: TeamRole",
- tier as "tier!: TeamUserTier"
+ team_role as "team_role!: TeamRole"
FROM team_user
WHERE team_id = $1
"#,
@@ -866,7 +848,6 @@ impl TeamRepository for TeamRepositoryImpl {
user_id: id.into_owned(),
role: row.team_role,
team_id: *team_id,
- tier: row.tier,
})
.ok()
})
@@ -1044,8 +1025,7 @@ impl TeamRepository for TeamRepositoryImpl {
let member = sqlx::query!(
r#"
SELECT user_id,
- team_role as "team_role!: TeamRole",
- tier as "tier!: TeamUserTier"
+ team_role as "team_role!: TeamRole"
FROM team_user
WHERE team_id = $1
AND user_id = $2
@@ -1060,7 +1040,6 @@ impl TeamRepository for TeamRepositoryImpl {
.into_owned(),
team_id: *team_id,
role: r.team_role,
- tier: r.tier,
})
})
.fetch_one(&self.pool)
@@ -1069,34 +1048,6 @@ impl TeamRepository for TeamRepositoryImpl {
Ok(member)
}
- #[tracing::instrument(skip(self), err)]
- async fn patch_team_tier(
- &self,
- team_id: &uuid::Uuid,
- user_id: &MacroUserIdStr<'_>,
- team_tier: TeamUserTier,
- ) -> Result<(), TeamError> {
- let result = sqlx::query!(
- r#"
- UPDATE team_user
- SET tier = $3
- WHERE team_id = $1
- AND user_id = $2
- "#,
- team_id,
- user_id.as_ref(),
- team_tier as _,
- )
- .execute(&self.pool)
- .await?;
-
- if result.rows_affected() == 0 {
- return Err(TeamError::TeamMemberNotFound(*team_id));
- }
-
- Ok(())
- }
-
#[tracing::instrument(skip(self), err)]
async fn patch_team_user_role(
&self,
diff --git a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
index 7c82310fce..96d03334bd 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
@@ -76,9 +76,7 @@ async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- let result = team_repo
- .create_team(&user_id, "team1", &TeamUserTier::Sonnet)
- .await?;
+ let result = team_repo.create_team(&user_id, "team1").await?;
assert!(!result.id.to_string().is_empty());
assert_eq!(result.name, "team1");
@@ -86,7 +84,7 @@ async fn test_create_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
// Create team with too large a name
let err = team_repo
- .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", &TeamUserTier::Sonnet)
+ .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000")
.await
.err()
.unwrap();
@@ -107,10 +105,7 @@ async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
- let invites = vec![(
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- )];
+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
@@ -121,14 +116,8 @@ async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
assert_eq!(invited[0].email.as_ref(), "[email protected]");
let invites = vec![
- (
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- ),
- (
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- ),
+ Email::parse_from_str("[email protected]")?.lowercase(),
+ Email::parse_from_str("[email protected]")?.lowercase(),
];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
@@ -141,59 +130,6 @@ async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
Ok(())
}
-/// Inviting users with different tiers stores each tier correctly.
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("teams"))
-)]
-async fn test_invite_stores_tier(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let team_repo = TeamRepositoryImpl::new(pool.clone());
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
-
- let invites = vec![
- (
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Opus,
- ),
- (
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Sonnet,
- ),
- ];
- let invites = non_empty::NonEmpty::new(invites.as_slice())?;
-
- let invited = team_repo
- .invite_users_to_team(&team_id, &user_id, invites)
- .await?;
-
- assert_eq!(invited.len(), 2);
-
- let opus_row = sqlx::query!(
- r#"
- SELECT tier as "tier!: TeamUserTier"
- FROM team_invite
- WHERE email = '[email protected]'
- "#,
- )
- .fetch_one(&pool)
- .await?;
- assert_eq!(opus_row.tier, TeamUserTier::Opus);
-
- let sonnet_row = sqlx::query!(
- r#"
- SELECT tier as "tier!: TeamUserTier"
- FROM team_invite
- WHERE email = '[email protected]'
- "#,
- )
- .fetch_one(&pool)
- .await?;
- assert_eq!(sonnet_row.tier, TeamUserTier::Sonnet);
-
- Ok(())
-}
-
/// Re-inviting an already-invited user within the 5-minute window should not
/// return them (rate limited), so the result should be empty.
#[sqlx::test(
@@ -206,10 +142,7 @@ async fn test_invite_existing_user_within_rate_limit(pool: Pool<Postgres>) -> an
let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
// [email protected] already has an invite with last_sent_at = NOW() in the fixture
- let invites = vec![(
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- )];
+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
@@ -241,10 +174,7 @@ async fn test_invite_existing_user_after_rate_limit(pool: Pool<Postgres>) -> any
.execute(&pool)
.await?;
- let invites = vec![(
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- )];
+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
@@ -277,14 +207,8 @@ async fn test_invite_mix_new_and_existing(pool: Pool<Postgres>) -> anyhow::Resul
.await?;
let invites = vec![
- (
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- ),
- (
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- ),
+ Email::parse_from_str("[email protected]")?.lowercase(),
+ Email::parse_from_str("[email protected]")?.lowercase(),
];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
@@ -321,10 +245,7 @@ async fn test_reinvite_updates_last_sent_at(pool: Pool<Postgres>) -> anyhow::Res
.await?;
// First re-invite should succeed
- let invites = vec![(
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- )];
+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites)
@@ -336,10 +257,7 @@ async fn test_reinvite_updates_last_sent_at(pool: Pool<Postgres>) -> anyhow::Res
team_repo.mark_invites_sent(&sent_ids).await?;
// Second immediate re-invite should be rate limited
- let invites = vec![(
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- )];
+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites)
@@ -369,10 +287,7 @@ async fn test_resend_without_mark_sent_stays_eligible(pool: Pool<Postgres>) -> a
.await?;
// First re-invite returns the invite
- let invites = vec![(
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- )];
+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites)
@@ -382,10 +297,7 @@ async fn test_resend_without_mark_sent_stays_eligible(pool: Pool<Postgres>) -> a
// Do NOT call mark_invites_sent (simulating failed notification delivery)
// Second re-invite should still return the invite because last_sent_at was not updated
- let invites = vec![(
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- )];
+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites)
@@ -435,10 +347,7 @@ async fn test_mark_invites_sent(pool: Pool<Postgres>) -> anyhow::Result<()> {
// The invite should now be rate limited
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- let invites = vec![(
- Email::parse_from_str("[email protected]")?.lowercase(),
- TeamUserTier::Haiku,
- )];
+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];
let invites = non_empty::NonEmpty::new(invites.as_slice())?;
let invited = team_repo
.invite_users_to_team(&team_id, &user_id, invites)
@@ -660,42 +569,6 @@ async fn test_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Result<()> {
Ok(())
}
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("teams"))
-)]
-async fn test_accept_team_invite_uses_invite_tier(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let team_repo = TeamRepositoryImpl::new(pool.clone());
-
- // Invite 22222222... has tier = 'opus' in the fixture
- let team_invite_id = macro_uuid::string_to_uuid("22222222-2222-2222-2222-222222222222")?;
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
-
- let accepted_invite = team_repo
- .accept_team_invite(&team_invite_id, &user_id)
- .await?;
- let team_member = accepted_invite.member;
-
- assert_eq!(team_member.tier, TeamUserTier::Opus);
-
- // Verify the tier persisted in team_user table
- let row = sqlx::query!(
- r#"
- SELECT tier as "tier!: TeamUserTier"
- FROM team_user
- WHERE team_id = $1 AND user_id = $2
- "#,
- &team_member.team_id,
- user_id.as_ref(),
- )
- .fetch_one(&pool)
- .await?;
-
- assert_eq!(row.tier, TeamUserTier::Opus);
-
- Ok(())
-}
-
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))
@@ -730,7 +603,7 @@ async fn test_rollback_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Resul
let invite = sqlx::query(
r#"
- SELECT email, team_role, tier
+ SELECT email, team_role
FROM team_invite
WHERE id = $1
"#,
@@ -743,10 +616,6 @@ async fn test_rollback_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Resul
invite.try_get::<TeamRole, _>("team_role")?,
TeamRole::Member
);
- assert_eq!(
- invite.try_get::<TeamUserTier, _>("tier")?,
- TeamUserTier::Opus
- );
let team = sqlx::query(r#"SELECT seat_count FROM team WHERE id = $1"#)
.bind(team_id)
@@ -770,13 +639,9 @@ async fn test_rollback_remove_user_from_team(pool: Pool<Postgres>) -> anyhow::Re
team_repo
.patch_team_user_role(&team_id, &user_id, TeamRole::Admin)
.await?;
- team_repo
- .patch_team_tier(&team_id, &user_id, TeamUserTier::Sonnet)
- .await?;
let removed_member = team_repo.remove_user_from_team(&team_id, &user_id).await?;
assert_eq!(removed_member.role, TeamRole::Admin);
- assert_eq!(removed_member.tier, TeamUserTier::Sonnet);
team_repo
.rollback_remove_user_from_team(&removed_member)
@@ -784,7 +649,6 @@ async fn test_rollback_remove_user_from_team(pool: Pool<Postgres>) -> anyhow::Re
let member = team_repo.get_team_member(&team_id, &user_id).await?;
assert_eq!(member.role, TeamRole::Admin);
- assert_eq!(member.tier, TeamUserTier::Sonnet);
let team = sqlx::query(r#"SELECT seat_count FROM team WHERE id = $1"#)
.bind(team_id)
@@ -924,46 +788,6 @@ async fn test_get_team_member(pool: Pool<Postgres>) -> anyhow::Result<()> {
Ok(())
}
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("teams"))
-)]
-async fn test_patch_team_tier(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let team_repo = TeamRepositoryImpl::new(pool);
-
- let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
-
- // Patch tier to Opus
- team_repo
- .patch_team_tier(&team_id, &user_id, TeamUserTier::Opus)
- .await?;
-
- // Verify the tier was updated
- let member = team_repo.get_team_member(&team_id, &user_id).await?;
- assert_eq!(member.tier, TeamUserTier::Opus);
-
- // Patch tier to Haiku
- team_repo
- .patch_team_tier(&team_id, &user_id, TeamUserTier::Haiku)
- .await?;
-
- let member = team_repo.get_team_member(&team_id, &user_id).await?;
- assert_eq!(member.tier, TeamUserTier::Haiku);
-
- // Patch tier for non-existent user
- let missing_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- let err = team_repo
- .patch_team_tier(&team_id, &missing_id, TeamUserTier::Opus)
- .await
- .err()
- .unwrap();
-
- assert!(err.to_string().contains("member not found"));
-
- Ok(())
-}
-
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))