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): patch team user tier request (#2231)

Will Hutchinsonbc7b757e50c8
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 10323c0b88..053670b9a5 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -29,6 +29,7 @@ import type {
PasswordlessRequest,
PasswordRequest,
PatchTeamRequest,
+ PatchTeamUserTierRequest,
PatchUserGroupRequest,
PatchUserOnboardingRequest,
PatchUserTutorialRequest,
@@ -2369,6 +2370,76 @@ 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 = (teamId: string) => {
+ return `/team/${teamId}/tier`;
+};
+
+export const patchTeamUserTier = async (
+ teamId: string,
+ patchTeamUserTierRequest: PatchTeamUserTierRequest,
+ options?: RequestInit
+): Promise<patchTeamUserTierResponse> => {
+ const res = await fetch(getPatchTeamUserTierUrl(teamId), {
+ ...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 Creates a new 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 c838b8a4f7..e571a0b6ce 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
@@ -37,6 +37,7 @@ export * from './passwordlessRequestReferralCode';
export * from './passwordRequest';
export * from './patchTeamRequest';
export * from './patchTeamRequestName';
+export * from './patchTeamUserTierRequest';
export * from './patchUserGroupRequest';
export * from './patchUserOnboardingRequest';
export * from './patchUserTutorialRequest';
@@ -60,6 +61,7 @@ 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/patchTeamUserTierRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamUserTierRequest.ts
new file mode 100644
index 0000000000..dd664ddf84
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamUserTierRequest.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.13.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/teamUserTier.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamUserTier.ts
new file mode 100644
index 0000000000..c3f042371f
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamUserTier.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.13.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 4b0446f1d7..09069f32b1 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -2068,6 +2068,79 @@
}
}
},
+ "/team/{team_id}/tier": {
+ "patch": {
+ "tags": ["teams::inbound::axum_router::patch_team_user_tier"],
+ "summary": "Updates a team.",
+ "operationId": "patch_team_user_tier",
+ "parameters": [
+ {
+ "name": "team_id",
+ "in": "path",
+ "description": "The ID of the team to update",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "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"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/user": {
"post": {
"tags": ["user::create_user"],
@@ -3321,6 +3394,21 @@
}
}
},
+ "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"],
@@ -3576,6 +3664,11 @@
"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/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rs
index 726f01487b..e9a8cf6197 100644
--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs
+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs
@@ -1,6 +1,7 @@
use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};
use teams::domain::model::{
- PatchTeamRequest, Team, TeamInviteDetails, TeamMember, TeamRole, TeamWithMembers,
+ PatchTeamRequest, PatchTeamUserTierRequest, Team, TeamInviteDetails, TeamMember, TeamRole,
+ TeamUserTier, TeamWithMembers,
};
use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;
use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;
@@ -116,6 +117,7 @@ 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::reinvite_to_team::handler::<crate::api::context::TeamsServiceType>,
@@ -183,6 +185,8 @@ use model::user::{
PatchTeamRequest,
TeamTeamInvitesResponse,
UserTeamInvitesResponse,
+ PatchTeamUserTierRequest,
+ TeamUserTier,
// Merge
CreateAccountMergeRequest,
diff --git a/rust/cloud-storage/github/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json b/rust/cloud-storage/github/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json
new file mode 100644
index 0000000000..83caec4173
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM email_threads t\n JOIN \"Project\" p ON t.project_id = p.id AND p.\"deletedAt\" IS NULL\n WHERE t.id = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $2\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json b/rust/cloud-storage/github/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
new file mode 100644
index 0000000000..44d3a67e72
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM public.email_threads t\n JOIN public.email_links l ON l.id = t.link_id\n WHERE t.id = $1::uuid\n AND l.macro_id = $2\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json b/rust/cloud-storage/github/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
new file mode 100644
index 0000000000..60bfee0647
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"DocumentPermission\" WHERE \"documentId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json b/rust/cloud-storage/github/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
new file mode 100644
index 0000000000..58618b2697
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n -- CTE to recursively find all parent projects, starting from the given project.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project ID provided.\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n -- The hierarchy CTE includes the starting project, so this is all we need.\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n -- We only need to check ProjectPermission for the items in the hierarchy.\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\"\n WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json b/rust/cloud-storage/github/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
new file mode 100644
index 0000000000..524cc25ec7
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The chat itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"ChatPermission\" WHERE \"chatId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json b/rust/cloud-storage/github/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
new file mode 100644
index 0000000000..03a8dbf6bb
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json b/rust/cloud-storage/github/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
new file mode 100644
index 0000000000..655495fb29
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT c.id\n FROM comms_channels c\n INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n AND c.id = ANY($2::uuid[])\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json b/rust/cloud-storage/github/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
new file mode 100644
index 0000000000..2bde15938f
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json b/rust/cloud-storage/github/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
new file mode 100644
index 0000000000..e42c9f2009
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0"
+}
diff --git a/rust/cloud-storage/github/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json b/rust/cloud-storage/github/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json
new file mode 100644
index 0000000000..6ef8856744
--- /dev/null
+++ b/rust/cloud-storage/github/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM email_threads t\n JOIN \"Project\" p ON t.project_id = p.id AND p.\"deletedAt\" IS NULL\n WHERE t.id = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $3 AND item_id IN (\n SELECT $2 -- The thread ID as text\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $2\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed"
+}
diff --git a/rust/cloud-storage/github/fixtures/github_installation_test_data.sql b/rust/cloud-storage/github/fixtures/github_installation_test_data.sql
index 464117c008..9e669bb4ce 100644
--- a/rust/cloud-storage/github/fixtures/github_installation_test_data.sql
+++ b/rust/cloud-storage/github/fixtures/github_installation_test_data.sql
@@ -1,12 +1,14 @@
INSERT INTO
public.macro_user (id, username, email, stripe_customer_id)
VALUES
- ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid, 'testuser', '[email protected]', 'cus_test');
+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid, 'testuser', '[email protected]', 'cus_test'),
+ ('cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid, 'testuser2', '[email protected]', 'cus_test2');
INSERT INTO
public."User" (id, email, macro_user_id)
VALUES
- ('macro|[email protected]', '[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid);
+ ('macro|[email protected]', '[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid),
+ ('macro|[email protected]', '[email protected]', 'cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid);
INSERT INTO
public.github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id)
@@ -17,10 +19,10 @@ INSERT INTO
public.team (id, name, owner_id)
VALUES
('dddddddd-dddd-dddd-dddd-dddddddddddd'::uuid, 'Team Alpha', 'macro|[email protected]'),
- ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, 'Team Beta', 'macro|[email protected]');
+ ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, 'Team Beta', 'macro|[email protected]');
INSERT INTO
public.team_user (user_id, team_id, team_role)
VALUES
('macro|[email protected]', 'dddddddd-dddd-dddd-dddd-dddddddddddd'::uuid, 'owner'),
- ('macro|[email protected]', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, 'member');
+ ('macro|[email protected]', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, 'owner');
diff --git a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
index cefe6d035a..1ec0ec1f87 100644
--- a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs
@@ -224,15 +224,25 @@ async fn test_get_user_team_ids(pool: Pool<Postgres>) {
let repo = PgGithubSyncRepo::new(pool);
let team_ids = repo.get_user_team_ids("macro|[email protected]").await.unwrap();
-
- assert_eq!(team_ids.len(), 2);
- let expected: Vec<Uuid> = vec![
- "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap(),
- "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".parse().unwrap(),
- ];
- for id in &expected {
- assert!(team_ids.contains(id));
- }
+ assert_eq!(team_ids.len(), 1);
+ assert_eq!(
+ team_ids[0],
+ "dddddddd-dddd-dddd-dddd-dddddddddddd"
+ .parse::<Uuid>()
+ .unwrap()
+ );
+
+ let team_ids2 = repo
+ .get_user_team_ids("macro|[email protected]")
+ .await
+ .unwrap();
+ assert_eq!(team_ids2.len(), 1);
+ assert_eq!(
+ team_ids2[0],
+ "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"
+ .parse::<Uuid>()
+ .unwrap()
+ );
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json b/rust/cloud-storage/macro_db_client/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json
new file mode 100644
index 0000000000..83caec4173
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM email_threads t\n JOIN \"Project\" p ON t.project_id = p.id AND p.\"deletedAt\" IS NULL\n WHERE t.id = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $2\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json
new file mode 100644
index 0000000000..d2b084cf10
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[],\n $4::JSONB[]\n ) AS u(id, entity_id, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "UuidArray",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json b/rust/cloud-storage/macro_db_client/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
new file mode 100644
index 0000000000..44d3a67e72
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM public.email_threads t\n JOIN public.email_links l ON l.id = t.link_id\n WHERE t.id = $1::uuid\n AND l.macro_id = $2\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json b/rust/cloud-storage/macro_db_client/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
new file mode 100644
index 0000000000..03a8dbf6bb
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json
new file mode 100644
index 0000000000..6d97183829
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n NULL\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[]\n ) AS u(id, entity_id, property_definition_id)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json b/rust/cloud-storage/macro_db_client/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
new file mode 100644
index 0000000000..655495fb29
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT c.id\n FROM comms_channels c\n INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n AND c.id = ANY($2::uuid[])\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json b/rust/cloud-storage/macro_db_client/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
new file mode 100644
index 0000000000..2bde15938f
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-8d21bf0aa4c20589a55cf5777aa9c658fdacea4d0d0c7070aded12cccd373911.json b/rust/cloud-storage/macro_db_client/.sqlx/query-8d21bf0aa4c20589a55cf5777aa9c658fdacea4d0d0c7070aded12cccd373911.json
new file mode 100644
index 0000000000..505a2bd912
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-8d21bf0aa4c20589a55cf5777aa9c658fdacea4d0d0c7070aded12cccd373911.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE entity_properties\n SET values = $2\n WHERE entity_id = $1\n AND property_definition_id = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Jsonb",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "8d21bf0aa4c20589a55cf5777aa9c658fdacea4d0d0c7070aded12cccd373911"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json b/rust/cloud-storage/macro_db_client/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
new file mode 100644
index 0000000000..e42c9f2009
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json
new file mode 100644
index 0000000000..9d717fa5f9
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT property_definition_id, values\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "values",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json b/rust/cloud-storage/macro_db_client/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json
new file mode 100644
index 0000000000..6ef8856744
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM email_threads t\n JOIN \"Project\" p ON t.project_id = p.id AND p.\"deletedAt\" IS NULL\n WHERE t.id = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $3 AND item_id IN (\n SELECT $2 -- The thread ID as text\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $2\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json
new file mode 100644
index 0000000000..182e0858ba
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n u.entity_type::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::TEXT[],\n $4::UUID[],\n $5::JSONB[]\n ) AS u(id, entity_id, entity_type, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "TextArray",
+ "UuidArray",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069"
+}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260327140350_restrict_one_team_per_user.sql b/rust/cloud-storage/macro_db_client/migrations/20260327140350_restrict_one_team_per_user.sql
new file mode 100644
index 0000000000..e6c1cc5ad0
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260327140350_restrict_one_team_per_user.sql
@@ -0,0 +1,3 @@
+ALTER TABLE "team_user" ADD CONSTRAINT "team_user_user_id_unique" UNIQUE ("user_id");
+
+ALTER TABLE "team" ADD CONSTRAINT "team_owner_id_unique" UNIQUE ("owner_id");
diff --git a/rust/cloud-storage/teams/.sqlx/query-169f49448d5e78ac04686fb3a6d0b86c07b91393f2dba801e4e51d3c8ab5e506.json b/rust/cloud-storage/teams/.sqlx/query-169f49448d5e78ac04686fb3a6d0b86c07b91393f2dba801e4e51d3c8ab5e506.json
deleted file mode 100644
index 9501e6b51c..0000000000
--- a/rust/cloud-storage/teams/.sqlx/query-169f49448d5e78ac04686fb3a6d0b86c07b91393f2dba801e4e51d3c8ab5e506.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT tier as \"tier!: TeamUserTier\"\n FROM team_user\n WHERE user_id = $1 AND team_id != $2\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "tier!: TeamUserTier",
- "type_info": {
- "Custom": {
- "name": "team_user_tier",
- "kind": {
- "Enum": [
- "haiku",
- "sonnet",
- "opus"
- ]
- }
- }
- }
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Uuid"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "169f49448d5e78ac04686fb3a6d0b86c07b91393f2dba801e4e51d3c8ab5e506"
-}
diff --git a/rust/cloud-storage/teams/.sqlx/query-32caedb3c1bd949d4c4cfec7a3f43a1403707f4e9126f51d33d7c3c3c82b7c8a.json b/rust/cloud-storage/teams/.sqlx/query-32caedb3c1bd949d4c4cfec7a3f43a1403707f4e9126f51d33d7c3c3c82b7c8a.json
new file mode 100644
index 0000000000..bedfa7824c
--- /dev/null
+++ b/rust/cloud-storage/teams/.sqlx/query-32caedb3c1bd949d4c4cfec7a3f43a1403707f4e9126f51d33d7c3c3c82b7c8a.json
@@ -0,0 +1,57 @@
+{
+ "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 ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_role!: TeamRole",
+ "type_info": {
+ "Custom": {
+ "name": "team_role",
+ "kind": {
+ "Enum": [
+ "member",
+ "admin",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 2,
+ "name": "tier!: TeamUserTier",
+ "type_info": {
+ "Custom": {
+ "name": "team_user_tier",
+ "kind": {
+ "Enum": [
+ "haiku",
+ "sonnet",
+ "opus"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "32caedb3c1bd949d4c4cfec7a3f43a1403707f4e9126f51d33d7c3c3c82b7c8a"
+}
diff --git a/rust/cloud-storage/teams/.sqlx/query-93e4b43a340a79ff7a4ebff7ae351893f605ea8a568a304968bec11a6c0cc2b6.json b/rust/cloud-storage/teams/.sqlx/query-93e4b43a340a79ff7a4ebff7ae351893f605ea8a568a304968bec11a6c0cc2b6.json
new file mode 100644
index 0000000000..07e69c222d
--- /dev/null
+++ b/rust/cloud-storage/teams/.sqlx/query-93e4b43a340a79ff7a4ebff7ae351893f605ea8a568a304968bec11a6c0cc2b6.json
@@ -0,0 +1,27 @@
+{
+ "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/teams/fixtures/teams.sql b/rust/cloud-storage/teams/fixtures/teams.sql
index af4e741d2c..f3efd463e9 100644
--- a/rust/cloud-storage/teams/fixtures/teams.sql
+++ b/rust/cloud-storage/teams/fixtures/teams.sql
@@ -13,8 +13,7 @@ INSERT INTO "User" ("id", "email", "name", "stripeCustomerId", "macro_user_id")
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),
- ('33333333-3333-3333-3333-333333333333', 'team3', 'macro|[email protected]', NULL, 1);
+ ('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'),
@@ -23,6 +22,4 @@ VALUES ('11111111-1111-1111-1111-111111111111', '11111111-1111-1111-1111-1111111
INSERT INTO team_user (team_id, user_id, team_role)
VALUES ('11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'owner'),
('11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'member'),
- ('22222222-2222-2222-2222-222222222222', 'macro|[email protected]', 'member'),
- ('33333333-3333-3333-3333-333333333333', 'macro|[email protected]', 'owner'),
- ('33333333-3333-3333-3333-333333333333', 'macro|[email protected]', 'member');
+ ('22222222-2222-2222-2222-222222222222', '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 7fe75cd50a..d36798d7ab 100644
--- a/rust/cloud-storage/teams/fixtures/teams_remaining_tiers.sql
+++ b/rust/cloud-storage/teams/fixtures/teams_remaining_tiers.sql
@@ -1,40 +1,22 @@
-- Fixture for testing get_user_remaining_tiers
--- Sets up users in multiple teams with different tiers
+-- With unique user_id constraint, each user can only be in one team
INSERT INTO "macro_user" (id, username, email, stripe_customer_id)
VALUES
('a1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'cus_owner'),
- ('a2222222-2222-2222-2222-222222222222', '[email protected]', '[email protected]', 'cus_multi'),
- ('a3333333-3333-3333-3333-333333333333', '[email protected]', '[email protected]', 'cus_single'),
- ('a4444444-4444-4444-4444-444444444444', '[email protected]', '[email protected]', 'cus_none');
+ ('a2222222-2222-2222-2222-222222222222', '[email protected]', '[email protected]', 'cus_single'),
+ ('a3333333-3333-3333-3333-333333333333', '[email protected]', '[email protected]', 'cus_none');
INSERT INTO "User" ("id", "email", "name", "stripeCustomerId", "macro_user_id") VALUES
('macro|[email protected]', '[email protected]', 'Owner', 'cus_owner', 'a1111111-1111-1111-1111-111111111111'),
-('macro|[email protected]', '[email protected]', 'Multi', 'cus_multi', 'a2222222-2222-2222-2222-222222222222'),
-('macro|[email protected]', '[email protected]', 'Single', 'cus_single', 'a3333333-3333-3333-3333-333333333333'),
-('macro|[email protected]', '[email protected]', 'NoTeam', 'cus_none', 'a4444444-4444-4444-4444-444444444444');
+('macro|[email protected]', '[email protected]', 'Single', 'cus_single', 'a2222222-2222-2222-2222-222222222222'),
+('macro|[email protected]', '[email protected]', 'NoTeam', 'cus_none', 'a3333333-3333-3333-3333-333333333333');
--- Team A: haiku tier members
INSERT INTO team(id, name, owner_id, subscription_id, seat_count)
-VALUES ('aaaa1111-1111-1111-1111-111111111111', 'Team A', 'macro|[email protected]', 'sub_a', 3);
-
--- Team B: sonnet tier members
-INSERT INTO team(id, name, owner_id, subscription_id, seat_count)
-VALUES ('bbbb2222-2222-2222-2222-222222222222', 'Team B', 'macro|[email protected]', 'sub_b', 2);
-
--- Team C: opus tier members
-INSERT INTO team(id, name, owner_id, subscription_id, seat_count)
-VALUES ('cccc3333-3333-3333-3333-333333333333', 'Team C', 'macro|[email protected]', 'sub_c', 2);
+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)
VALUES
- -- Owner on all teams
('aaaa1111-1111-1111-1111-111111111111', 'macro|[email protected]', 'owner', 'haiku'),
- ('bbbb2222-2222-2222-2222-222222222222', 'macro|[email protected]', 'owner', 'sonnet'),
- ('cccc3333-3333-3333-3333-333333333333', 'macro|[email protected]', 'owner', 'opus'),
- -- [email protected]: member of all 3 teams with different tiers
- ('aaaa1111-1111-1111-1111-111111111111', 'macro|[email protected]', 'member', 'haiku'),
- ('bbbb2222-2222-2222-2222-222222222222', 'macro|[email protected]', 'member', 'sonnet'),
- ('cccc3333-3333-3333-3333-333333333333', 'macro|[email protected]', 'member', 'opus'),
- -- [email protected]: member of only Team A
- ('aaaa1111-1111-1111-1111-111111111111', 'macro|[email protected]', 'member', 'haiku');
+ ('bbbb2222-2222-2222-2222-222222222222', 'macro|[email protected]', 'owner', 'sonnet');
diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rs
index 0838d11426..54adb7689b 100644
--- a/rust/cloud-storage/teams/src/domain/model.rs
+++ b/rust/cloud-storage/teams/src/domain/model.rs
@@ -6,7 +6,18 @@ 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)]
+#[derive(
+ Eq,
+ PartialEq,
+ Debug,
+ Clone,
+ Hash,
+ PartialOrd,
+ Copy,
+ std::cmp::Ord,
+ serde::Serialize,
+ serde::Deserialize,
+)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "outbound", derive(sqlx::Type))]
#[cfg_attr(
@@ -140,6 +151,17 @@ pub struct PatchTeamRequest {
pub name: Option<String>,
}
+/// 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))]
@@ -219,6 +241,9 @@ pub enum TeamError {
/// The team does not exist
#[error("The team does not exist")]
TeamDoesNotExist,
+ /// Team member was not found
+ #[error("Team member not found for team {0}")]
+ TeamMemberNotFound(uuid::Uuid),
/// The subscription does not exist
#[error("No subscription")]
NoSubscription,
@@ -228,6 +253,9 @@ pub enum TeamError {
/// The team invite does not exist
#[error("The team invite does not exist")]
TeamInviteDoesNotExist,
+ /// Bad request
+ #[error("Bad request: {0}")]
+ BadRequest(String),
/// Storage layer error
#[error("Storage layer error {0}")]
StorageLayerError(#[from] anyhow::Error),
diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rs
index 730b8be64a..0fb82f045b 100644
--- a/rust/cloud-storage/teams/src/domain/team_repo.rs
+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs
@@ -6,7 +6,7 @@ use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr
use crate::domain::model::{
CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, PatchTeamRequest,
- ReinviteError, RemoveTeamInviteError, RemoveUserFromTeamError,
+ PatchTeamUserTierRequest, ReinviteError, RemoveTeamInviteError, RemoveUserFromTeamError,
RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team, TeamError,
TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamUserTier, TeamWithMembers,
};
@@ -112,14 +112,6 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<bool, TeamError>> + Send;
- /// Gets the set of tiers a user has across all their teams,
- /// excluding a specific team.
- fn get_user_remaining_tiers(
- &self,
- user_id: &MacroUserIdStr<'_>,
- exclude_team_id: &uuid::Uuid,
- ) -> impl Future<Output = Result<HashSet<TeamUserTier>, TeamError>> + Send;
-
/// Gets the members of the team.
/// This does not include the team owner.
fn get_team_members(
@@ -191,6 +183,21 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {
team_id: &uuid::Uuid,
user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Option<TeamRole>, TeamError>> + Send;
+
+ /// Gets the team member for the team
+ fn get_team_member(
+ &self,
+ team_id: &uuid::Uuid,
+ 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;
}
/// The TeamService defines a set of actions to perform on the teams
@@ -312,4 +319,11 @@ 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,
+ team_id: &uuid::Uuid,
+ 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 1ee6199f4c..a706c369e5 100644
--- a/rust/cloud-storage/teams/src/domain/team_service.rs
+++ b/rust/cloud-storage/teams/src/domain/team_service.rs
@@ -19,7 +19,7 @@ use crate::domain::{
customer_repo::CustomerRepository,
model::{
CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, PatchTeamRequest,
- ReinviteError, RemoveTeamInviteError, RemoveUserFromTeamError,
+ PatchTeamUserTierRequest, ReinviteError, RemoveTeamInviteError, RemoveUserFromTeamError,
RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team,
TeamError, TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamUserTier,
TeamWithMembers,
@@ -277,24 +277,15 @@ where
.decrease_subscription_quantity(&subscription_id, tier)
.await?;
- let remaining_tiers = self
- .team_repository
- .get_user_remaining_tiers(user_id, team_id)
- .await?;
+ let roles_to_remove = vec![RoleId::TeamSubscriber, RoleId::from(tier)];
- let mut roles_to_remove = vec![];
- if remaining_tiers.is_empty() {
- roles_to_remove.push(RoleId::TeamSubscriber);
- }
- if !remaining_tiers.contains(&tier) {
- roles_to_remove.push(RoleId::from(tier));
- }
- if let Ok(roles) = non_empty::NonEmpty::new(roles_to_remove.as_slice()) {
- self.user_roles_and_permissions_service
- .dangerous_remove_roles_from_user(user_id, &roles)
- .await
- .map_err(RemoveUserFromTeamError::RemoveRolesFromUserError)?;
- }
+ self.user_roles_and_permissions_service
+ .dangerous_remove_roles_from_user(
+ user_id,
+ &non_empty::NonEmpty::new(roles_to_remove.as_slice()).unwrap(),
+ )
+ .await
+ .map_err(RemoveUserFromTeamError::RemoveRolesFromUserError)?;
}
tier.map(|_| ())
@@ -383,6 +374,7 @@ where
team_invite_id: &uuid::Uuid,
user_id: &MacroUserIdStr<'_>,
) -> Result<TeamMember<'_>, JoinTeamError> {
+ // This will fail if the user is already in another team
let team_member = self
.team_repository
.accept_team_invite(team_invite_id, user_id)
@@ -424,26 +416,16 @@ where
return Ok(());
}
- // For each member, check remaining tiers and remove roles accordingly
for member in members {
- let remaining_tiers = self
- .team_repository
- .get_user_remaining_tiers(&member.user_id, team_id)
- .await?;
+ let roles_to_remove = vec![RoleId::TeamSubscriber, RoleId::from(member.tier)];
- let mut roles_to_remove = vec![];
- if remaining_tiers.is_empty() {
- roles_to_remove.push(RoleId::TeamSubscriber);
- }
- if !remaining_tiers.contains(&member.tier) {
- roles_to_remove.push(RoleId::from(member.tier));
- }
- if let Ok(roles) = non_empty::NonEmpty::new(roles_to_remove.as_slice()) {
- self.user_roles_and_permissions_service
- .dangerous_remove_roles_from_user(&member.user_id, &roles)
- .await
- .map_err(RevokePermissionsForTeamMembersError::RemoveRolesFromUserError)?;
- }
+ self.user_roles_and_permissions_service
+ .dangerous_remove_roles_from_user(
+ &member.user_id,
+ &non_empty::NonEmpty::new(roles_to_remove.as_slice()).unwrap(),
+ )
+ .await
+ .map_err(RevokePermissionsForTeamMembersError::RemoveRolesFromUserError)?;
}
Ok(())
@@ -575,4 +557,54 @@ where
.await
.map_err(|e| TeamError::StorageLayerError(e.into()))
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn patch_team_user_tier(
+ &self,
+ team_id: &uuid::Uuid,
+ request: &PatchTeamUserTierRequest,
+ ) -> Result<(), TeamError> {
+ 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?;
+
+ 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/inbound/axum_router/mod.rs b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
index 93bd9145f3..8cb510fd6f 100644
--- a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs
@@ -22,6 +22,8 @@ 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;
/// Reinvite a user to a team.
pub mod reinvite_to_team;
/// Reject a team invitation.
@@ -85,6 +87,7 @@ where
.route("/user/invites", get(get_user_invites::handler::<T>))
.route("/{team_id}", get(get_team::handler::<T>))
.route("/{team_id}", patch(patch_team::handler::<T>))
+ .route("/{team_id}/tier", patch(patch_team_user_tier::handler::<T>))
.route("/{team_id}", delete(delete_team::handler::<T>))
.route("/{team_id}/invites", get(get_team_invites::handler::<T>))
.route("/{team_id}/invite", post(invite_to_team::handler::<T>))
@@ -118,12 +121,25 @@ impl IntoResponse for TeamError {
message: "team does not exist".into(),
}),
),
+ TeamError::TeamMemberNotFound(_) => (
+ StatusCode::NOT_FOUND,
+ Json(ErrorResponse {
+ message: self.to_string().into(),
+ }),
+ ),
+
TeamError::TeamInviteDoesNotExist => (
StatusCode::NOT_FOUND,
Json(ErrorResponse {
message: "team invite does not exist".into(),
}),
),
+ TeamError::BadRequest(_) => (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: self.to_string().into(),
+ }),
+ ),
_ => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
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
new file mode 100644
index 0000000000..0b255bbcd1
--- /dev/null
+++ b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_user_tier.rs
@@ -0,0 +1,40 @@
+use axum::{
+ Json,
+ extract::{Path, State},
+};
+use model_error_response::ErrorResponse;
+
+use crate::domain::{
+ model::{PatchTeamUserTierRequest, TeamError},
+ team_repo::TeamService,
+};
+
+use super::{TeamPathParam, TeamRouterState, middleware::TeamAccessRoleExtractor};
+
+/// Updates a team.
+#[utoipa::path(
+ patch,
+ path = "/team/{team_id}/tier",
+ operation_id = "patch_team_user_tier",
+ params(
+ ("team_id" = String, Path, description = "The ID of the team to update")
+ ),
+ 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>(
+ _access: TeamAccessRoleExtractor<super::middleware::OwnerRole, T>,
+ State(state): State<TeamRouterState<T>>,
+ Path(TeamPathParam { team_id }): Path<TeamPathParam>,
+ Json(req): Json<PatchTeamUserTierRequest>,
+) -> Result<(), TeamError> {
+ state.service.patch_team_user_tier(&team_id, &req).await?;
+ Ok(())
+}
diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rs
index b9eb3f23d2..84facb32bb 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs
@@ -11,7 +11,7 @@ use macro_user_id::{
cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,
};
use sqlx::PgPool;
-use std::{collections::HashSet, str::FromStr};
+use std::str::FromStr;
/// utility fn for queries to create a sqlx err
fn type_err<E: std::fmt::Display>(e: E) -> sqlx::Error {
@@ -581,27 +581,6 @@ impl TeamRepository for TeamRepositoryImpl {
Ok(team_member.is_some())
}
- #[tracing::instrument(skip(self), err)]
- async fn get_user_remaining_tiers(
- &self,
- user_id: &MacroUserIdStr<'_>,
- exclude_team_id: &uuid::Uuid,
- ) -> Result<HashSet<TeamUserTier>, TeamError> {
- let tiers = sqlx::query!(
- r#"
- SELECT tier as "tier!: TeamUserTier"
- FROM team_user
- WHERE user_id = $1 AND team_id != $2
- "#,
- user_id.as_ref(),
- exclude_team_id,
- )
- .fetch_all(&self.pool)
- .await?;
-
- Ok(tiers.into_iter().map(|row| row.tier).collect())
- }
-
#[tracing::instrument(skip(self), err)]
async fn get_team_members(
&self,
@@ -955,4 +934,66 @@ impl TeamRepository for TeamRepositoryImpl {
Ok(team_role)
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_team_member(
+ &self,
+ team_id: &uuid::Uuid,
+ user_id: &MacroUserIdStr<'_>,
+ ) -> Result<TeamMember<'_>, TeamError> {
+ let member = sqlx::query!(
+ r#"
+ SELECT user_id,
+ team_role as "team_role!: TeamRole",
+ tier as "tier!: TeamUserTier"
+ FROM team_user
+ WHERE team_id = $1
+ AND user_id = $2
+ "#,
+ team_id,
+ user_id.as_ref(),
+ )
+ .try_map(|r| {
+ Ok(TeamMember {
+ user_id: MacroUserIdStr::parse_from_str(&r.user_id)
+ .map_err(type_err)?
+ .into_owned(),
+ team_id: *team_id,
+ role: r.team_role,
+ tier: r.tier,
+ })
+ })
+ .fetch_one(&self.pool)
+ .await?;
+
+ 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(())
+ }
}
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 3d4ec88c07..79591ef378 100644
--- a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
+++ b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs
@@ -75,14 +75,14 @@ async fn test_get_team_subscription_id(pool: Pool<Postgres>) -> anyhow::Result<(
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 user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let result = team_repo
.create_team(&user_id, "team1", &TeamUserTier::Sonnet)
.await?;
assert!(!result.id.to_string().is_empty());
assert_eq!(result.name, "team1");
- assert_eq!(result.owner_id.0.as_ref(), "macro|[email protected]");
+ assert_eq!(result.owner_id.0.as_ref(), "macro|[email protected]");
// Create team with too large a name
let err = team_repo
@@ -385,12 +385,12 @@ async fn test_accept_team_invite_uses_invite_tier(pool: Pool<Postgres>) -> anyho
async fn test_is_user_member_of_team(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
- // [email protected] is an owner on team1 and team3
+ // [email protected] is an owner on team1
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let is_member = team_repo.is_user_member_of_team(&user_id).await?;
assert!(is_member);
- // [email protected] is a member of team1 and team2
+ // [email protected] is a member of team1
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
let is_member = team_repo.is_user_member_of_team(&user_id).await?;
assert!(is_member);
@@ -471,127 +471,77 @@ async fn test_bump_seat_count_negative(pool: Pool<Postgres>) -> anyhow::Result<(
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("teams_remaining_tiers"))
+ fixtures(path = "../../../fixtures", scripts("teams"))
)]
-async fn test_get_user_remaining_tiers_multi_team_user(pool: Pool<Postgres>) -> anyhow::Result<()> {
+async fn test_get_team_member(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- let team_a = macro_uuid::string_to_uuid("aaaa1111-1111-1111-1111-111111111111")?;
- let team_b = macro_uuid::string_to_uuid("bbbb2222-2222-2222-2222-222222222222")?;
- let team_c = macro_uuid::string_to_uuid("cccc3333-3333-3333-3333-333333333333")?;
+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
- // Excluding Team A (haiku): should still have Sonnet and Opus from B and C
- let tiers = team_repo
- .get_user_remaining_tiers(&user_id, &team_a)
- .await?;
- assert!(tiers.contains(&TeamUserTier::Sonnet));
- assert!(tiers.contains(&TeamUserTier::Opus));
- assert!(!tiers.contains(&TeamUserTier::Haiku));
+ // Get existing member
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ let member = team_repo.get_team_member(&team_id, &user_id).await?;
- // Excluding Team B (sonnet): should still have Haiku and Opus from A and C
- let tiers = team_repo
- .get_user_remaining_tiers(&user_id, &team_b)
- .await?;
- assert!(tiers.contains(&TeamUserTier::Haiku));
- assert!(tiers.contains(&TeamUserTier::Opus));
- assert!(!tiers.contains(&TeamUserTier::Sonnet));
+ assert_eq!(member.user_id.as_ref(), "macro|[email protected]");
+ assert_eq!(member.team_id, team_id);
+ assert_eq!(member.role, TeamRole::Member);
- // Excluding Team C (opus): should still have Haiku and Sonnet from A and B
- let tiers = team_repo
- .get_user_remaining_tiers(&user_id, &team_c)
- .await?;
- assert!(tiers.contains(&TeamUserTier::Haiku));
- assert!(tiers.contains(&TeamUserTier::Sonnet));
- assert!(!tiers.contains(&TeamUserTier::Opus));
+ // Get owner
+ let owner_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ let member = team_repo.get_team_member(&team_id, &owner_id).await?;
- Ok(())
-}
+ assert_eq!(member.user_id.as_ref(), "macro|[email protected]");
+ assert_eq!(member.role, TeamRole::Owner);
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("teams_remaining_tiers"))
-)]
-async fn test_get_user_remaining_tiers_single_team_user(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let team_repo = TeamRepositoryImpl::new(pool);
-
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- let team_a = macro_uuid::string_to_uuid("aaaa1111-1111-1111-1111-111111111111")?;
+ // Get non-existent member
+ let missing_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ let err = team_repo
+ .get_team_member(&team_id, &missing_id)
+ .await
+ .err()
+ .unwrap();
- // [email protected] is only in Team A; excluding it should return empty
- let tiers = team_repo
- .get_user_remaining_tiers(&user_id, &team_a)
- .await?;
- assert!(tiers.is_empty());
+ assert!(err.to_string().contains("does not exist"));
Ok(())
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("teams_remaining_tiers"))
+ fixtures(path = "../../../fixtures", scripts("teams"))
)]
-async fn test_get_user_remaining_tiers_user_not_in_any_team(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
+async fn test_patch_team_tier(pool: Pool<Postgres>) -> anyhow::Result<()> {
let team_repo = TeamRepositoryImpl::new(pool);
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- let team_a = macro_uuid::string_to_uuid("aaaa1111-1111-1111-1111-111111111111")?;
+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- // User not in any team should return empty
- let tiers = team_repo
- .get_user_remaining_tiers(&user_id, &team_a)
+ // Patch tier to Opus
+ team_repo
+ .patch_team_tier(&team_id, &user_id, TeamUserTier::Opus)
.await?;
- assert!(tiers.is_empty());
-
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("teams_remaining_tiers"))
-)]
-async fn test_get_user_remaining_tiers_includes_owner_role(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let team_repo = TeamRepositoryImpl::new(pool);
- // [email protected] is owner on all 3 teams — their tiers are included
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- let team_a = macro_uuid::string_to_uuid("aaaa1111-1111-1111-1111-111111111111")?;
+ // Verify the tier was updated
+ let member = team_repo.get_team_member(&team_id, &user_id).await?;
+ assert_eq!(member.tier, TeamUserTier::Opus);
- let tiers = team_repo
- .get_user_remaining_tiers(&user_id, &team_a)
+ // Patch tier to Haiku
+ team_repo
+ .patch_team_tier(&team_id, &user_id, TeamUserTier::Haiku)
.await?;
- assert!(tiers.contains(&TeamUserTier::Sonnet));
- assert!(tiers.contains(&TeamUserTier::Opus));
- Ok(())
-}
-
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("teams_remaining_tiers"))
-)]
-async fn test_get_user_remaining_tiers_excluding_nonexistent_team(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let team_repo = TeamRepositoryImpl::new(pool);
+ let member = team_repo.get_team_member(&team_id, &user_id).await?;
+ assert_eq!(member.tier, TeamUserTier::Haiku);
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- let fake_team = macro_uuid::string_to_uuid("deadbeef-dead-beef-dead-beefdeadbeef")?;
+ // 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();
- // Excluding a team the user isn't in should return all their tiers
- let tiers = team_repo
- .get_user_remaining_tiers(&user_id, &fake_team)
- .await?;
- assert!(tiers.contains(&TeamUserTier::Haiku));
- assert!(tiers.contains(&TeamUserTier::Sonnet));
- assert!(tiers.contains(&TeamUserTier::Opus));
- assert_eq!(tiers.len(), 3);
+ assert!(err.to_string().contains("member not found"));
Ok(())
}