Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(teams) support tiers team members (#2175)
Will Hutchinsonc8474146adf1
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.tsindex 3debcd991d..d9742385d6 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,6 +14,8 @@ 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/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex 3641f3f8bc..4b0446f1d7 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -3550,7 +3550,7 @@"TeamMember": {"type": "object","description": "The team member struct",- "required": ["team_id", "user_id", "role"],+ "required": ["team_id", "user_id", "role", "tier"],"properties": {"role": {"$ref": "#/components/schemas/TeamRole",@@ -3561,6 +3561,10 @@"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"diff --git a/js/app/scripts/generate-api-schema.ts b/js/app/scripts/generate-api-schema.tsindex 8fb58241ed..abc541a9a4 100644--- a/js/app/scripts/generate-api-schema.ts+++ b/js/app/scripts/generate-api-schema.ts@@ -10,7 +10,7 @@ import * as path from 'node:path';import { $, write } from 'bun';import { type Service, services } from './services';-const MAX_CONCURRENCY = 6;+const elapsed = (start: number) => `${((performance.now() - start) / 1000).toFixed(1)}s`;// Map service names to Rust crate namesconst serviceToCrate: Record<string, string> = {@@ -33,42 +33,34 @@ const getServiceClientsDir = () => path.resolve(import.meta.dirname, '../package// Parse argumentsconst getTargetServices = () => process.argv.slice(2).filter(arg => arg !== '--check');-// Build OpenAPI binaries. In CI (--check), batches to MAX_CONCURRENCY to limit resource usage.-async function buildOpenApiBinaries(crateNames: string[], { checkMode = false, rustCloudStorageDir = getRustCloudStorageDir() } = {}): Promise<void> {+// Build all OpenAPI binaries in a single cargo invocation (cargo parallelizes internally).+async function buildOpenApiBinaries(crateNames: string[], { rustCloudStorageDir = getRustCloudStorageDir() } = {}): Promise<void> {if (crateNames.length === 0) return;- const batchSize = checkMode ? MAX_CONCURRENCY : crateNames.length;+ const binArgs = crateNames.flatMap(crate => ['--bin', `${crate}_openapi`]);- for (let i = 0; i < crateNames.length; i += batchSize) {- const batch = crateNames.slice(i, i + batchSize);- const packageArgs = batch.flatMap(crate => ['-p', crate]);- const binArgs = batch.flatMap(crate => ['--bin', `${crate}_openapi`]);-- // Also build the DCS models binary if document_cognition_service is included- if (batch.includes('document_cognition_service')) {- binArgs.push('--bin', 'document_cognition_service_models');- }-- if (batchSize < crateNames.length) {- console.log(`Building batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(crateNames.length / batchSize)} (${batch.length} crates)...`);- } else {- console.log(`Building ${crateNames.length} OpenAPI binaries in parallel...`);- }- await $`cd ${rustCloudStorageDir} && SQLX_OFFLINE=true cargo build --release ${packageArgs} ${binArgs}`;+ // Also build the DCS models + tools binaries if document_cognition_service is included+ if (crateNames.includes('document_cognition_service')) {+ binArgs.push('--bin', 'document_cognition_service_models');+ binArgs.push('--bin', 'gen_tool_schemas');}++ console.log(`Building ${crateNames.length} OpenAPI binaries...`);+ console.log(`cargo build args: ${binArgs.join(' ')}`);+ await $`cd ${rustCloudStorageDir} && SQLX_OFFLINE=true cargo build ${binArgs}`;console.log('Build complete.\n');}// Run pre-built binary directly (no cargo lock needed)async function runOpenApiBinary(crateName: string, rustCloudStorageDir = getRustCloudStorageDir()): Promise<string> {- const binaryPath = path.join(rustCloudStorageDir, 'target', 'release', `${crateName}_openapi`);+ const binaryPath = path.join(rustCloudStorageDir, 'target', 'debug', `${crateName}_openapi`);const result = await $`${binaryPath}`.text();return result;}-// Run a named binary from the release directory+// Run a named binary from the debug directoryasync function runBinary(binaryName: string, rustCloudStorageDir = getRustCloudStorageDir()): Promise<string> {- const binaryPath = path.join(rustCloudStorageDir, 'target', 'release', binaryName);+ const binaryPath = path.join(rustCloudStorageDir, 'target', 'debug', binaryName);const result = await $`${binaryPath}`.text();return result;}@@ -127,10 +119,12 @@ const processService = async (service: Service, { serviceClientsDir }: { serviceconst generatedDir = path.resolve(outputDir, 'generated');const openApiPath = path.join(outputDir, 'openapi.json');- console.log(`[${service.name}] Running OpenAPI binary...`);+ const serviceStart = performance.now();- // Run pre-built binary directly+ console.log(`[${service.name}] Running OpenAPI binary...`);+ let stepStart = performance.now();const openApiJson = await runOpenApiBinary(crateName);+ console.log(`[${service.name}] OpenAPI binary finished (${elapsed(stepStart)})`);// Remove existing generated dirawait $`rm -rf ${generatedDir}`.quiet();@@ -140,25 +134,30 @@ const processService = async (service: Service, { serviceClientsDir }: { serviceconsole.log(`[${service.name}] Saved OpenAPI spec`);// Run orval to generate types+ stepStart = performance.now();await $`cd ${serviceClientsDir} && bun run orval --config orval.config.ts --project ${service.orvalKey}`.quiet();+ console.log(`[${service.name}] Orval finished (${elapsed(stepStart)})`);// Special handling for document-cognitionif (service.name === 'document-cognition') {- // Run the models binary to get the models JSON from local Rust code+ stepStart = performance.now();const rustCloudStorageDir = getRustCloudStorageDir();const modelsJson = await runBinary('document_cognition_service_models', rustCloudStorageDir);+ console.log(`[${service.name}] Models binary finished (${elapsed(stepStart)})`);const modelsJsonPath = path.join(import.meta.dirname, '.models.json');await write(modelsJsonPath, modelsJson);+ stepStart = performance.now();const appDir = path.resolve(import.meta.dirname, '..');try {await $`cd ${appDir} && MODELS_JSON=${modelsJsonPath} bun scripts/generate-dcs-types.ts`.quiet();} finally {await $`rm -f ${modelsJsonPath}`.quiet();}+ console.log(`[${service.name}] DCS types generation finished (${elapsed(stepStart)})`);}- console.log(`[${service.name}] ✓ Done`);+ console.log(`[${service.name}] ✓ Done (total: ${elapsed(serviceStart)})`);return { service: service.name, status: 'success' as const };} catch (error) {console.error(`[${service.name}] Failed:`, error);@@ -181,10 +180,12 @@ async function main() {console.log(`\nProcessing ${servicesToProcess.length} service(s)...\n`);// Phase 1: Build all binaries in a single cargo invocation (parallelized by cargo)- await buildOpenApiBinaries(crateNames, { checkMode });+ const buildStart = performance.now();+ await buildOpenApiBinaries(crateNames);+ console.log(`Phase 1 (cargo build) total: ${elapsed(buildStart)}`);// Phase 2: Run binaries and generate TypeScript in parallel- console.log('Generating TypeScript clients in parallel...\n');+ console.log('\nGenerating TypeScript clients...\n');const results = await Promise.all(servicesToProcess.map(service => processService(service, { serviceClientsDir })));@@ -210,12 +211,15 @@ async function main() {// On NixOS, the npm-installed biome binary doesn't work due to dynamic linking issues.// We detect NixOS and use the system biome instead.const isNixOS = process.env.NIX_PATH !== undefined || (await Bun.file("/etc/os-release").exists() && (await Bun.file("/etc/os-release").text()).includes("NixOS"));+ const biomeStart = performance.now();+ console.log('\nRunning biome check...');if (isNixOS) {const systemBiomePath = await $`bash -c 'PATH=$(echo "$PATH" | tr ":" "\n" | grep -v node_modules | tr "\n" ":") which biome'`.text();await $`${systemBiomePath.trim()} check --write --unsafe packages/service-clients/`;} else {await $`biome check --write --unsafe packages/service-clients/`;}+ console.log(`Biome check finished (${elapsed(biomeStart)})`);// In check mode, verify no uncommitted changesif (checkMode) {diff --git a/js/app/scripts/generate-dcs-tools.ts b/js/app/scripts/generate-dcs-tools.tsindex 9628be5328..663521555a 100644--- a/js/app/scripts/generate-dcs-tools.ts+++ b/js/app/scripts/generate-dcs-tools.ts@@ -100,14 +100,14 @@ type AiToolsResponse = z.infer<typeof AiToolsResponseSchema>["schemas"];async function buildAndRunSchemaGenerator(): Promise<void> {console.log("Building gen_tool_schemas binary...");- await $`cd ${rustCloudStorageDir} && SQLX_OFFLINE=true cargo build --release -p ai_tools --bin gen_tool_schemas`;+ await $`cd ${rustCloudStorageDir} && SQLX_OFFLINE=true cargo build --bin gen_tool_schemas`;console.log("Build complete.");// Remove existing schemas dir if it exists (the binary expects to create it)await $`rm -rf ${path.join(aiToolsDir, "schemas")}`.quiet();console.log("Running gen_tool_schemas...");- const binaryPath = path.join(rustCloudStorageDir, "target", "release", "gen_tool_schemas");+ const binaryPath = path.join(rustCloudStorageDir, "target", "debug", "gen_tool_schemas");await $`cd ${aiToolsDir} && ${binaryPath}`;console.log("Schema generation complete.");}diff --git a/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs b/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rsindex 2c1958ef05..8c76ba00ff 100644--- a/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs+++ b/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs@@ -363,12 +363,18 @@ async fn handle_team_subscription_event(team_id: &uuid::Uuid,tracking_data: SubscriptionTrackingData,) -> anyhow::Result<()> {+ tracing::trace!("handling team subscription");+if subscription_status == "trialing" {anyhow::bail!("unexpected trialing status for team subscription");}match subscription_status {"active" => {+ ctx.teams_service+ .restore_permissions_for_team_members(team_id)+ .await?;+track_stripe_subscription(ctx.analytics_client.clone(), subscription_id, tracking_data);Ok(())}diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex 22dbeffa2f..3ee1dd3739 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -228,7 +228,11 @@ async fn main() -> anyhow::Result<()> {let teams_repo_impl = TeamRepositoryImpl::new(db.clone());let customer_repo_impl = CustomerRepositoryImpl::new(stripe_client.clone(),- &config.stripe_price_ids.stripe_price_id_haiku,+ teams::outbound::customer_repo::StripePriceIds {+ haiku: config.stripe_price_ids.stripe_price_id_haiku.to_string(),+ sonnet: config.stripe_price_ids.stripe_price_id_sonnet.to_string(),+ opus: config.stripe_price_ids.stripe_price_id_opus.to_string(),+ },);let team_channels_repo_impl = TeamChannelsRepositoryImpl::new(db.clone());diff --git a/rust/cloud-storage/macro_db_client/migrations/20260325131311_team_user_tier.sql b/rust/cloud-storage/macro_db_client/migrations/20260325131311_team_user_tier.sqlnew file mode 100644index 0000000000..44894d966e--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260325131311_team_user_tier.sql@@ -0,0 +1,7 @@+-- Create new enum for the team users tier+-- Ordered from lowest tier to highest tier+CREATE TYPE "team_user_tier" AS ENUM ('haiku', 'sonnet', 'opus');++-- Add in a new tier associated with each team member+-- NOTE: we will keep track of the owners tier this way as well as they are stored in the team_user table+ALTER TABLE "team_user" ADD COLUMN tier "team_user_tier" NOT NULL DEFAULT 'haiku';diff --git a/rust/cloud-storage/macro_db_client/migrations/20260325154744_team_invite_tier.sql b/rust/cloud-storage/macro_db_client/migrations/20260325154744_team_invite_tier.sqlnew file mode 100644index 0000000000..588d4c8fce--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260325154744_team_invite_tier.sql@@ -0,0 +1,2 @@+-- Add a way to assign a custom tier to a team member on invite+ALTER TABLE "team_invite" ADD COLUMN tier "team_user_tier" NOT NULL DEFAULT 'haiku';diff --git a/rust/cloud-storage/roles_and_permissions/.sqlx/query-8717ae7a285b36ee3b82b3688a274b9734ecd81e4e1e1d0f7a1fc3a7d2c2c053.json b/rust/cloud-storage/roles_and_permissions/.sqlx/query-8717ae7a285b36ee3b82b3688a274b9734ecd81e4e1e1d0f7a1fc3a7d2c2c053.jsonnew file mode 100644index 0000000000..9685f5f4fb--- /dev/null+++ b/rust/cloud-storage/roles_and_permissions/.sqlx/query-8717ae7a285b36ee3b82b3688a274b9734ecd81e4e1e1d0f7a1fc3a7d2c2c053.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n ru.\"roleId\" as role_id\n FROM \"RolesOnUsers\" ru\n WHERE ru.\"userId\" = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "role_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "8717ae7a285b36ee3b82b3688a274b9734ecd81e4e1e1d0f7a1fc3a7d2c2c053"+}diff --git a/rust/cloud-storage/roles_and_permissions/src/domain/model.rs b/rust/cloud-storage/roles_and_permissions/src/domain/model.rsindex 16b6b640a5..3241167ada 100644--- a/rust/cloud-storage/roles_and_permissions/src/domain/model.rs+++ b/rust/cloud-storage/roles_and_permissions/src/domain/model.rs@@ -61,6 +61,31 @@ pub enum RoleId {SubOpus,}+impl FromStr for RoleId {+ type Err = anyhow::Error;+ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "professional_subscriber" => Ok(RoleId::ProfessionalSubscriber),+ "team_subscriber" => Ok(RoleId::TeamSubscriber),+ "corporate" => Ok(RoleId::Corporate),+ "partner_sales" => Ok(RoleId::PartnerSales),+ "self_serve" => Ok(RoleId::SelfServe),+ "super_admin" => Ok(RoleId::SuperAdmin),+ "online_subscriber" => Ok(RoleId::OnlineSubscriber),+ "organization_it" => Ok(RoleId::OrganizationIt),+ "manage_organization_subscription" => Ok(RoleId::ManageOrganizationSubscription),+ "email_tool" => Ok(RoleId::EmailTool),+ "email_tool_on_prem" => Ok(RoleId::EmailToolOnPrem),+ "ai_subscriber" => Ok(RoleId::AiSubscriber),+ "editor_user" => Ok(RoleId::EditorUser),+ "sub_haiku" => Ok(RoleId::SubHaiku),+ "sub_sonnet" => Ok(RoleId::SubSonnet),+ "sub_opus" => Ok(RoleId::SubOpus),+ _ => anyhow::bail!("unknown role id: {s}"),+ }+ }+}+impl Display for RoleId {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {@@ -246,7 +271,7 @@ impl TryFrom<&str> for SubscriptionStatus {"canceled" => Ok(Self::Canceled),"unpaid" => Ok(Self::Unpaid),"paused" => Ok(Self::Paused),- _ => Err(anyhow::anyhow!("invalid subscription status {value}")),+ _ => anyhow::bail!("invalid subscription status {value}"),}}}diff --git a/rust/cloud-storage/roles_and_permissions/src/domain/port.rs b/rust/cloud-storage/roles_and_permissions/src/domain/port.rsindex 7d129ef9e8..647822807d 100644--- a/rust/cloud-storage/roles_and_permissions/src/domain/port.rs+++ b/rust/cloud-storage/roles_and_permissions/src/domain/port.rs@@ -22,6 +22,12 @@ pub trait UserRepository: Clone + Send + Sync + 'static {/// The UserRolesAndPermissionsRepository defines a set of actions to perform on the users roles and permissionspub trait UserRolesAndPermissionsRepository: Clone + Send + Sync + 'static {+ /// Gets the roles for a MacroUserID+ fn get_user_roles(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<HashSet<RoleId>, UserRolesAndPermissionsError>> + Send;+/// Gets the permissiosn for a MacroUserIDfn get_user_permissions(&self,@@ -43,6 +49,12 @@ pub trait UserRolesAndPermissionsRepository: Clone + Send + Sync + 'static {/// The UserRolesAndPermissionsService defines a set of actions to perform on the users for their roles and permissionspub trait UserRolesAndPermissionsService: Clone + Send + Sync + 'static {+ /// Gets the users roles+ fn get_user_roles(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<HashSet<RoleId>, UserRolesAndPermissionsError>> + Send;+/// Gets the users permissionsfn get_user_permissions(&self,diff --git a/rust/cloud-storage/roles_and_permissions/src/domain/port/test.rs b/rust/cloud-storage/roles_and_permissions/src/domain/port/test.rsindex 212b39d748..4b0fb82dde 100644--- a/rust/cloud-storage/roles_and_permissions/src/domain/port/test.rs+++ b/rust/cloud-storage/roles_and_permissions/src/domain/port/test.rs@@ -25,6 +25,13 @@ impl UserRepository for MockUserRepository {struct MockUserRolesAndPermissionsRepository {}impl UserRolesAndPermissionsRepository for MockUserRolesAndPermissionsRepository {+ async fn get_user_roles(+ &self,+ _user_id: &MacroUserIdStr<'_>,+ ) -> Result<HashSet<RoleId>, UserRolesAndPermissionsError> {+ Ok(HashSet::from([RoleId::SelfServe]))+ }+async fn get_user_permissions(&self,_user_id: &MacroUserIdStr<'_>,@@ -111,6 +118,20 @@ async fn test_add_roles_to_user() -> anyhow::Result<()> {Ok(())}+#[tokio::test]+async fn test_get_user_roles() -> anyhow::Result<()> {+ let user_roles_and_permissions_repository = MockUserRolesAndPermissionsRepository::default();++ let roles = user_roles_and_permissions_repository+ .get_user_roles(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)+ .await?;++ assert_eq!(roles.len(), 1);+ assert!(roles.contains(&RoleId::SelfServe));++ Ok(())+}+#[tokio::test]async fn test_remove_roles_from_user() -> anyhow::Result<()> {let user_roles_and_permissions_repository = MockUserRolesAndPermissionsRepository::default();diff --git a/rust/cloud-storage/roles_and_permissions/src/domain/service.rs b/rust/cloud-storage/roles_and_permissions/src/domain/service.rsindex 75b31dd810..ed3b3f38ce 100644--- a/rust/cloud-storage/roles_and_permissions/src/domain/service.rs+++ b/rust/cloud-storage/roles_and_permissions/src/domain/service.rs@@ -110,4 +110,14 @@ where.map(|p| p.id).collect())}++ #[tracing::instrument(skip(self), err)]+ async fn get_user_roles(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> Result<std::collections::HashSet<RoleId>, UserRolesAndPermissionsError> {+ self.user_roles_and_permissions_repository+ .get_user_roles(user_id)+ .await+ }}diff --git a/rust/cloud-storage/roles_and_permissions/src/domain/service/test.rs b/rust/cloud-storage/roles_and_permissions/src/domain/service/test.rsindex d37904c7eb..033f2b3f99 100644--- a/rust/cloud-storage/roles_and_permissions/src/domain/service/test.rs+++ b/rust/cloud-storage/roles_and_permissions/src/domain/service/test.rs@@ -41,6 +41,16 @@ impl MockUserRolesAndPermissionsRepository {}impl UserRolesAndPermissionsRepository for MockUserRolesAndPermissionsRepository {+ async fn get_user_roles(+ &self,+ _user_id: &MacroUserIdStr<'_>,+ ) -> Result<HashSet<RoleId>, UserRolesAndPermissionsError> {+ Ok(HashSet::from([+ RoleId::SelfServe,+ RoleId::ProfessionalSubscriber,+ ]))+ }+async fn get_user_permissions(&self,_user_id: &MacroUserIdStr<'_>,@@ -105,3 +115,47 @@ async fn test_user_respository_get_user_id_by_email() -> anyhow::Result<()> {);Ok(())}++#[tokio::test]+async fn test_get_user_roles() -> anyhow::Result<()> {+ let mock_user_repository = MockUserRepository::default();+ let mock_user_roles_and_permissions_repository =+ MockUserRolesAndPermissionsRepository::default();++ let user_service = UserRolesAndPermissionsServiceImpl::new(+ mock_user_roles_and_permissions_repository,+ mock_user_repository,+ );++ let roles = user_service+ .get_user_roles(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)+ .await?;++ assert_eq!(roles.len(), 2);+ assert!(roles.contains(&RoleId::SelfServe));+ assert!(roles.contains(&RoleId::ProfessionalSubscriber));++ Ok(())+}++#[tokio::test]+async fn test_get_user_roles_delegates_to_repository() -> anyhow::Result<()> {+ let mock_user_repository = MockUserRepository::default();+ let mock_user_roles_and_permissions_repository =+ MockUserRolesAndPermissionsRepository::default();++ let user_service = UserRolesAndPermissionsServiceImpl::new(+ mock_user_roles_and_permissions_repository,+ mock_user_repository,+ );++ let roles = user_service+ .get_user_roles(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)+ .await?;++ // Mock returns the same roles regardless of user_id+ assert!(roles.contains(&RoleId::SelfServe));+ assert!(roles.contains(&RoleId::ProfessionalSubscriber));++ Ok(())+}diff --git a/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool.rs b/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool.rsindex 854be28de3..fcbd71abae 100644--- a/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool.rs+++ b/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool.rs@@ -14,7 +14,7 @@ use macro_user_id::{use sqlx::PgPool;use crate::domain::{- model::{Permission, RoleId, UserRolesAndPermissionsError},+ model::{Permission, PermissionId, RoleId, UserRolesAndPermissionsError},port::{UserRepository, UserRolesAndPermissionsRepository},};@@ -117,9 +117,19 @@ impl MacroDB {"#,user_id.as_ref(),)- .map(|r| Permission::new(r.id.parse().unwrap(), r.description)).fetch_all(&self.pool)- .await?;+ .await?+ .into_iter()+ .filter_map(|r| {+ let permission_id: Option<PermissionId> = r.id.parse().ok();+ if let Some(permission_id) = permission_id {+ Some(Permission::new(permission_id, r.description))+ } else {+ tracing::warn!(permission_id=%r.id, "unknown permission id");+ None+ }+ })+ .collect();let user_permissions = user_permissions.into_iter().collect::<HashSet<_>>();@@ -137,6 +147,34 @@ impl From<sqlx::Error> for UserRolesAndPermissionsError {}impl UserRolesAndPermissionsRepository for MacroDB {+ #[tracing::instrument(skip(self), err)]+ async fn get_user_roles(+ &self,+ user_id: &MacroUserIdStr<'_>,+ ) -> Result<HashSet<RoleId>, UserRolesAndPermissionsError> {+ let user_roles: Vec<RoleId> = sqlx::query!(+ r#"+ SELECT+ ru."roleId" as role_id+ FROM "RolesOnUsers" ru+ WHERE ru."userId" = $1+ "#,+ user_id.as_ref()+ )+ .fetch_all(&self.pool)+ .await?+ .iter()+ .filter_map(|r| {+ r.role_id.parse().ok().or_else(|| {+ tracing::warn!(role_id = %r.role_id, "Unknown role_id in database, skipping");+ None+ })+ })+ .collect();++ Ok(user_roles.into_iter().collect::<HashSet<_>>())+ }+async fn get_user_permissions(&self,user_id: &MacroUserIdStr<'_>,diff --git a/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool/test.rs b/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool/test.rsindex e71fac4cb2..ea9e6c3e6e 100644--- a/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool/test.rs+++ b/rust/cloud-storage/roles_and_permissions/src/outbound/pgpool/test.rs@@ -144,3 +144,88 @@ async fn test_remove_roles_from_user(pool: Pool<Postgres>) -> anyhow::Result<()>Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("users"))+)]+async fn test_get_user_roles(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let macro_db = MacroDB::new(pool);++ // [email protected] has professional_subscriber and corporate+ let roles = UserRolesAndPermissionsRepository::get_user_roles(+ ¯o_db,+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,+ )+ .await?;++ assert_eq!(roles.len(), 2);+ assert!(roles.contains(&RoleId::ProfessionalSubscriber));+ assert!(roles.contains(&RoleId::Corporate));++ // [email protected] has only corporate+ let roles = UserRolesAndPermissionsRepository::get_user_roles(+ ¯o_db,+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,+ )+ .await?;++ assert_eq!(roles.len(), 1);+ assert!(roles.contains(&RoleId::Corporate));++ // user that doesn't exist returns empty set+ let roles = UserRolesAndPermissionsRepository::get_user_roles(+ ¯o_db,+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,+ )+ .await?;++ assert!(roles.is_empty());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("users"))+)]+async fn test_get_user_roles_after_add_and_remove(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let macro_db = MacroDB::new(pool);++ // Add a role and verify it shows up+ macro_db+ .add_roles_to_user(+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,+ &["self_serve".to_string()],+ )+ .await?;++ let roles = UserRolesAndPermissionsRepository::get_user_roles(+ ¯o_db,+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,+ )+ .await?;++ assert_eq!(roles.len(), 2);+ assert!(roles.contains(&RoleId::Corporate));+ assert!(roles.contains(&RoleId::SelfServe));++ // Remove the role and verify it's gone+ macro_db+ .remove_roles_from_user(+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,+ &["self_serve".to_string()],+ )+ .await?;++ let roles = UserRolesAndPermissionsRepository::get_user_roles(+ ¯o_db,+ &MacroUserIdStr::parse_from_str("macro|[email protected]")?,+ )+ .await?;++ assert_eq!(roles.len(), 1);+ assert!(roles.contains(&RoleId::Corporate));++ Ok(())+}diff --git a/rust/cloud-storage/teams/.sqlx/query-faf480f442ad8f5864ede47f580b5b9feb8ce049c8b1826d7d7043d3054f8a73.json b/rust/cloud-storage/teams/.sqlx/query-0e03c9e174ceafd652563ce587e5025e8bf0dd3532b21cc1e2a939c0c26c7927.jsonsimilarity index 69%rename from rust/cloud-storage/teams/.sqlx/query-faf480f442ad8f5864ede47f580b5b9feb8ce049c8b1826d7d7043d3054f8a73.jsonrename to rust/cloud-storage/teams/.sqlx/query-0e03c9e174ceafd652563ce587e5025e8bf0dd3532b21cc1e2a939c0c26c7927.jsonindex 3f3f6acd3f..03bdd66fc9 100644--- a/rust/cloud-storage/teams/.sqlx/query-faf480f442ad8f5864ede47f580b5b9feb8ce049c8b1826d7d7043d3054f8a73.json+++ b/rust/cloud-storage/teams/.sqlx/query-0e03c9e174ceafd652563ce587e5025e8bf0dd3532b21cc1e2a939c0c26c7927.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT team_id FROM team_user\n WHERE user_id = $1 AND team_role NOT IN ('owner')\n ",+ "query": "\n SELECT team_id FROM team_user\n WHERE user_id = $1\n ","describe": {"columns": [{@@ -18,5 +18,5 @@false]},- "hash": "faf480f442ad8f5864ede47f580b5b9feb8ce049c8b1826d7d7043d3054f8a73"+ "hash": "0e03c9e174ceafd652563ce587e5025e8bf0dd3532b21cc1e2a939c0c26c7927"}diff --git a/rust/cloud-storage/teams/.sqlx/query-0f2057f8430788bb20f5d0f144445f28fba6434c9a2fe208e0a4a45b892dea2b.json b/rust/cloud-storage/teams/.sqlx/query-0f2057f8430788bb20f5d0f144445f28fba6434c9a2fe208e0a4a45b892dea2b.jsonnew file mode 100644index 0000000000..14012e1c66--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-0f2057f8430788bb20f5d0f144445f28fba6434c9a2fe208e0a4a45b892dea2b.json@@ -0,0 +1,87 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO team_user (team_id, user_id, team_role, tier)\n VALUES ($1, $2, $3, $4)\n RETURNING user_id, team_role as \"role!: TeamRole\", tier as \"tier!: TeamUserTier\", team_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "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"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "team_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ {+ "Custom": {+ "name": "team_role",+ "kind": {+ "Enum": [+ "member",+ "admin",+ "owner"+ ]+ }+ }+ },+ {+ "Custom": {+ "name": "team_user_tier",+ "kind": {+ "Enum": [+ "haiku",+ "sonnet",+ "opus"+ ]+ }+ }+ }+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false+ ]+ },+ "hash": "0f2057f8430788bb20f5d0f144445f28fba6434c9a2fe208e0a4a45b892dea2b"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-14ebe9e55b31c7dc4aec3553cff79e80942169ef55c62a990d3bbd54389e681a.json b/rust/cloud-storage/teams/.sqlx/query-14ebe9e55b31c7dc4aec3553cff79e80942169ef55c62a990d3bbd54389e681a.jsondeleted file mode 100644index 40a40653cc..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-14ebe9e55b31c7dc4aec3553cff79e80942169ef55c62a990d3bbd54389e681a.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM team_user\n WHERE team_id = $1 AND user_id = $2\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": []- },- "hash": "14ebe9e55b31c7dc4aec3553cff79e80942169ef55c62a990d3bbd54389e681a"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-169f49448d5e78ac04686fb3a6d0b86c07b91393f2dba801e4e51d3c8ab5e506.json b/rust/cloud-storage/teams/.sqlx/query-169f49448d5e78ac04686fb3a6d0b86c07b91393f2dba801e4e51d3c8ab5e506.jsonnew file mode 100644index 0000000000..9501e6b51c--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-169f49448d5e78ac04686fb3a6d0b86c07b91393f2dba801e4e51d3c8ab5e506.json@@ -0,0 +1,34 @@+{+ "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-1bf9b2bf67d4780b41454d87c4a1995677a162dd11af0b9d77df947b657cd651.json b/rust/cloud-storage/teams/.sqlx/query-1bf9b2bf67d4780b41454d87c4a1995677a162dd11af0b9d77df947b657cd651.jsondeleted file mode 100644index 8c916fcea0..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-1bf9b2bf67d4780b41454d87c4a1995677a162dd11af0b9d77df947b657cd651.json+++ /dev/null@@ -1,15 +0,0 @@-{- "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/teams/.sqlx/query-4f26a2f6044225dd1019390579a3652eafdf1db2ae15212335ebd5ecbb3b4ebe.json b/rust/cloud-storage/teams/.sqlx/query-4f26a2f6044225dd1019390579a3652eafdf1db2ae15212335ebd5ecbb3b4ebe.jsonnew file mode 100644index 0000000000..eb4edb65d2--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-4f26a2f6044225dd1019390579a3652eafdf1db2ae15212335ebd5ecbb3b4ebe.json@@ -0,0 +1,27 @@+{+ "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/teams/.sqlx/query-b60b1112072c68b63df317c76ae2bf8ac8a2162990c35916b021a462ccb9eb6c.json b/rust/cloud-storage/teams/.sqlx/query-50332c40ef917c839c4539f12419035115d61a4c9e8146a894e41db59b0f0daa.jsonsimilarity index 55%rename from rust/cloud-storage/teams/.sqlx/query-b60b1112072c68b63df317c76ae2bf8ac8a2162990c35916b021a462ccb9eb6c.jsonrename to rust/cloud-storage/teams/.sqlx/query-50332c40ef917c839c4539f12419035115d61a4c9e8146a894e41db59b0f0daa.jsonindex 3c3c366f95..76d5ad2fda 100644--- a/rust/cloud-storage/teams/.sqlx/query-b60b1112072c68b63df317c76ae2bf8ac8a2162990c35916b021a462ccb9eb6c.json+++ b/rust/cloud-storage/teams/.sqlx/query-50332c40ef917c839c4539f12419035115d61a4c9e8146a894e41db59b0f0daa.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT team_role as \"team_role!: TeamRole\", team_id\n FROM team_invite\n WHERE id = $1 AND email = $2\n ",+ "query": "\n SELECT team_role as \"team_role!: TeamRole\", team_id, tier as \"tier!: TeamUserTier\"\n FROM team_invite\n WHERE id = $1 AND email = $2\n ","describe": {"columns": [{@@ -23,6 +23,22 @@"ordinal": 1,"name": "team_id","type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "tier!: TeamUserTier",+ "type_info": {+ "Custom": {+ "name": "team_user_tier",+ "kind": {+ "Enum": [+ "haiku",+ "sonnet",+ "opus"+ ]+ }+ }+ }}],"parameters": {@@ -32,9 +48,10 @@]},"nullable": [+ false,false,false]},- "hash": "b60b1112072c68b63df317c76ae2bf8ac8a2162990c35916b021a462ccb9eb6c"+ "hash": "50332c40ef917c839c4539f12419035115d61a4c9e8146a894e41db59b0f0daa"}diff --git a/rust/cloud-storage/teams/.sqlx/query-a3a570d4857e91eb55d5e4299f9a856e70e71c0a070f0a1a005ba5e2aa7eabac.json b/rust/cloud-storage/teams/.sqlx/query-a3a570d4857e91eb55d5e4299f9a856e70e71c0a070f0a1a005ba5e2aa7eabac.jsonnew file mode 100644index 0000000000..4ec697bc9f--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-a3a570d4857e91eb55d5e4299f9a856e70e71c0a070f0a1a005ba5e2aa7eabac.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM team_invite\n WHERE id = $1 AND team_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "a3a570d4857e91eb55d5e4299f9a856e70e71c0a070f0a1a005ba5e2aa7eabac"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-b36669573fe9b78417dfafd57157822e24246a4ad2f6fb4f2366aa5af643cf58.json b/rust/cloud-storage/teams/.sqlx/query-b36669573fe9b78417dfafd57157822e24246a4ad2f6fb4f2366aa5af643cf58.jsondeleted file mode 100644index 66c0abf7d3..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-b36669573fe9b78417dfafd57157822e24246a4ad2f6fb4f2366aa5af643cf58.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE team\n SET seat_count = seat_count - 1\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": []- },- "hash": "b36669573fe9b78417dfafd57157822e24246a4ad2f6fb4f2366aa5af643cf58"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-b470add8d87f6fff56d158c2aa9bf5dd871973fd3b9b6e1f25033f24a2cde3bd.json b/rust/cloud-storage/teams/.sqlx/query-b470add8d87f6fff56d158c2aa9bf5dd871973fd3b9b6e1f25033f24a2cde3bd.jsonnew file mode 100644index 0000000000..81c4b7f8fe--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-b470add8d87f6fff56d158c2aa9bf5dd871973fd3b9b6e1f25033f24a2cde3bd.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM team_user\n WHERE team_id = $1 AND user_id = $2\n RETURNING tier AS \"tier!: TeamUserTier\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "tier!: TeamUserTier",+ "type_info": {+ "Custom": {+ "name": "team_user_tier",+ "kind": {+ "Enum": [+ "haiku",+ "sonnet",+ "opus"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "b470add8d87f6fff56d158c2aa9bf5dd871973fd3b9b6e1f25033f24a2cde3bd"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04.json b/rust/cloud-storage/teams/.sqlx/query-bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04.jsondeleted file mode 100644index c645aa3823..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04.json+++ /dev/null@@ -1,39 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT user_id,\n team_role as \"team_role!: TeamRole\"\n FROM team_user\n WHERE team_id = $1\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"- ]- }- }- }- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- false- ]- },- "hash": "bcb0dfd2aa420f102d8dd3484f65defd6cbcf8e801c4c4d43d5e0d1338e1ab04"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-312222d6afadd1145cc5e355ce27f3775163b674cc6b17b6329b6a7de6e6d3b6.json b/rust/cloud-storage/teams/.sqlx/query-d1f79f2a50de2167f06ac49f52b134ccc3b8eeb070e7fd710b18dbbfc783aa1d.jsonsimilarity index 53%rename from rust/cloud-storage/teams/.sqlx/query-312222d6afadd1145cc5e355ce27f3775163b674cc6b17b6329b6a7de6e6d3b6.jsonrename to rust/cloud-storage/teams/.sqlx/query-d1f79f2a50de2167f06ac49f52b134ccc3b8eeb070e7fd710b18dbbfc783aa1d.jsonindex 9ab2405604..12074b1ba2 100644--- a/rust/cloud-storage/teams/.sqlx/query-312222d6afadd1145cc5e355ce27f3775163b674cc6b17b6329b6a7de6e6d3b6.json+++ b/rust/cloud-storage/teams/.sqlx/query-d1f79f2a50de2167f06ac49f52b134ccc3b8eeb070e7fd710b18dbbfc783aa1d.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT user_id, \n team_role as \"team_role!: TeamRole\"\n FROM team_user\n WHERE team_id = $1 AND team_role NOT IN ('owner')\n ",+ "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 ","describe": {"columns": [{@@ -23,6 +23,22 @@}}}+ },+ {+ "ordinal": 2,+ "name": "tier!: TeamUserTier",+ "type_info": {+ "Custom": {+ "name": "team_user_tier",+ "kind": {+ "Enum": [+ "haiku",+ "sonnet",+ "opus"+ ]+ }+ }+ }}],"parameters": {@@ -31,9 +47,10 @@]},"nullable": [+ false,false,false]},- "hash": "312222d6afadd1145cc5e355ce27f3775163b674cc6b17b6329b6a7de6e6d3b6"+ "hash": "d1f79f2a50de2167f06ac49f52b134ccc3b8eeb070e7fd710b18dbbfc783aa1d"}diff --git a/rust/cloud-storage/teams/.sqlx/query-bb388935342b00b795083239b71fea0878d96b2f85889931bd59d94ff4318b81.json b/rust/cloud-storage/teams/.sqlx/query-d5ffa82610d978dab83826ea1dfe5c5fdba0126759ea99c27f91555adab1480d.jsonsimilarity index 53%rename from rust/cloud-storage/teams/.sqlx/query-bb388935342b00b795083239b71fea0878d96b2f85889931bd59d94ff4318b81.jsonrename to rust/cloud-storage/teams/.sqlx/query-d5ffa82610d978dab83826ea1dfe5c5fdba0126759ea99c27f91555adab1480d.jsonindex 4b9d573df4..b3cca681f4 100644--- a/rust/cloud-storage/teams/.sqlx/query-bb388935342b00b795083239b71fea0878d96b2f85889931bd59d94ff4318b81.json+++ b/rust/cloud-storage/teams/.sqlx/query-d5ffa82610d978dab83826ea1dfe5c5fdba0126759ea99c27f91555adab1480d.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO team_user (team_id, user_id, team_role)\n VALUES ($1, $2, $3)\n RETURNING user_id, team_role as \"role!: TeamRole\"\n ",+ "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 ","describe": {"columns": [{@@ -10,7 +10,7 @@},{"ordinal": 1,- "name": "role!: TeamRole",+ "name": "team_role!: TeamRole","type_info": {"Custom": {"name": "team_role",@@ -23,30 +23,34 @@}}}- }- ],- "parameters": {- "Left": [- "Uuid",- "Text",- {+ },+ {+ "ordinal": 2,+ "name": "tier!: TeamUserTier",+ "type_info": {"Custom": {- "name": "team_role",+ "name": "team_user_tier","kind": {"Enum": [- "member",- "admin",- "owner"+ "haiku",+ "sonnet",+ "opus"]}}}+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"]},"nullable": [+ false,false,false]},- "hash": "bb388935342b00b795083239b71fea0878d96b2f85889931bd59d94ff4318b81"+ "hash": "d5ffa82610d978dab83826ea1dfe5c5fdba0126759ea99c27f91555adab1480d"}diff --git a/rust/cloud-storage/teams/.sqlx/query-71f0916419e122c5dba653bdc23114987bb800ba14658efaac7cafd0c16672c8.json b/rust/cloud-storage/teams/.sqlx/query-d9a13a9704a1f510f984862914c0fda59b2d50ec3e26b9bf2659cc8b85e4f5a1.jsonsimilarity index 52%rename from rust/cloud-storage/teams/.sqlx/query-71f0916419e122c5dba653bdc23114987bb800ba14658efaac7cafd0c16672c8.jsonrename to rust/cloud-storage/teams/.sqlx/query-d9a13a9704a1f510f984862914c0fda59b2d50ec3e26b9bf2659cc8b85e4f5a1.jsonindex 51e00bbc86..86b13f1dcb 100644--- a/rust/cloud-storage/teams/.sqlx/query-71f0916419e122c5dba653bdc23114987bb800ba14658efaac7cafd0c16672c8.json+++ b/rust/cloud-storage/teams/.sqlx/query-d9a13a9704a1f510f984862914c0fda59b2d50ec3e26b9bf2659cc8b85e4f5a1.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT user_id, \n team_role as \"team_role!: TeamRole\"\n FROM team_user\n WHERE team_id = $1\n ",+ "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 AND team_role NOT IN ('owner')\n ","describe": {"columns": [{@@ -23,6 +23,22 @@}}}+ },+ {+ "ordinal": 2,+ "name": "tier!: TeamUserTier",+ "type_info": {+ "Custom": {+ "name": "team_user_tier",+ "kind": {+ "Enum": [+ "haiku",+ "sonnet",+ "opus"+ ]+ }+ }+ }}],"parameters": {@@ -31,9 +47,10 @@]},"nullable": [+ false,false,false]},- "hash": "71f0916419e122c5dba653bdc23114987bb800ba14658efaac7cafd0c16672c8"+ "hash": "d9a13a9704a1f510f984862914c0fda59b2d50ec3e26b9bf2659cc8b85e4f5a1"}diff --git a/rust/cloud-storage/teams/fixtures/teams.sql b/rust/cloud-storage/teams/fixtures/teams.sqlindex 76f2a9f20d..af4e741d2c 100644--- a/rust/cloud-storage/teams/fixtures/teams.sql+++ b/rust/cloud-storage/teams/fixtures/teams.sql@@ -16,9 +16,9 @@ VALUES ('11111111-1111-1111-1111-111111111111', 'team1', 'macro|[email protected]',('22222222-2222-2222-2222-222222222222', 'team2', 'macro|[email protected]', NULL, 1),('33333333-3333-3333-3333-333333333333', 'team3', 'macro|[email protected]', NULL, 1);-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_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_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.sqlnew file mode 100644index 0000000000..7fe75cd50a--- /dev/null+++ b/rust/cloud-storage/teams/fixtures/teams_remaining_tiers.sql@@ -0,0 +1,40 @@+-- Fixture for testing get_user_remaining_tiers+-- Sets up users in multiple teams with different tiers++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');++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');++-- 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);++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');diff --git a/rust/cloud-storage/teams/src/domain/customer_repo.rs b/rust/cloud-storage/teams/src/domain/customer_repo.rsindex 7ec88fbf3e..4b7401b42c 100644--- a/rust/cloud-storage/teams/src/domain/customer_repo.rs+++ b/rust/cloud-storage/teams/src/domain/customer_repo.rs@@ -1,9 +1,25 @@//! Contains the domain logic for teams handling the customers-use crate::domain::model::{CreateSubscriptionArgs, CustomerError};+use macro_user_id::user_id::MacroUserIdStr;++use crate::domain::model::{CreateSubscriptionArgs, CustomerError, TeamUserTier};/// The CustomerRepository defines a set of actions to perform on customer datapub trait CustomerRepository: Clone + Send + Sync + 'static {+ /// Mark subscription as a team subscription+ fn convert_subscription_to_team(+ &self,+ subscription_id: &stripe::SubscriptionId,+ team_id: &uuid::Uuid,+ team_owner_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send;++ /// Get the customers subscription id+ fn get_subscription_id_for_customer(+ &self,+ customer_id: &stripe::CustomerId,+ ) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send;+/// Create a new subscription for a customerfn create_subscription(&self,@@ -14,14 +30,22 @@ pub trait CustomerRepository: Clone + Send + Sync + 'static {fn increase_subscription_quantity(&self,subscription_id: &stripe::SubscriptionId,- increase_amount: u64,+ tier: TeamUserTier,) -> impl Future<Output = Result<(), CustomerError>> + Send;/// Decrement the quantity of a subscriptionfn decrease_subscription_quantity(&self,subscription_id: &stripe::SubscriptionId,- decrease_amount: u64,+ 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.diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rsindex 5208af985e..0838d11426 100644--- a/rust/cloud-storage/teams/src/domain/model.rs+++ b/rust/cloud-storage/teams/src/domain/model.rs@@ -1,16 +1,71 @@//! Contains the models for teams-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use chrono::{DateTime, Utc};use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};-use roles_and_permissions::domain::model::UserRolesAndPermissionsError;+use roles_and_permissions::domain::model::{RoleId, UserRolesAndPermissionsError};-#[derive(- Eq, PartialEq, Debug, Clone, PartialOrd, sqlx::Type, Copy, std::cmp::Ord, serde::Serialize,+#[derive(Eq, PartialEq, Debug, Clone, Hash, PartialOrd, Copy, std::cmp::Ord, serde::Serialize)]+#[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 {+ /// 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")+ }+ }+}++#[derive(Eq, PartialEq, Debug, Clone, PartialOrd, Copy, std::cmp::Ord, serde::Serialize)]#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]-#[sqlx(type_name = "\"team_role\"", rename_all = "lowercase")]+#[cfg_attr(feature = "outbound", derive(sqlx::Type))]+#[cfg_attr(+ feature = "outbound",+ sqlx(type_name = "\"team_role\"", rename_all = "lowercase")+)]/// Ordered from least to most access top -> bottompub enum TeamRole {/// The user is a member of the team@@ -42,6 +97,9 @@ pub struct TeamMember<'a> {pub user_id: MacroUserIdStr<'a>,/// The role of the team memberpub role: TeamRole,+ /// The tier of the team member+ #[cfg_attr(feature = "axum", schema(value_type = String))]+ pub tier: TeamUserTier,}/// A team with its members@@ -88,12 +146,13 @@ pub struct PatchTeamRequest {pub struct Team {pub(crate) id: uuid::Uuid,pub(crate) name: String,- pub(crate) owner_id: String,+ #[cfg_attr(feature = "axum", schema(value_type = String))]+ pub(crate) owner_id: MacroUserIdStr<'static>,}impl Team {/// Creates a new Team- pub fn new(id: uuid::Uuid, name: String, owner_id: String) -> Self {+ pub fn new(id: uuid::Uuid, name: String, owner_id: MacroUserIdStr<'static>) -> Self {Self { id, name, owner_id }}}@@ -111,7 +170,7 @@ impl Team {/// The owner id of the teampub fn owner_id(&self) -> &str {- &self.owner_id+ self.owner_id.as_ref()}}@@ -337,3 +396,14 @@ pub enum RevokePermissionsForTeamMembersError {#[error("Underlying user roles and permissions error")]RemoveRolesFromUserError(#[from] UserRolesAndPermissionsError),}++/// Error when restoring permissions for team members+#[derive(Debug, thiserror::Error)]+pub enum RestorePermissionsForTeamMembersError {+ /// Underlying team error+ #[error("Underlying team error")]+ TeamError(#[from] TeamError),+ /// Underlying user roles and permissions error+ #[error("Underlying user roles and permissions error")]+ AddRolesToUserError(#[from] UserRolesAndPermissionsError),+}diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rsindex 8325dca63e..730b8be64a 100644--- a/rust/cloud-storage/teams/src/domain/team_repo.rs+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs@@ -7,8 +7,8 @@ use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStruse crate::domain::model::{CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, PatchTeamRequest,ReinviteError, RemoveTeamInviteError, RemoveUserFromTeamError,- RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,- TeamMember, TeamRole, TeamWithMembers,+ RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team, TeamError,+ TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamUserTier, TeamWithMembers,};/// The TeamChannelsRepository defines a set of actions related to team channels@@ -47,6 +47,7 @@ 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.@@ -64,7 +65,7 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {&self,team_id: &uuid::Uuid,user_id: &MacroUserIdStr<'_>,- ) -> impl Future<Output = Result<(), RemoveUserFromTeamError>> + Send;+ ) -> impl Future<Output = Result<TeamUserTier, RemoveUserFromTeamError>> + Send;///Gets a team invite by idfn get_team_invite_by_id(@@ -111,6 +112,14 @@ 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(@@ -244,6 +253,13 @@ pub trait TeamService: Clone + Send + Sync + 'static {team_id: &uuid::Uuid,) -> impl Future<Output = Result<(), RevokePermissionsForTeamMembersError>> + Send;+ /// Restores permissions for all team members.+ /// This is used when a team subscription becomes active again.+ fn restore_permissions_for_team_members(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<(), RestorePermissionsForTeamMembersError>> + Send;+/// Gets a team by id with all its membersfn get_team(&self,diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rsindex 151b927a9e..1ee6199f4c 100644--- a/rust/cloud-storage/teams/src/domain/team_service.rs+++ b/rust/cloud-storage/teams/src/domain/team_service.rs@@ -1,7 +1,8 @@//! Contains the service logic for teams-use std::{collections::HashSet, str::FromStr, sync::Arc};+use std::{collections::HashSet, sync::Arc};+use anyhow::Context;use macro_user_id::{cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,};@@ -17,10 +18,11 @@ use notification::domain::{models::SendNotificationRequestBuilder, service::Notiuse crate::domain::{customer_repo::CustomerRepository,model::{- CreateSubscriptionArgs, CreateTeamError, CustomerError, DeleteTeamError,- InviteUsersToTeamError, JoinTeamError, PatchTeamRequest, ReinviteError,- RemoveTeamInviteError, RemoveUserFromTeamError, RevokePermissionsForTeamMembersError, Team,- TeamError, TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamWithMembers,+ CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, PatchTeamRequest,+ ReinviteError, RemoveTeamInviteError, RemoveUserFromTeamError,+ RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team,+ TeamError, TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamUserTier,+ TeamWithMembers,},team_repo::{TeamChannelsRepository, TeamRepository, TeamService},};@@ -100,7 +102,54 @@ whereURPS: 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,+ ) -> anyhow::Result<stripe::SubscriptionId> {+ let subscription_id = self+ .team_repository+ .get_team_subscription_id(team_id)+ .await?;++ // 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?;++ let customer_id = self+ .team_repository+ .get_stripe_customer_id(&team.team.owner_id)+ .await?+ .context("expected customer id")?;++ let customer_subscription_id = self+ .customer_repository+ .get_subscription_id_for_customer(&customer_id)+ .await?;++ // update the customers subscription to a team sub+ self.team_repository+ .update_team_subscription(team_id, &customer_subscription_id)+ .await?;++ // convert the customers subscription to a team subscription+ self.customer_repository+ .convert_subscription_to_team(&customer_subscription_id, team_id, &team.team.owner_id)+ .await?;++ Ok(customer_subscription_id)+ }+/// Sends an invite notification for a team invite+ #[tracing::instrument(skip(self), err)]async fn send_invite_notification(&self,team_id: &uuid::Uuid,@@ -146,14 +195,27 @@ whereURPS: UserRolesAndPermissionsService,NI: NotificationIngress,{+ #[tracing::instrument(skip(self), err)]async fn create_team(&self,user_id: &MacroUserIdStr<'_>,team_name: &str,) -> Result<Team, CreateTeamError> {- self.team_repository.create_team(user_id, team_name).await+ 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}+ #[tracing::instrument(skip(self), err)]async fn invite_users_to_team(&self,team_id: &uuid::Uuid,@@ -165,54 +227,6 @@ where.invite_users_to_team(team_id, invited_by, emails).await?;- if !invited.is_empty() {- let subscription_id = self- .team_repository- .get_team_subscription_id(team_id)- .await?;-- // Increase the quantity of the subscription- if let Some(subscription_id) = subscription_id {- let subscription_id = stripe::SubscriptionId::from_str(&subscription_id)- .map_err(|e| InviteUsersToTeamError::StorageLayerError(e.into()))?;-- // Increment the quantity of the subscription by the number of emails- self.customer_repository- .increase_subscription_quantity(&subscription_id, invited.len() as u64)- .await?;- } else {- // Create new subscription- let customer_id = self- .team_repository- .get_stripe_customer_id(invited_by)- .await?- .ok_or(InviteUsersToTeamError::CustomerError(- CustomerError::NoStripeCustomerId,- ))?;-- let subscription_id = self- .customer_repository- .create_subscription(CreateSubscriptionArgs {- customer_id,- quantity: invited.len() as u64,- metadata: Some(- vec![- ("team_id".to_string(), team_id.to_string()),- ("owner_id".to_string(), invited_by.as_ref().to_string()),- ]- .into_iter()- .collect(),- ),- })- .await?;-- // Update team with the new subscription id- self.team_repository- .update_team_subscription(team_id, &subscription_id)- .await?;- }- }-// Send notifications for new invitesif !invited.is_empty() {let team_name = self.team_repository.get_team_name(team_id).await.ok();@@ -239,49 +253,54 @@ whereOk(invited)}+ #[tracing::instrument(skip(self), err)]async fn remove_user_from_team(&self,team_id: &uuid::Uuid,user_id: &MacroUserIdStr<'_>,) -> Result<(), RemoveUserFromTeamError> {- let result = self+ let tier = self.team_repository.remove_user_from_team(team_id, user_id).await;// The user was part of the team and was removed- if result.is_ok() {+ if let Ok(tier) = tier {self.team_channels_repository.remove_team_member_from_channels(team_id, user_id).await?;- let subscription_id = self+ let subscription_id = self.get_team_subscription(team_id).await?;++ // Decrement the quantity of the subscription+ self.customer_repository+ .decrease_subscription_quantity(&subscription_id, tier)+ .await?;++ let remaining_tiers = self.team_repository- .get_team_subscription_id(team_id)+ .get_user_remaining_tiers(user_id, team_id).await?;- if let Some(subscription_id) = subscription_id {- // Decrement the quantity of the subscription- self.customer_repository- .decrease_subscription_quantity(&subscription_id, 1)- .await?;- } else {- return Err(RemoveUserFromTeamError::NoSubscription);+ 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)?;}}- if !self.team_repository.is_user_member_of_team(user_id).await? {- let roles = vec![RoleId::TeamSubscriber];- let roles = non_empty::NonEmpty::new(roles.as_slice()).unwrap();- self.user_roles_and_permissions_service- .dangerous_remove_roles_from_user(user_id, &roles)- .await- .map_err(RemoveUserFromTeamError::RemoveRolesFromUserError)?;- }-- result+ tier.map(|_| ())}+ #[tracing::instrument(skip(self), err)]async fn reject_invitation(&self,user_id: &MacroUserIdStr<'_>,@@ -300,23 +319,10 @@ where.delete_team_invite(&team_invite.team_id, team_invite_id).await?;- let subscription_id = self- .team_repository- .get_team_subscription_id(&team_invite.team_id)- .await?;-- if let Some(subscription_id) = subscription_id {- // Decrement the quantity of the subscription- self.customer_repository- .decrease_subscription_quantity(&subscription_id, 1)- .await?;- } else {- return Err(TeamError::NoSubscription.into());- }-Ok(())}+ #[tracing::instrument(skip(self), err)]async fn delete_team_invite(&self,team_id: &uuid::Uuid,@@ -326,23 +332,10 @@ where.delete_team_invite(team_id, team_invite_id).await?;- let subscription_id = self- .team_repository- .get_team_subscription_id(team_id)- .await?;-- if let Some(subscription_id) = subscription_id {- // Decrement the quantity of the subscription- self.customer_repository- .decrease_subscription_quantity(&subscription_id, 1)- .await?;- } else {- return Err(TeamError::NoSubscription.into());- }-Ok(())}+ #[tracing::instrument(skip(self), err)]async fn delete_team(&self, team_id: &uuid::Uuid) -> Result<(), DeleteTeamError> {let members = self.team_repository.get_all_team_members(team_id).await?;@@ -350,14 +343,8 @@ where.team_repository.get_team_subscription_id(team_id).await?;-if let Some(subscription_id) = subscription_id {// Cancel subscription- let subscription_id =- stripe::SubscriptionId::from_str(&subscription_id).map_err(|_| {- DeleteTeamError::StorageLayerError(anyhow::anyhow!("Invalid subscription id"))- })?;-self.customer_repository.cancel_subscription(&subscription_id).await@@ -390,6 +377,7 @@ whereOk(())}+ #[tracing::instrument(skip(self), err)]async fn join_team(&self,team_invite_id: &uuid::Uuid,@@ -401,8 +389,9 @@ where.await.map_err(JoinTeamError::TeamError)?;- // subscribe the user to professional features from the TeamSubscriber role- let roles = vec![RoleId::TeamSubscriber];+ // subscribe the user to professional features from the TeamSubscriber role and the role associated with their tier+ let roles = vec![RoleId::TeamSubscriber, RoleId::from(team_member.tier)];+let roles = non_empty::NonEmpty::new(roles.as_slice()).unwrap();self.user_roles_and_permissions_service@@ -414,9 +403,17 @@ where.add_team_member_to_channels(&team_member.team_id, user_id).await?;+ let subscription_id = self.get_team_subscription(&team_member.team_id).await?;++ // Increment the quantity of the subscription by the number of emails+ self.customer_repository+ .increase_subscription_quantity(&subscription_id, team_member.tier)+ .await?;+Ok(team_member)}+ #[tracing::instrument(skip(self), err)]async fn revoke_permissions_for_team_members(&self,team_id: &uuid::Uuid,@@ -427,47 +424,66 @@ wherereturn Ok(());}- let members: Vec<MacroUserIdStr<'_>> = members.into_iter().map(|m| m.user_id).collect();+ // 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 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)?;+ }+ }++ Ok(())+ }- // Ignore the current team- let ignore_team_ids = vec![*team_id];+ #[tracing::instrument(skip(self), err)]+ async fn restore_permissions_for_team_members(+ &self,+ team_id: &uuid::Uuid,+ ) -> Result<(), RestorePermissionsForTeamMembersError> {+ let members = self.team_repository.get_team_members(team_id).await?;- let members_of_team = self- .team_repository- .bulk_is_member_of_other_team(- non_empty::NonEmpty::new(ignore_team_ids.as_slice()).unwrap(),- non_empty::NonEmpty::new(members.as_slice()).unwrap(),- )- .await?;+ if members.is_empty() {+ return Ok(());+ }- let members_of_team: HashSet<&str> = members_of_team.iter().map(|m| m.as_ref()).collect();- // Get all members that are not in the other team- let members_to_revoke: Vec<_> = members- .into_iter()- .filter(|m| !members_of_team.contains(m.as_ref()))- .collect();+ for member in members {+ let roles = vec![RoleId::TeamSubscriber, RoleId::from(member.tier)];+ let roles = non_empty::NonEmpty::new(roles.as_slice()).unwrap();- // Revoke permissions for all members- let roles = vec![RoleId::TeamSubscriber];- let roles = non_empty::NonEmpty::new(roles.as_slice()).unwrap();- for member in members_to_revoke {self.user_roles_and_permissions_service- .dangerous_remove_roles_from_user(&member, &roles)+ .dangerous_upsert_roles_for_user(&member.user_id, roles).await- .map_err(RevokePermissionsForTeamMembersError::RemoveRolesFromUserError)?;+ .map_err(RestorePermissionsForTeamMembersError::AddRolesToUserError)?;}Ok(())}+ #[tracing::instrument(skip(self), err)]async fn get_team(&self, team_id: &uuid::Uuid) -> Result<TeamWithMembers, TeamError> {self.team_repository.get_team_by_id(team_id).await}+ #[tracing::instrument(skip(self), err)]async fn get_user_teams(&self, user_id: &MacroUserIdStr<'_>) -> Result<Vec<Team>, TeamError> {self.team_repository.get_user_teams(user_id).await}+ #[tracing::instrument(skip(self), err)]async fn get_user_invites(&self,user_id: &MacroUserIdStr<'_>,@@ -475,6 +491,7 @@ whereself.team_repository.get_user_team_invites(user_id).await}+ #[tracing::instrument(skip(self), err)]async fn get_team_invites(&self,team_id: &uuid::Uuid,@@ -482,6 +499,7 @@ whereself.team_repository.get_team_invites(team_id).await}+ #[tracing::instrument(skip(self), err)]async fn patch_team(&self,team_id: &uuid::Uuid,@@ -490,6 +508,7 @@ whereself.team_repository.patch_team(team_id, req).await}+ #[tracing::instrument(skip(self), err)]async fn reinvite_to_team(&self,team_invite_id: &uuid::Uuid,@@ -537,6 +556,7 @@ whereOk(invite)}+ #[tracing::instrument(skip(self), err)]async fn get_team_role(&self,team_id: &uuid::Uuid,diff --git a/rust/cloud-storage/teams/src/outbound/customer_repo.rs b/rust/cloud-storage/teams/src/outbound/customer_repo.rsindex 75d9e9fdbd..1b4cb85dec 100644--- a/rust/cloud-storage/teams/src/outbound/customer_repo.rs+++ b/rust/cloud-storage/teams/src/outbound/customer_repo.rs@@ -1,34 +1,57 @@//! Implementation for CustomerRepository using Stripe.-use std::sync::Arc;+use std::{collections::HashMap, sync::Arc};use stripe::{CreateSubscription, CreateSubscriptionItems, UpdateSubscription};use crate::domain::{customer_repo::CustomerRepository,- model::{CreateSubscriptionArgs, CustomerError},+ model::{CreateSubscriptionArgs, CustomerError, TeamUserTier},};+/// The stripe price ids for all tiers+#[derive(Clone)]+pub struct StripePriceIds {+ /// haiku tier price id+ pub haiku: String,+ /// sonnet tier price id+ pub sonnet: String,+ /// opus tier price id+ 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 {/// The underlying stripe::Client connected to stripe.client: Arc<stripe::Client>,- /// The price id for the professional subscription- stripe_price_id: String,+ /// The stripe price ids+ stripe_price_ids: StripePriceIds,}impl CustomerRepositoryImpl {/// Creates a new instance of CustomerRepositoryImpl- pub fn new(stripe_client: stripe::Client, stripe_price_id: &str) -> Self {+ pub fn new(stripe_client: stripe::Client, stripe_price_ids: StripePriceIds) -> Self {Self {client: Arc::new(stripe_client),- stripe_price_id: stripe_price_id.to_string(),+ stripe_price_ids,}}}impl CustomerRepository for CustomerRepositoryImpl {+ #[tracing::instrument(skip(self), err)]async fn create_subscription(&self,args: CreateSubscriptionArgs,@@ -36,7 +59,7 @@ impl CustomerRepository for CustomerRepositoryImpl {// Create the subscriptionlet mut params = CreateSubscription::new(args.customer_id);params.items = Some(vec![CreateSubscriptionItems {- price: Some(self.stripe_price_id.clone()),+ price: Some(self.stripe_price_ids.haiku.clone()),quantity: Some(args.quantity),..Default::default()}]);@@ -50,10 +73,11 @@ impl CustomerRepository for CustomerRepositoryImpl {Ok(subscription.id)}+ #[tracing::instrument(skip(self), err)]async fn increase_subscription_quantity(&self,subscription_id: &stripe::SubscriptionId,- increase_amount: u64,+ team_user_tier: TeamUserTier,) -> Result<(), CustomerError> {// Get existing subscription quantitylet subscription = stripe::Subscription::retrieve(&self.client, subscription_id, &[])@@ -67,21 +91,43 @@ impl CustomerRepository for CustomerRepositoryImpl {}}- // Get the first subscription item (assuming single item subscription)- let item = subscription.items.data.first().ok_or_else(|| {- CustomerError::StorageLayerError(anyhow::anyhow!("No subscription items found"))- })?;+ let tier_price_id = self.stripe_price_ids.price_id_for_tier(&team_user_tier);- // There should always be a quantity on the subscription item- let current_quantity = item.quantity.unwrap_or(1);- let new_quantity = current_quantity + increase_amount;+ // 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)+ });- // Update the subscription item quantity- let update_params = UpdateSubscription { items: Some(vec![stripe::UpdateSubscriptionItems {- id: Some(item.id.to_string()),- quantity: Some(new_quantity),- ..Default::default()- }]), proration_behavior: Some(stripe::generated::billing::subscription::SubscriptionProrationBehavior::CreateProrations), ..Default::default()};+ 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@@ -90,45 +136,69 @@ impl CustomerRepository for CustomerRepositoryImpl {Ok(())}+ #[tracing::instrument(skip(self), err)]async fn decrease_subscription_quantity(&self,subscription_id: &stripe::SubscriptionId,- decrease_amount: u64,+ team_user_tier: TeamUserTier,) -> Result<(), CustomerError> {- // Get existing subscriptionlet subscription = stripe::Subscription::retrieve(&self.client, subscription_id, &[]).await.map_err(|e| CustomerError::StorageLayerError(e.into()))?;- // Check if subscription is active- match subscription.status {- stripe::SubscriptionStatus::Active => (),- _ => {- return Err(CustomerError::SubscriptionNotActive);- }+ if subscription.status != stripe::SubscriptionStatus::Active {+ return Err(CustomerError::SubscriptionNotActive);}- // Get the first subscription item (assuming single item subscription)- let item = subscription.items.data.first().ok_or_else(|| {- CustomerError::StorageLayerError(anyhow::anyhow!("No subscription items found"))- })?;+ 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);- // Check if decrease amount would result in quantity < 1- if decrease_amount >= current_quantity {- // Cancel the subscription instead+ // 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 new_quantity = current_quantity - decrease_amount;+ 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()+ }]+ };- // Update the subscription item quantity- let update_params = UpdateSubscription { items: Some(vec![stripe::UpdateSubscriptionItems {- id: Some(item.id.to_string()),- quantity: Some(new_quantity),- ..Default::default()- }]), proration_behavior: Some(stripe::generated::billing::subscription::SubscriptionProrationBehavior::CreateProrations), ..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@@ -137,6 +207,7 @@ impl CustomerRepository for CustomerRepositoryImpl {Ok(())}+ #[tracing::instrument(skip(self), err)]async fn cancel_subscription(&self,subscription_id: &stripe::SubscriptionId,@@ -149,4 +220,150 @@ impl CustomerRepository for CustomerRepositoryImpl {Ok(())}++ #[tracing::instrument(skip(self), err)]+ async fn convert_subscription_to_team(+ &self,+ subscription_id: &stripe::SubscriptionId,+ team_id: &uuid::Uuid,+ team_owner_id: ¯o_user_id::user_id::MacroUserIdStr<'_>,+ ) -> Result<(), CustomerError> {+ let mut metadata = HashMap::new();+ metadata.insert("team_id".to_string(), team_id.to_string());+ metadata.insert("owner_id".to_string(), team_owner_id.to_string());++ let mut params = UpdateSubscription::new();+ params.metadata = Some(metadata);++ stripe::Subscription::update(&self.client, subscription_id, params)+ .await+ .map_err(|e| CustomerError::StorageLayerError(e.into()))?;++ Ok(())+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_subscription_id_for_customer(+ &self,+ customer_id: &stripe::CustomerId,+ ) -> Result<stripe::SubscriptionId, CustomerError> {+ let mut params = stripe::ListSubscriptions::new();+ params.customer = Some(customer_id.clone());+ params.status = Some(stripe::SubscriptionStatusFilter::Active);+ params.limit = Some(1);++ let subscriptions = stripe::Subscription::list(&self.client, ¶ms)+ .await+ .map_err(|e| CustomerError::StorageLayerError(e.into()))?;++ subscriptions+ .data+ .into_iter()+ .next()+ .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.rsindex 54c19e0af6..b9eb3f23d2 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::{CreateTeamError, InviteUsersToTeamError, PatchTeamRequest, RemoveTeamInviteError,RemoveUserFromTeamError, Team, TeamError, TeamInvite, TeamInviteDetails, TeamMember,- TeamRole, TeamWithMembers,+ TeamRole, TeamUserTier, TeamWithMembers,},team_repo::TeamRepository,};@@ -11,7 +11,14 @@ use macro_user_id::{cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,};use sqlx::PgPool;-use std::str::FromStr;+use std::{collections::HashSet, str::FromStr};++/// utility fn for queries to create a sqlx err+fn type_err<E: std::fmt::Display>(e: E) -> sqlx::Error {+ sqlx::Error::TypeNotFound {+ type_name: e.to_string(),+ }+}#[cfg(test)]mod test;@@ -31,7 +38,30 @@ impl TeamRepositoryImpl {}impl TeamRepositoryImpl {+ /// Bumps the teams seat count by the quantity number (positive or negative)+ #[tracing::instrument(skip(transaction), err)]+ async fn bump_seat_count<'t>(+ transaction: &mut sqlx::Transaction<'t, sqlx::Postgres>,+ team_id: &uuid::Uuid,+ quantity: i32,+ ) -> Result<(), anyhow::Error> {+ sqlx::query!(+ r#"+ UPDATE team+ SET seat_count = seat_count + $2+ WHERE id = $1+ "#,+ team_id,+ quantity+ )+ .execute(transaction.as_mut())+ .await?;++ Ok(())+ }+/// Gets the owner of a team+ #[tracing::instrument(skip(self), err)]async fn get_team_owner(&self,team_id: &uuid::Uuid,@@ -51,10 +81,12 @@ impl TeamRepositoryImpl {Ok(MacroUserIdStr::parse_from_str(owner_id.as_str()).map(|id| id.into_owned())?)}+ #[tracing::instrument(skip(self), err)]async fn create_team_inner(&self,user_id: &MacroUserIdStr<'_>,team_name: &str,+ team_user_tier: &TeamUserTier,) -> Result<Team, sqlx::Error> {let mut transaction = self.pool.begin().await?;@@ -70,17 +102,26 @@ impl TeamRepositoryImpl {team_name,user_id.as_ref(),)- .map(|row| Team::new(row.id, row.name, row.owner_id))+ .try_map(|row| {+ Ok(Team {+ id: row.id,+ name: row.name,+ owner_id: MacroUserIdStr::parse_from_str(&row.owner_id)+ .map_err(type_err)?+ .into_owned(),+ })+ }).fetch_one(&mut *transaction).await?;sqlx::query!(r#"- INSERT INTO team_user (team_id, user_id, team_role)- VALUES ($1, $2, 'owner')+ INSERT INTO team_user (team_id, user_id, team_role, tier)+ VALUES ($1, $2, 'owner', $3)"#,&team.id,user_id.as_ref(),+ team_user_tier as _,).execute(&mut *transaction).await?;@@ -125,6 +166,7 @@ impl From<sqlx::Error> for RemoveTeamInviteError {}impl TeamRepository for TeamRepositoryImpl {+ #[tracing::instrument(skip(self), err)]async fn get_stripe_customer_id(&self,user_id: &MacroUserIdStr<'_>,@@ -154,6 +196,7 @@ impl TeamRepository for TeamRepositoryImpl {}}+ #[tracing::instrument(skip(self), err)]async fn get_team_subscription_id(&self,team_id: &uuid::Uuid,@@ -182,20 +225,23 @@ impl TeamRepository for TeamRepositoryImpl {Ok(team_subscription_id)}+ #[tracing::instrument(skip(self), err)]async fn create_team(&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)+ self.create_team_inner(user_id, team_name, team_user_tier).await.map_err(|e| e.into())}+ #[tracing::instrument(skip(self), err)]async fn invite_users_to_team(&self,team_id: &uuid::Uuid,@@ -268,29 +314,17 @@ impl TeamRepository for TeamRepositoryImpl {}).collect();- // Update the team seat count- sqlx::query!(- r#"- UPDATE team- SET seat_count = seat_count + $2- WHERE id = $1- "#,- team_id,- created_emails.len() as i64,- )- .execute(&mut *transaction)- .await?;-transaction.commit().await?;Ok(created_emails)}+ #[tracing::instrument(skip(self), err)]async fn remove_user_from_team(&self,team_id: &uuid::Uuid,user_id: &MacroUserIdStr<'_>,- ) -> Result<(), RemoveUserFromTeamError> {+ ) -> Result<TeamUserTier, RemoveUserFromTeamError> {let owner_id = self.get_team_owner(team_id).await?;if user_id.as_ref().eq(owner_id.as_ref()) {@@ -299,38 +333,30 @@ impl TeamRepository for TeamRepositoryImpl {let mut transaction = self.pool.begin().await?;- let removed = sqlx::query!(+ let row = sqlx::query!(r#"DELETE FROM team_userWHERE team_id = $1 AND user_id = $2- "#,+ RETURNING tier AS "tier!: TeamUserTier"+ "#,team_id,user_id.as_ref(),)- .execute(&mut *transaction)+ .fetch_optional(&mut *transaction).await?;- if removed.rows_affected() == 0 {- return Err(RemoveUserFromTeamError::UserNotInTeam);- }+ let tier = row+ .map(|r| r.tier)+ .ok_or(RemoveUserFromTeamError::UserNotInTeam)?;- // Update the team seat count- sqlx::query!(- r#"- UPDATE team- SET seat_count = seat_count - 1- WHERE id = $1- "#,- team_id,- )- .execute(&mut *transaction)- .await?;+ TeamRepositoryImpl::bump_seat_count(&mut transaction, team_id, -1).await?;transaction.commit().await?;- Ok(())+ Ok(tier)}+ #[tracing::instrument(skip(self), err)]async fn get_team_invite_by_id(&self,team_invite_id: &uuid::Uuid,@@ -364,6 +390,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(team_invite.to_owned())}+ #[tracing::instrument(skip(self), err)]async fn delete_team_invite(&self,team_id: &uuid::Uuid,@@ -373,9 +400,10 @@ impl TeamRepository for TeamRepositoryImpl {let result = sqlx::query!(r#"DELETE FROM team_invite- WHERE id = $1+ WHERE id = $1 AND team_id = $2"#,team_invite_id,+ team_id,).execute(&mut *transaction).await?;@@ -384,23 +412,12 @@ impl TeamRepository for TeamRepositoryImpl {return Err(RemoveTeamInviteError::TeamInviteDoesNotExist);}- // Update the team seat count- sqlx::query!(- r#"- UPDATE team- SET seat_count = seat_count - 1- WHERE id = $1- "#,- team_id,- )- .execute(&mut *transaction)- .await?;-transaction.commit().await?;Ok(())}+ #[tracing::instrument(skip(self), err)]async fn update_team_subscription(&self,team_id: &uuid::Uuid,@@ -421,6 +438,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(())}+ #[tracing::instrument(skip(self), err)]async fn delete_team(&self, team_id: &uuid::Uuid) -> Result<(), TeamError> {sqlx::query!(r#"@@ -435,6 +453,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(())}+ #[tracing::instrument(skip(self), err)]async fn get_all_team_members(&self,team_id: &uuid::Uuid,@@ -442,7 +461,8 @@ impl TeamRepository for TeamRepositoryImpl {let members = sqlx::query!(r#"SELECT user_id,- team_role as "team_role!: TeamRole"+ team_role as "team_role!: TeamRole",+ tier as "tier!: TeamUserTier"FROM team_userWHERE team_id = $1"#,@@ -462,6 +482,7 @@ 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"))@@ -477,6 +498,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(members)}+ #[tracing::instrument(skip(self), err)]async fn accept_team_invite(&self,team_invite_id: &uuid::Uuid,@@ -489,7 +511,7 @@ impl TeamRepository for TeamRepositoryImpl {// Get user role from team invitelet invite = sqlx::query!(r#"- SELECT team_role as "team_role!: TeamRole", team_id+ SELECT team_role as "team_role!: TeamRole", team_id, tier as "tier!: TeamUserTier"FROM team_inviteWHERE id = $1 AND email = $2"#,@@ -502,17 +524,21 @@ impl TeamRepository for TeamRepositoryImpl {// Assign user to team_userlet team_member = sqlx::query!(r#"- INSERT INTO team_user (team_id, user_id, team_role)- VALUES ($1, $2, $3)- RETURNING user_id, team_role as "role!: TeamRole"+ INSERT INTO team_user (team_id, user_id, team_role, tier)+ VALUES ($1, $2, $3, $4)+ RETURNING user_id, team_role as "role!: TeamRole", tier as "tier!: TeamUserTier", team_id"#,&invite.team_id,user_id.as_ref(),invite.team_role as _,+ invite.tier as _,).fetch_one(&mut *transaction).await?;+ // bump seat count+ TeamRepositoryImpl::bump_seat_count(&mut transaction, &team_member.team_id, 1).await?;+// Remove team invitesqlx::query!(r#"@@ -530,11 +556,13 @@ impl TeamRepository for TeamRepositoryImpl {user_id: user_id.clone().into_owned(),role: team_member.role,team_id: invite.team_id,+ tier: team_member.tier,};Ok(team_member)}+ #[tracing::instrument(skip(self), err)]async fn is_user_member_of_team(&self,user_id: &MacroUserIdStr<'_>,@@ -542,7 +570,7 @@ impl TeamRepository for TeamRepositoryImpl {let team_member: Option<()> = sqlx::query!(r#"SELECT team_id FROM team_user- WHERE user_id = $1 AND team_role NOT IN ('owner')+ WHERE user_id = $1"#,user_id.as_ref(),)@@ -553,6 +581,28 @@ 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,team_id: &uuid::Uuid,@@ -560,7 +610,8 @@ impl TeamRepository for TeamRepositoryImpl {let members = sqlx::query!(r#"SELECT user_id,- team_role as "team_role!: TeamRole"+ team_role as "team_role!: TeamRole",+ tier as "tier!: TeamUserTier"FROM team_userWHERE team_id = $1 AND team_role NOT IN ('owner')"#,@@ -580,6 +631,7 @@ 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"))@@ -595,6 +647,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(members)}+ #[tracing::instrument(skip(self), err)]async fn bulk_is_member_of_other_team(&self,ignore_team_ids: non_empty::NonEmpty<&[uuid::Uuid]>,@@ -633,6 +686,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(members)}+ #[tracing::instrument(skip(self), err)]async fn get_team_by_id(&self, team_id: &uuid::Uuid) -> Result<TeamWithMembers, TeamError> {let team = sqlx::query!(r#"@@ -642,14 +696,23 @@ impl TeamRepository for TeamRepositoryImpl {"#,team_id,)- .map(|row| Team::new(row.id, row.name, row.owner_id))+ .try_map(|row| {+ Ok(Team {+ id: row.id,+ name: row.name,+ owner_id: MacroUserIdStr::parse_from_str(&row.owner_id)+ .map_err(type_err)?+ .into_owned(),+ })+ }).fetch_one(&self.pool).await?;let members = sqlx::query!(r#"SELECT user_id,- team_role as "team_role!: TeamRole"+ team_role as "team_role!: TeamRole",+ tier as "tier!: TeamUserTier"FROM team_userWHERE team_id = $1"#,@@ -666,6 +729,7 @@ impl TeamRepository for TeamRepositoryImpl {user_id: id.into_owned(),role: row.team_role,team_id: *team_id,+ tier: row.tier,}).ok()})@@ -674,6 +738,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(TeamWithMembers { team, members })}+ #[tracing::instrument(skip(self), err)]async fn get_user_teams(&self, user_id: &MacroUserIdStr<'_>) -> Result<Vec<Team>, TeamError> {let teams = sqlx::query!(r#"@@ -684,13 +749,22 @@ impl TeamRepository for TeamRepositoryImpl {"#,user_id.as_ref(),)- .map(|row| Team::new(row.id, row.name, row.owner_id))+ .try_map(|row| {+ Ok(Team {+ id: row.id,+ name: row.name,+ owner_id: MacroUserIdStr::parse_from_str(&row.owner_id)+ .map_err(type_err)?+ .into_owned(),+ })+ }).fetch_all(&self.pool).await?;Ok(teams)}+ #[tracing::instrument(skip(self), err)]async fn get_user_team_invites(&self,user_id: &MacroUserIdStr<'_>,@@ -727,6 +801,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(invites)}+ #[tracing::instrument(skip(self), err)]async fn get_team_invites(&self,team_id: &uuid::Uuid,@@ -761,6 +836,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(invites)}+ #[tracing::instrument(skip(self), err)]async fn get_team_name(&self, team_id: &uuid::Uuid) -> Result<String, TeamError> {let name = sqlx::query!(r#"@@ -777,6 +853,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(name)}+ #[tracing::instrument(skip(self), err)]async fn patch_team(&self,team_id: &uuid::Uuid,@@ -799,6 +876,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(())}+ #[tracing::instrument(skip(self), err)]async fn get_team_invite_details_by_id(&self,invite_id: &uuid::Uuid,@@ -837,6 +915,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(invite)}+ #[tracing::instrument(skip(self), err)]async fn update_team_invite_last_sent_at(&self,invite_id: &uuid::Uuid,@@ -855,6 +934,7 @@ impl TeamRepository for TeamRepositoryImpl {Ok(())}+ #[tracing::instrument(skip(self), err)]async fn get_team_role(&self,team_id: &uuid::Uuid,diff --git a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs b/rust/cloud-storage/teams/src/outbound/team_repo/test.rsindex c2ae1200fc..3d4ec88c07 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs@@ -76,15 +76,17 @@ 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").await?;+ 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, "macro|[email protected]");+ assert_eq!(result.owner_id.0.as_ref(), "macro|[email protected]");// Create team with too large a namelet err = team_repo- .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000")+ .create_team(&user_id, "12345678901234567890123456789012345678901234567890123456789000000000000000000000000000000000000000000000", &TeamUserTier::Sonnet).await.err().unwrap();@@ -341,6 +343,41 @@ 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 team_member = team_repo+ .accept_team_invite(&team_invite_id, &user_id)+ .await?;++ 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"))@@ -348,18 +385,21 @@ async fn test_accept_team_invite(pool: Pool<Postgres>) -> anyhow::Result<()> {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 team3let 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);- assert!(!is_member);-+ // [email protected] is a member of team1 and team2let 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 not in any team+ 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);+Ok(())}@@ -393,42 +433,165 @@ async fn test_get_team_members(pool: Pool<Postgres>) -> anyhow::Result<()> {migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("teams")))]-async fn test_bulk_is_member_of_other_team(pool: Pool<Postgres>) -> anyhow::Result<()> {+async fn test_bump_seat_count_positive(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ let mut transaction = pool.begin().await?;+ TeamRepositoryImpl::bump_seat_count(&mut transaction, &team_id, 2).await?;+ transaction.commit().await?;++ let row = sqlx::query!(r#"SELECT seat_count FROM team WHERE id = $1"#, &team_id,)+ .fetch_one(&pool)+ .await?;++ assert_eq!(row.seat_count, 5); // 3 + 2++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_bump_seat_count_negative(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ let mut transaction = pool.begin().await?;+ TeamRepositoryImpl::bump_seat_count(&mut transaction, &team_id, -1).await?;+ transaction.commit().await?;++ let row = sqlx::query!(r#"SELECT seat_count FROM team WHERE id = $1"#, &team_id,)+ .fetch_one(&pool)+ .await?;++ assert_eq!(row.seat_count, 2); // 3 - 1++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams_remaining_tiers"))+)]+async fn test_get_user_remaining_tiers_multi_team_user(pool: Pool<Postgres>) -> anyhow::Result<()> {let team_repo = TeamRepositoryImpl::new(pool);- let ignore_team_ids = vec![macro_uuid::string_to_uuid(- "11111111-1111-1111-1111-111111111111",- )?];+ 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 users = vec![- MacroUserIdStr::parse_from_str("macro|[email protected]")?,- MacroUserIdStr::parse_from_str("macro|[email protected]")?,- ];+ // 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));- let ignore_team_ids = non_empty::NonEmpty::new(ignore_team_ids.as_slice())?;- let users = non_empty::NonEmpty::new(users.as_slice())?;+ // 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));- let result = team_repo- .bulk_is_member_of_other_team(ignore_team_ids, users)+ // 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));- assert_eq!(result.len(), 1);- assert_eq!(result[0].as_ref(), "macro|[email protected]");+ Ok(())+}- let ignore_team_ids = vec![macro_uuid::string_to_uuid(- "33333333-3333-3333-3333-333333333333",- )?];+#[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 users = vec![MacroUserIdStr::parse_from_str("macro|[email protected]")?];+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let team_a = macro_uuid::string_to_uuid("aaaa1111-1111-1111-1111-111111111111")?;- let ignore_team_ids = non_empty::NonEmpty::new(ignore_team_ids.as_slice())?;- let users = non_empty::NonEmpty::new(users.as_slice())?;+ // [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());- let result = team_repo- .bulk_is_member_of_other_team(ignore_team_ids, users)+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams_remaining_tiers"))+)]+async fn test_get_user_remaining_tiers_user_not_in_any_team(+ 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")?;++ // User not in any team should return empty+ let tiers = team_repo+ .get_user_remaining_tiers(&user_id, &team_a).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")?;- assert!(result.is_empty());+ let tiers = team_repo+ .get_user_remaining_tiers(&user_id, &team_a)+ .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 user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let fake_team = macro_uuid::string_to_uuid("deadbeef-dead-beef-dead-beefdeadbeef")?;++ // 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);Ok(())}