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(team): setup team plan and updating team plan (#3295)
Will Hutchinsonfb9a24c79f73
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.tsindex 36c00de24f..3c37d1c150 100644--- a/js/app/packages/service-clients/service-auth/generated/client.ts+++ b/js/app/packages/service-clients/service-auth/generated/client.ts@@ -30,6 +30,7 @@ import type {PasswordlessRequest,PasswordRequest,PatchSubscriptionTierRequest,+ PatchTeamPlanRequest,PatchTeamRequest,PatchUserGroupRequest,PatchUserOnboardingRequest,@@ -2250,6 +2251,75 @@ export const rejectInvitation = async (} as rejectInvitationResponse;};+/**+ * @summary Updates a team plan.+ */+export type patchTeamPlanResponse200 = {+ data: void;+ status: 200;+};++export type patchTeamPlanResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type patchTeamPlanResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type patchTeamPlanResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type patchTeamPlanResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type patchTeamPlanResponseSuccess = patchTeamPlanResponse200 & {+ headers: Headers;+};+export type patchTeamPlanResponseError = (+ | patchTeamPlanResponse400+ | patchTeamPlanResponse401+ | patchTeamPlanResponse404+ | patchTeamPlanResponse500+) & {+ headers: Headers;+};++export type patchTeamPlanResponse =+ | patchTeamPlanResponseSuccess+ | patchTeamPlanResponseError;++export const getPatchTeamPlanUrl = () => {+ return `/team/plan`;+};++export const patchTeamPlan = async (+ patchTeamPlanRequest: PatchTeamPlanRequest,+ options?: RequestInit+): Promise<patchTeamPlanResponse> => {+ const res = await fetch(getPatchTeamPlanUrl(), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchTeamPlanRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: patchTeamPlanResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as patchTeamPlanResponse;+};+/*** @summary Removes a user from a team.*/diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.tsindex 89c9a2428a..28619a6fff 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts@@ -41,6 +41,7 @@ export * from './passwordlessRequest';export * from './passwordlessRequestReferralCode';export * from './passwordRequest';export * from './patchSubscriptionTierRequest';+export * from './patchTeamPlanRequest';export * from './patchTeamRequest';export * from './patchTeamRequestName';export * from './patchTeamRequestUserRoleUpdates';@@ -69,6 +70,7 @@ export * from './team';export * from './teamInviteDetails';export * from './teamInvitesResponse';export * from './teamMember';+export * from './teamPlan';export * from './teamRole';export * from './teamWithMembers';export * from './userLinkResponse';diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamPlanRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamPlanRequest.tsnew file mode 100644index 0000000000..52bdf1f609--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/patchTeamPlanRequest.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { TeamPlan } from './teamPlan';++/**+ * Request to update the team plan+ */+export interface PatchTeamPlanRequest {+ /** The new team plan */+ team_plan: TeamPlan;+}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/teamPlan.ts b/js/app/packages/service-clients/service-auth/generated/schemas/teamPlan.tsnew file mode 100644index 0000000000..65ce02d5ec--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/teamPlan.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Team plans+ */+export type TeamPlan = (typeof TeamPlan)[keyof typeof TeamPlan];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const TeamPlan = {+ idea: 'idea',+ pre_seed: 'pre_seed',+ seed: 'seed',+ series_a: 'series_a',+ growth: 'growth',+} as const;diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex c8b9b5eeb5..8ad68b3546 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -1884,6 +1884,68 @@}}},+ "/team/plan": {+ "patch": {+ "tags": ["teams::inbound::axum_router::patch_team_plan"],+ "summary": "Updates a team plan.",+ "operationId": "patch_team_plan",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PatchTeamPlanRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": ""+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/team/remove/{remove_user_id}": {"delete": {"tags": ["teams::inbound::axum_router::remove_user_from_team"],@@ -3393,6 +3455,17 @@}}},+ "PatchTeamPlanRequest": {+ "type": "object",+ "description": "Request to update the team plan",+ "required": ["team_plan"],+ "properties": {+ "team_plan": {+ "$ref": "#/components/schemas/TeamPlan",+ "description": "The new team plan"+ }+ }+ },"PatchTeamRequest": {"type": "object","description": "Request to update a team",@@ -3691,6 +3764,11 @@}}},+ "TeamPlan": {+ "type": "string",+ "description": "Team plans",+ "enum": ["idea", "pre_seed", "seed", "series_a", "growth"]+ },"TeamRole": {"type": "string","description": "Ordered from least to most access top -> bottom",diff --git a/rust/cloud-storage/.sqlx/query-0b00cee5a9723451b253275a51d86bffbd01384921dd9c149aebcf6e1fd4f5c2.json b/rust/cloud-storage/.sqlx/query-6a4e10be5bba1043622c0cac69f3f74891866fb4828bf00db7ce0f763ff55da4.jsonsimilarity index 67%rename from rust/cloud-storage/.sqlx/query-0b00cee5a9723451b253275a51d86bffbd01384921dd9c149aebcf6e1fd4f5c2.jsonrename to rust/cloud-storage/.sqlx/query-6a4e10be5bba1043622c0cac69f3f74891866fb4828bf00db7ce0f763ff55da4.jsonindex 957f493eb5..0469ed3ec7 100644--- a/rust/cloud-storage/.sqlx/query-0b00cee5a9723451b253275a51d86bffbd01384921dd9c149aebcf6e1fd4f5c2.json+++ b/rust/cloud-storage/.sqlx/query-6a4e10be5bba1043622c0cac69f3f74891866fb4828bf00db7ce0f763ff55da4.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO team (id, name, owner_id)\n VALUES ($1, $2, $3)\n RETURNING id, name, owner_id\n ",+ "query": "\n INSERT INTO team (id, name, owner_id, seat_count)\n VALUES ($1, $2, $3, 1)\n RETURNING id, name, owner_id\n ","describe": {"columns": [{@@ -32,5 +32,5 @@false]},- "hash": "0b00cee5a9723451b253275a51d86bffbd01384921dd9c149aebcf6e1fd4f5c2"+ "hash": "6a4e10be5bba1043622c0cac69f3f74891866fb4828bf00db7ce0f763ff55da4"}diff --git a/rust/cloud-storage/.sqlx/query-7b34f011e0ff7320e6a43825cace039b37662cf51a607ad905f758c508aa5049.json b/rust/cloud-storage/.sqlx/query-7b34f011e0ff7320e6a43825cace039b37662cf51a607ad905f758c508aa5049.jsonnew file mode 100644index 0000000000..a26e1d5521--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-7b34f011e0ff7320e6a43825cace039b37662cf51a607ad905f758c508aa5049.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT seat_count\n FROM team\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "seat_count",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "7b34f011e0ff7320e6a43825cace039b37662cf51a607ad905f758c508aa5049"+}diff --git a/rust/cloud-storage/.sqlx/query-c396a4e1c32ab75bdb9a1bb4b3bb0f550620554bab6862d4ec9731236c227cfc.json b/rust/cloud-storage/.sqlx/query-c396a4e1c32ab75bdb9a1bb4b3bb0f550620554bab6862d4ec9731236c227cfc.jsonnew file mode 100644index 0000000000..e61663ad16--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c396a4e1c32ab75bdb9a1bb4b3bb0f550620554bab6862d4ec9731236c227cfc.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT plan as \"plan?: TeamPlan\"\n FROM team\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "plan?: TeamPlan",+ "type_info": {+ "Custom": {+ "name": "team_plan",+ "kind": {+ "Enum": [+ "idea",+ "pre_seed",+ "seed",+ "series_a",+ "growth"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "c396a4e1c32ab75bdb9a1bb4b3bb0f550620554bab6862d4ec9731236c227cfc"+}diff --git a/rust/cloud-storage/.sqlx/query-c5e833a5efdd06f446538cca125c29318b92959b2ddab117bfd98273a45d1838.json b/rust/cloud-storage/.sqlx/query-c5e833a5efdd06f446538cca125c29318b92959b2ddab117bfd98273a45d1838.jsonnew file mode 100644index 0000000000..2c03184e20--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c5e833a5efdd06f446538cca125c29318b92959b2ddab117bfd98273a45d1838.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE team\n SET plan = $2\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ {+ "Custom": {+ "name": "team_plan",+ "kind": {+ "Enum": [+ "idea",+ "pre_seed",+ "seed",+ "series_a",+ "growth"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "c5e833a5efdd06f446538cca125c29318b92959b2ddab117bfd98273a45d1838"+}diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex cf7492b4fa..9b8578aded 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -29,7 +29,7 @@ use roles_and_permissions::{};use sqlx::PgPool;-use crate::config::StripePriceIds;+use crate::config::LegacyStripePriceIds;pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;@@ -80,7 +80,7 @@ pub(crate) struct ApiContext {pub referral_service: Arc<ReferralServiceType>,pub rate_limit_service: RateLimiter,/// The stripe price ids- pub stripe_price_ids: StripePriceIds,+ pub legacy_stripe_price_ids: LegacyStripePriceIds,}env_var! {diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rsindex a7b0b96544..e41ef6d674 100644--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs@@ -1,7 +1,7 @@use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};use teams::domain::model::{- PatchTeamRequest, PatchTeamUserRole, Team, TeamInviteDetails, TeamMember, TeamRole,- TeamWithMembers,+ PatchTeamPlanRequest, PatchTeamRequest, PatchTeamUserRole, Team, TeamInviteDetails, TeamMember,+ TeamPlan, TeamRole, TeamWithMembers,};use teams::inbound::axum_router::get_team_invites::TeamInvitesResponse as TeamTeamInvitesResponse;use teams::inbound::axum_router::get_user_invites::TeamInvitesResponse as UserTeamInvitesResponse;@@ -120,6 +120,7 @@ use model::user::{teams::inbound::axum_router::invite_to_team::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::get_team_invites::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::patch_team::handler::<crate::api::context::TeamsServiceType>,+ teams::inbound::axum_router::patch_team_plan::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::reject_invitation::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::get_user_invites::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::get_user_teams::handler::<crate::api::context::TeamsServiceType>,@@ -183,11 +184,13 @@ use model::user::{TeamRole,TeamMember,Team,+ TeamPlan,TeamWithMembers,TeamInviteDetails,CreateTeamRequest,InviteToTeamRequest,PatchTeamRequest,+ PatchTeamPlanRequest,PatchTeamUserRole,TeamTeamInvitesResponse,UserTeamInvitesResponse,diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rsindex 03515ce965..2365787afd 100644--- a/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs@@ -130,9 +130,9 @@ pub async fn create_checkout_session(});let price_id = match req.tier {- StripeProductTier::Haiku => ctx.stripe_price_ids.stripe_price_id_haiku.as_ref(),- StripeProductTier::Sonnet => ctx.stripe_price_ids.stripe_price_id_sonnet.as_ref(),- StripeProductTier::Opus => ctx.stripe_price_ids.stripe_price_id_opus.as_ref(),+ StripeProductTier::Haiku => ctx.legacy_stripe_price_ids.stripe_price_id_haiku.as_ref(),+ StripeProductTier::Sonnet => ctx.legacy_stripe_price_ids.stripe_price_id_sonnet.as_ref(),+ StripeProductTier::Opus => ctx.legacy_stripe_price_ids.stripe_price_id_opus.as_ref(),};// Create the checkout sessiondiff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/patch_subscription_tier.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/patch_subscription_tier.rsindex 333d790431..c083a4df78 100644--- a/rust/cloud-storage/authentication_service/src/api/user/stripe/patch_subscription_tier.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/patch_subscription_tier.rs@@ -13,7 +13,7 @@ use utoipa::ToSchema;use super::{StripeOperationError, StripeProductTier};use crate::api::context::ApiContext;-use crate::config::StripePriceIds;+use crate::config::LegacyStripePriceIds;use model::response::ErrorResponse;use model::user::UserContext;@@ -65,7 +65,7 @@ pub async fn patch_subscription_tier(}let new_tier = req.new_tier;- let new_price_id = price_id_for_tier(&ctx.stripe_price_ids, new_tier);+ let new_price_id = price_id_for_tier(&ctx.legacy_stripe_price_ids, new_tier);let user_roles = ctx.user_roles_and_permissions_service@@ -78,7 +78,7 @@ pub async fn patch_subscription_tier(return Err(StripeOperationError::TierUnchanged);}- let old_price_id = price_id_for_tier(&ctx.stripe_price_ids, old_tier);+ let old_price_id = price_id_for_tier(&ctx.legacy_stripe_price_ids, old_tier);let old_role = tier_to_sub_role(old_tier);let new_role = tier_to_sub_role(new_tier);@@ -172,7 +172,7 @@ fn tier_key_str(tier: StripeProductTier) -> &'static str {}/// Returns the Stripe price ID configured for the given tier.-fn price_id_for_tier(price_ids: &StripePriceIds, tier: StripeProductTier) -> &str {+fn price_id_for_tier(price_ids: &LegacyStripePriceIds, tier: StripeProductTier) -> &str {match tier {StripeProductTier::Haiku => price_ids.stripe_price_id_haiku.as_ref(),StripeProductTier::Sonnet => price_ids.stripe_price_id_sonnet.as_ref(),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 7ffc6827ba..4d78a2f7d1 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,9 +363,13 @@ async fn handle_customer_subscription_event(.context("no price id attached to subscription")?;let product_tier = match price_id.as_str() {- id if id == ctx.stripe_price_ids.stripe_price_id_haiku.as_ref() => ProductTier::Haiku,- id if id == ctx.stripe_price_ids.stripe_price_id_sonnet.as_ref() => ProductTier::Sonnet,- id if id == ctx.stripe_price_ids.stripe_price_id_opus.as_ref() => ProductTier::Opus,+ id if id == ctx.legacy_stripe_price_ids.stripe_price_id_haiku.as_ref() => {+ ProductTier::Haiku+ }+ id if id == ctx.legacy_stripe_price_ids.stripe_price_id_sonnet.as_ref() => {+ ProductTier::Sonnet+ }+ id if id == ctx.legacy_stripe_price_ids.stripe_price_id_opus.as_ref() => ProductTier::Opus,_ => {tracing::warn!(price_id=?price_id.as_str(), "unsupported price id, defaulting to haiku tier");ProductTier::Haikudiff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rsindex 0c7996c054..a617e90692 100644--- a/rust/cloud-storage/authentication_service/src/config.rs+++ b/rust/cloud-storage/authentication_service/src/config.rs@@ -87,13 +87,16 @@ pub struct Config {/// PostHog host (optional)pub posthog_host: Option<String>,- /// The stripe price ids- pub stripe_price_ids: StripePriceIds,+ /// The legacy stripe price ids+ pub legacy_stripe_price_ids: LegacyStripePriceIds,++ /// The team stripe price ids+ pub team_stripe_price_ids: TeamStripePriceIds,}env_var! {#[derive(Clone)]- pub struct StripePriceIds {+ pub struct LegacyStripePriceIds {#[derive(Clone)]pub StripePriceIdHaiku,#[derive(Clone)]@@ -103,6 +106,38 @@ env_var! {}}+#[derive(Clone)]+pub struct TeamStripePriceIds {+ /// The idea price id+ pub idea: String,+ /// The pre-seed price id+ pub pre_seed: String,+ /// The seed price id+ pub seed: String,+ /// The series-a price id+ pub series_a: String,+}++impl From<Environment> for TeamStripePriceIds {+ fn from(value: Environment) -> Self {+ // SAFETY: stripe price ids are not sensitive information so hard coding them here is simpler+ match value {+ Environment::Production => Self {+ idea: "price_1TX2JjJaD7zvQeOBv2MDjxUC".to_string(),+ pre_seed: "price_1TX2K5JaD7zvQeOBKbFKDQZr".to_string(),+ seed: "price_1TX2KJJaD7zvQeOBJljvtVoL".to_string(),+ series_a: "price_1TX2KVJaD7zvQeOByIRkVPdS".to_string(),+ },+ Environment::Develop | Environment::Local => Self {+ idea: "price_1TX2GiJaD7zvQeOBACos6om2".to_string(),+ pre_seed: "price_1TX2GxJaD7zvQeOBgueJpOTi".to_string(),+ seed: "price_1TX2HDJaD7zvQeOBXl4Xlc0c".to_string(),+ series_a: "price_1TX2HUJaD7zvQeOBMWwI4FFK".to_string(),+ },+ }+ }+}+impl Config {pub fn from_env() -> anyhow::Result<Self> {let base_url = std::env::var("BASE_URL").context("BASE_URL must be provided")?;@@ -173,7 +208,9 @@ impl Config {let posthog_api_key = std::env::var("POSTHOG_API_KEY").ok();let posthog_host = std::env::var("POSTHOG_HOST").ok();- let stripe_price_ids = StripePriceIds::new()?;+ let legacy_stripe_price_ids = LegacyStripePriceIds::new()?;++ let team_stripe_price_ids = TeamStripePriceIds::from(environment);Ok(Config {base_url,@@ -205,7 +242,8 @@ impl Config {meta_test_event_code,posthog_api_key,posthog_host,- stripe_price_ids,+ legacy_stripe_price_ids,+ team_stripe_price_ids,})}}diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex 0e6fd10bd4..2119d51d2d 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -242,10 +242,25 @@ async fn main() -> anyhow::Result<()> {let teams_repo_impl = TeamRepositoryImpl::new(db.clone());let customer_repo_impl = CustomerRepositoryImpl::new(stripe_client.clone(),- 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(),+ teams::outbound::customer_repo::TeamStripePriceIds {+ idea: config.team_stripe_price_ids.idea,+ pre_seed: config.team_stripe_price_ids.pre_seed,+ seed: config.team_stripe_price_ids.seed,+ series_a: config.team_stripe_price_ids.series_a,+ },+ teams::outbound::customer_repo::LegacyStripePriceIds {+ haiku: config+ .legacy_stripe_price_ids+ .stripe_price_id_haiku+ .to_string(),+ sonnet: config+ .legacy_stripe_price_ids+ .stripe_price_id_sonnet+ .to_string(),+ opus: config+ .legacy_stripe_price_ids+ .stripe_price_id_opus+ .to_string(),},);let team_channels_repo_impl = TeamChannelsRepositoryImpl::new(db.clone());@@ -324,7 +339,7 @@ async fn main() -> anyhow::Result<()> {},}),analytics_client: Arc::new(analytics_client),- stripe_price_ids: config.stripe_price_ids,+ legacy_stripe_price_ids: config.legacy_stripe_price_ids,},config.port,)diff --git a/rust/cloud-storage/macro_db_client/migrations/20260514192605_team_plans.sql b/rust/cloud-storage/macro_db_client/migrations/20260514192605_team_plans.sqlnew file mode 100644index 0000000000..176a290042--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260514192605_team_plans.sql@@ -0,0 +1,5 @@+-- Create enum team_plan ordered from cheapest to most expensive+CREATE TYPE "team_plan" AS ENUM ('idea', 'pre_seed', 'seed', 'series_a', 'growth');++-- Create the nullable team plan in the team line+ALTER TABLE "team" ADD COLUMN plan "team_plan";diff --git a/rust/cloud-storage/teams/src/domain/customer_repo.rs b/rust/cloud-storage/teams/src/domain/customer_repo.rsindex d848d20f8e..8ad9843868 100644--- a/rust/cloud-storage/teams/src/domain/customer_repo.rs+++ b/rust/cloud-storage/teams/src/domain/customer_repo.rs@@ -2,7 +2,7 @@use macro_user_id::user_id::MacroUserIdStr;-use crate::domain::model::{CreateSubscriptionArgs, CustomerError};+use crate::domain::model::{CreateSubscriptionArgs, CustomerError, TeamPlan};/// The CustomerRepository defines a set of actions to perform on customer datapub trait CustomerRepository: Clone + Send + Sync + 'static {@@ -31,4 +31,12 @@ pub trait CustomerRepository: Clone + Send + Sync + 'static {&self,subscription_id: &stripe::SubscriptionId,) -> impl Future<Output = Result<(), CustomerError>> + Send;++ /// Update the plan for the team+ fn update_team_plan(+ &self,+ subscription_id: &stripe::SubscriptionId,+ current_team_plan: Option<TeamPlan>,+ team_plan: TeamPlan,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send;}diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rsindex a00e95208b..a0a09786c0 100644--- a/rust/cloud-storage/teams/src/domain/model.rs+++ b/rust/cloud-storage/teams/src/domain/model.rs@@ -6,6 +6,51 @@ use chrono::{DateTime, Utc};use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};use roles_and_permissions::domain::model::UserRolesAndPermissionsError;+/// Team plans+#[derive(+ Eq,+ PartialEq,+ Debug,+ Clone,+ PartialOrd,+ Copy,+ std::cmp::Ord,+ serde::Serialize,+ serde::Deserialize,+)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "outbound", derive(sqlx::Type))]+#[cfg_attr(+ feature = "outbound",+ sqlx(type_name = "\"team_plan\"", rename_all = "snake_case")+)]+#[serde(rename_all = "snake_case")]+pub enum TeamPlan {+ /// Idea team plan+ Idea,+ /// Pre-seed team plan+ PreSeed,+ /// Seed team plan+ Seed,+ /// Series A team plan+ SeriesA,+ /// Growth team plan+ Growth,+}++impl TeamPlan {+ /// Get the seat cap associated with a team plan+ pub fn seat_cap(&self) -> i32 {+ match self {+ TeamPlan::Idea => 3,+ TeamPlan::PreSeed => 6,+ TeamPlan::Seed => 10,+ TeamPlan::SeriesA => 25,+ TeamPlan::Growth => i32::MAX,+ }+ }+}+#[derive(Eq,PartialEq,@@ -97,6 +142,14 @@ pub struct PatchTeamRequest {pub user_role_updates: Option<Vec<PatchTeamUserRole>>,}+/// Request to update the team plan+#[derive(Debug, serde::Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub struct PatchTeamPlanRequest {+ /// The new team plan+ pub team_plan: TeamPlan,+}+/// Request to update a team user's role#[derive(Debug, serde::Deserialize)]#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rsindex 44fc7140d3..cba4beaaa1 100644--- a/rust/cloud-storage/teams/src/domain/team_repo.rs+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs@@ -9,9 +9,9 @@ use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStruse crate::domain::model::{AcceptedTeamInvite, CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,- PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,+ PatchTeamPlanRequest, PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team, TeamError,- TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamWithMembers,+ TeamInvite, TeamInviteDetails, TeamMember, TeamPlan, TeamRole, TeamWithMembers,};/// The TeamChannelsRepository defines a set of actions related to team channels@@ -209,6 +209,25 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {user_id: &MacroUserIdStr<'_>,team_role: TeamRole,) -> impl Future<Output = Result<(), TeamError>> + Send;++ /// Get the teams current seat count+ fn get_team_seat_count(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<i32, TeamError>> + Send;++ /// Gets the teams current plan+ fn get_team_plan(+ &self,+ team_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<Option<TeamPlan>, TeamError>> + Send;++ /// Patches the teams current plan+ fn patch_team_plan(+ &self,+ team_id: &uuid::Uuid,+ team_plan: TeamPlan,+ ) -> impl Future<Output = Result<(), TeamError>> + Send;}/// The TeamService defines a set of actions to perform on the teams@@ -317,4 +336,11 @@ pub trait TeamService: Clone + Send + Sync + 'static {) -> impl Future<Output = Result<HashSet<roles_and_permissions::domain::model::PermissionId>, TeamError>,> + Send;++ /// Updates the teams plan+ fn update_team_plan(+ &self,+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,+ req: &PatchTeamPlanRequest,+ ) -> impl Future<Output = Result<(), TeamError>> + Send;}diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rsindex 696a475997..63a4256cbf 100644--- a/rust/cloud-storage/teams/src/domain/team_service.rs+++ b/rust/cloud-storage/teams/src/domain/team_service.rs@@ -5,6 +5,7 @@ mod test;use std::{collections::HashSet, sync::Arc};+use anyhow::Context;use entity_access::domain::models::{AdminTeamRole, EntityAccessReceipt, MemberTeamRole, OwnerTeamRole,};@@ -23,10 +24,10 @@ use notification::domain::{models::SendNotificationRequestBuilder, service::Notiuse crate::domain::{customer_repo::CustomerRepository,model::{- CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, PatchTeamRequest,- RemoveTeamInviteError, RemoveUserFromTeamError, RestorePermissionsForTeamMembersError,- RevokePermissionsForTeamMembersError, Team, TeamError, TeamInvite, TeamInviteDetails,- TeamMember, TeamRole, TeamWithMembers,+ CreateTeamError, CustomerError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,+ PatchTeamPlanRequest, PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError,+ RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team,+ TeamError, TeamInvite, TeamInviteDetails, TeamMember, TeamPlan, TeamRole, TeamWithMembers,},team_repo::{TeamChannelsRepository, TeamRepository, TeamService},};@@ -106,6 +107,62 @@ 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,+ ) -> Result<stripe::SubscriptionId, GetTeamSubscriptionError> {+ let subscription_id = self+ .team_repository+ .get_team_subscription_id(team_id)+ .await+ .map_err(GetTeamSubscriptionError::Team)?;++ // stripe subscription is already tracked for team+ if let Some(subscription_id) = subscription_id {+ return Ok(subscription_id);+ }++ tracing::info!("no subscription found for team");++ // Get the team to get owner+ let team = self+ .team_repository+ .get_team_by_id(team_id)+ .await+ .map_err(GetTeamSubscriptionError::Team)?;++ let customer_id = self+ .team_repository+ .get_stripe_customer_id(&team.team.owner_id)+ .await+ .map_err(GetTeamSubscriptionError::Team)?+ .context("expected customer id")?;++ let customer_subscription_id = self+ .customer_repository+ .get_subscription_id_for_customer(&customer_id)+ .await+ .map_err(GetTeamSubscriptionError::Customer)?;++ // Convert the customer's subscription to a team subscription before storing it locally,+ // so a customer failure cannot leave a local subscription_id pointing at an unconverted+ // personal subscription.+ self.customer_repository+ .convert_subscription_to_team(&customer_subscription_id, team_id, &team.team.owner_id)+ .await+ .map_err(GetTeamSubscriptionError::Customer)?;++ self.team_repository+ .update_team_subscription(team_id, &customer_subscription_id)+ .await+ .map_err(GetTeamSubscriptionError::Team)?;++ Ok(customer_subscription_id)+ }+/// Sends an invite notification for a team invite#[tracing::instrument(skip(self), err)]async fn send_invite_notification(@@ -133,6 +190,26 @@ where}}+#[derive(Debug, thiserror::Error)]+enum GetTeamSubscriptionError {+ #[error(transparent)]+ Team(#[from] TeamError),+ #[error(transparent)]+ Customer(#[from] CustomerError),+ #[error(transparent)]+ Storage(#[from] anyhow::Error),+}++impl GetTeamSubscriptionError {+ fn into_team_error(self) -> TeamError {+ match self {+ Self::Team(e) => e,+ Self::Customer(e) => TeamError::StorageLayerError(e.into()),+ Self::Storage(e) => TeamError::StorageLayerError(e),+ }+ }+}+impl<TR, CR, TCR, URPS, NI> TeamService for TeamServiceImpl<TR, CR, TCR, URPS, NI>whereTR: TeamRepository,@@ -493,4 +570,68 @@ where.await.map_err(|e| TeamError::StorageLayerError(e.into()))}++ #[tracing::instrument(skip(self), err)]+ async fn update_team_plan(+ &self,+ entity_access_receipt: EntityAccessReceipt<OwnerTeamRole>,+ req: &PatchTeamPlanRequest,+ ) -> Result<(), TeamError> {+ let team_id =+ macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();++ let new_team_plan = req.team_plan;++ // Ensure the user isn't trying to upgrade to growth plan+ if new_team_plan == TeamPlan::Growth {+ return Err(TeamError::BadRequest(+ "cannot upgrade to growth plan automatically".to_string(),+ ));+ }++ let team_seat_count = self.team_repository.get_team_seat_count(&team_id).await?;++ let current_team_plan = self.team_repository.get_team_plan(&team_id).await?;++ // Check if plans are equal+ if let Some(current_team_plan) = current_team_plan+ && new_team_plan == current_team_plan+ {+ return Err(TeamError::BadRequest(+ "cannot change plan to same plan.".to_string(),+ ));+ }++ // Check if the user has the seat capacity to downgrade+ if team_seat_count > new_team_plan.seat_cap() {+ return Err(TeamError::BadRequest(+ "you have too many members to downgrade to this plan".to_string(),+ ));+ }++ let subscription_id = match self.get_team_subscription(&team_id).await {+ Ok(subscription_id) => subscription_id,+ Err(e) => return Err(e.into_team_error()),+ };++ // Bump plan in db+ self.team_repository+ .patch_team_plan(&team_id, new_team_plan)+ .await?;++ if let Err(e) = self+ .customer_repository+ .update_team_plan(&subscription_id, current_team_plan, new_team_plan)+ .await+ {+ if let Some(team_plan) = current_team_plan {+ self.team_repository+ .patch_team_plan(&team_id, team_plan)+ .await?;+ }+ return Err(TeamError::StorageLayerError(e.into()));+ }++ Ok(())+ }}diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rsindex 66f50c3126..20e8e5a956 100644--- a/rust/cloud-storage/teams/src/domain/team_service/test.rs+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs@@ -37,7 +37,7 @@ use crate::domain::{model::{AcceptedTeamInvite, CreateSubscriptionArgs, CustomerError, PatchTeamRequest,PatchTeamUserRole, RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError,- TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamWithMembers,+ TeamInvite, TeamInviteDetails, TeamMember, TeamPlan, TeamRole, TeamWithMembers,},team_repo::{TeamChannelsRepository, TeamRepository},};@@ -330,6 +330,28 @@ impl TeamRepository for MockTeamRepository {));async { Ok(()) }}++ fn get_team_seat_count(+ &self,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<i32, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_team_plan(+ &self,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<Option<TeamPlan>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn patch_team_plan(+ &self,+ _: &uuid::Uuid,+ _: TeamPlan,+ ) -> impl Future<Output = Result<(), TeamError>> + Send {+ async { unimplemented!() }+ }}// -- Mock CustomerRepository --@@ -367,6 +389,15 @@ impl CustomerRepository for MockCustomerRepository {) -> impl Future<Output = Result<(), CustomerError>> + Send {async { unimplemented!() }}++ fn update_team_plan(+ &self,+ _subscription_id: &stripe::SubscriptionId,+ _current_team_plan: Option<TeamPlan>,+ _team_plan: TeamPlan,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send {+ async { unimplemented!() }+ }}// -- Mock TeamChannelsRepository --diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rsindex c780a0d503..e434d0d0ee 100644--- a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs+++ b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs@@ -22,6 +22,8 @@ pub mod join_team;pub mod middleware;/// Update a team.pub mod patch_team;+/// Update team plan.+pub mod patch_team_plan;/// Reject a team invitation.pub mod reject_invitation;/// Remove a user from a team.@@ -88,6 +90,7 @@ where.route("/user/invites", get(get_user_invites::handler::<T, Eas>)).route("/", get(get_team::handler::<T, Eas>)).route("/", patch(patch_team::handler::<T, Eas>))+ .route("/plan", patch(patch_team_plan::handler::<T, Eas>)).route("/", delete(delete_team::handler::<T, Eas>)).route("/invites", get(get_team_invites::handler::<T, Eas>)).route("/invite", post(invite_to_team::handler::<T, Eas>))diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_plan.rs b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_plan.rsnew file mode 100644index 0000000000..d522ab4088--- /dev/null+++ b/rust/cloud-storage/teams/src/inbound/axum_router/patch_team_plan.rs@@ -0,0 +1,40 @@+use axum::{Json, extract::State};+use entity_access::{+ domain::{models::OwnerTeamRole, ports::EntityAccessService},+ inbound::axum_extractors::MacroUserTeamExtractor,+};+use model_error_response::ErrorResponse;++use crate::domain::{+ model::{PatchTeamPlanRequest, TeamError},+ team_repo::TeamService,+};++use super::TeamRouterState;++/// Updates a team plan.+#[utoipa::path(+ patch,+ path = "/team/plan",+ operation_id = "patch_team_plan",+ request_body = PatchTeamPlanRequest,+ responses(+ (status = 200),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ ),+)]+#[tracing::instrument(skip_all, err)]+pub async fn handler<T: TeamService, Eas: EntityAccessService>(+ access: MacroUserTeamExtractor<OwnerTeamRole, Eas>,+ State(state): State<TeamRouterState<T, Eas>>,+ Json(req): Json<PatchTeamPlanRequest>,+) -> Result<(), TeamError> {+ state+ .service+ .update_team_plan(access.entity_access_receipt, &req)+ .await?;+ Ok(())+}diff --git a/rust/cloud-storage/teams/src/outbound/customer_repo.rs b/rust/cloud-storage/teams/src/outbound/customer_repo.rsindex 6157179e41..0ebbf37e0e 100644--- a/rust/cloud-storage/teams/src/outbound/customer_repo.rs+++ b/rust/cloud-storage/teams/src/outbound/customer_repo.rs@@ -6,12 +6,13 @@ use stripe::{CreateSubscription, CreateSubscriptionItems, UpdateSubscription};use crate::domain::{customer_repo::CustomerRepository,- model::{CreateSubscriptionArgs, CustomerError},+ model::{CreateSubscriptionArgs, CustomerError, TeamPlan},};/// The stripe price ids for all tiers+/// These are legacy stripe price ids for the old tier system#[derive(Clone)]-pub struct StripePriceIds {+pub struct LegacyStripePriceIds {/// haiku tier price idpub haiku: String,/// sonnet tier price id@@ -20,21 +21,57 @@ pub struct StripePriceIds {pub opus: String,}+/// Team plan stripe price ids+/// Note: there is not `growth` plan price id as growth plan is white glove.+#[derive(Clone)]+pub struct TeamStripePriceIds {+ /// The idea price id+ pub idea: String,+ /// The pre-seed price id+ pub pre_seed: String,+ /// The seed price id+ pub seed: String,+ /// The series-a price id+ pub series_a: String,+}++impl TeamStripePriceIds {+ /// Tries to map the stripe price id for a team plan+ fn try_get_price_id_for_team_plan(&self, value: TeamPlan) -> Result<String, CustomerError> {+ let price_id = match value {+ TeamPlan::Idea => self.idea.clone(),+ TeamPlan::PreSeed => self.pre_seed.clone(),+ TeamPlan::Seed => self.seed.clone(),+ TeamPlan::SeriesA => self.series_a.clone(),+ TeamPlan::Growth => return Err(anyhow::anyhow!("no price id for growth plan").into()),+ };++ Ok(price_id)+ }+}+/// 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 stripe price ids- stripe_price_ids: StripePriceIds,+ /// The team plan stripe price ids+ team_plan_stripe_price_ids: TeamStripePriceIds,+ /// The legacy stripe price ids+ legacy_stripe_price_ids: LegacyStripePriceIds,}impl CustomerRepositoryImpl {/// Creates a new instance of CustomerRepositoryImpl- pub fn new(stripe_client: stripe::Client, stripe_price_ids: StripePriceIds) -> Self {+ pub fn new(+ stripe_client: stripe::Client,+ team_plan_stripe_price_ids: TeamStripePriceIds,+ legacy_stripe_price_ids: LegacyStripePriceIds,+ ) -> Self {Self {client: Arc::new(stripe_client),- stripe_price_ids,+ team_plan_stripe_price_ids,+ legacy_stripe_price_ids,}}}@@ -48,7 +85,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_ids.haiku.clone()),+ price: Some(self.legacy_stripe_price_ids.haiku.clone()),quantity: Some(args.quantity),..Default::default()}]);@@ -118,4 +155,80 @@ impl CustomerRepository for CustomerRepositoryImpl {.map(|sub| sub.id).ok_or(CustomerError::SubscriptionNotActive)}++ #[tracing::instrument(skip(self), err)]+ async fn update_team_plan(+ &self,+ subscription_id: &stripe::SubscriptionId,+ current_plan: Option<TeamPlan>,+ team_plan: TeamPlan,+ ) -> Result<(), CustomerError> {+ // Get new plan price id+ let new_plan_price_id = self+ .team_plan_stripe_price_ids+ .try_get_price_id_for_team_plan(team_plan)?;++ 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 mut items = Vec::with_capacity(2);++ if let Some(current_team_plan) = current_plan {+ let old_plan_price_id = self+ .team_plan_stripe_price_ids+ .try_get_price_id_for_team_plan(current_team_plan)?;++ // The old item must exist+ let old_item = subscription+ .items+ .data+ .iter()+ .find(|item| {+ item.price+ .as_ref()+ .map(|p| p.id == old_plan_price_id)+ .unwrap_or(false)+ })+ .ok_or_else(|| {+ CustomerError::StorageLayerError(anyhow::anyhow!(+ "No subscription item found for old tier {:?}",+ current_team_plan+ ))+ })?;++ // delete the current price id+ items.push(stripe::UpdateSubscriptionItems {+ id: Some(old_item.id.to_string()),+ deleted: Some(true),+ ..Default::default()+ });+ }++ // Add the new item+ items.push(stripe::UpdateSubscriptionItems {+ price: Some(new_plan_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 c533ac0581..1427eaccea 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs@@ -3,7 +3,7 @@ use crate::domain::{model::{AcceptedTeamInvite, CreateTeamError, InviteUsersToTeamError, PatchTeamRequest,RemoveTeamInviteError, RemoveUserFromTeamError, Team, TeamError, TeamInvite,- TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamRole, TeamWithMembers,+ TeamInviteDetails, TeamInviteSnapshot, TeamMember, TeamPlan, TeamRole, TeamWithMembers,},team_repo::TeamRepository,};@@ -93,8 +93,8 @@ impl TeamRepositoryImpl {let team = sqlx::query!(r#"- INSERT INTO team (id, name, owner_id)- VALUES ($1, $2, $3)+ INSERT INTO team (id, name, owner_id, seat_count)+ VALUES ($1, $2, $3, 1)RETURNING id, name, owner_id"#,&id,@@ -1075,4 +1075,63 @@ impl TeamRepository for TeamRepositoryImpl {Ok(())}++ #[tracing::instrument(skip(self), err)]+ async fn get_team_seat_count(&self, team_id: &uuid::Uuid) -> Result<i32, TeamError> {+ let seat_count = sqlx::query!(+ r#"+ SELECT seat_count+ FROM team+ WHERE id = $1+ "#,+ team_id,+ )+ .map(|row| row.seat_count)+ .fetch_one(&self.pool)+ .await?;++ Ok(seat_count)+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_team_plan(&self, team_id: &uuid::Uuid) -> Result<Option<TeamPlan>, TeamError> {+ let plan = sqlx::query!(+ r#"+ SELECT plan as "plan?: TeamPlan"+ FROM team+ WHERE id = $1+ "#,+ team_id,+ )+ .map(|row| row.plan)+ .fetch_one(&self.pool)+ .await?;++ Ok(plan)+ }++ #[tracing::instrument(skip(self), err)]+ async fn patch_team_plan(+ &self,+ team_id: &uuid::Uuid,+ team_plan: TeamPlan,+ ) -> Result<(), TeamError> {+ let result = sqlx::query!(+ r#"+ UPDATE team+ SET plan = $2+ WHERE id = $1+ "#,+ team_id,+ team_plan as _,+ )+ .execute(&self.pool)+ .await?;++ if result.rows_affected() == 0 {+ return Err(TeamError::TeamDoesNotExist);+ }++ Ok(())+ }}diff --git a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs b/rust/cloud-storage/teams/src/outbound/team_repo/test.rsindex 96d03334bd..3969f43e98 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs@@ -751,6 +751,100 @@ async fn test_bump_seat_count_negative(pool: Pool<Postgres>) -> anyhow::Result<(Ok(())}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_get_team_seat_count(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool);++ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;+ let seat_count = team_repo.get_team_seat_count(&team_id).await?;+ assert_eq!(seat_count, 3);++ let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;+ let err = team_repo+ .get_team_seat_count(&missing_team_id)+ .await+ .err()+ .unwrap();+ assert!(err.to_string().contains("does not exist"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_get_team_plan(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool);++ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ let plan = team_repo.get_team_plan(&team_id).await?;+ assert_eq!(plan, None);++ team_repo+ .patch_team_plan(&team_id, TeamPlan::SeriesA)+ .await?;++ let plan = team_repo.get_team_plan(&team_id).await?;+ assert_eq!(plan, Some(TeamPlan::SeriesA));++ let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;+ let err = team_repo+ .get_team_plan(&missing_team_id)+ .await+ .err()+ .unwrap();+ assert!(err.to_string().contains("does not exist"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_patch_team_plan(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool.clone());++ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ team_repo.patch_team_plan(&team_id, TeamPlan::Seed).await?;++ let row = sqlx::query!(+ r#"SELECT plan::text AS "plan!" FROM team WHERE id = $1"#,+ &team_id,+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(row.plan, "seed");++ team_repo+ .patch_team_plan(&team_id, TeamPlan::Growth)+ .await?;++ let row = sqlx::query!(+ r#"SELECT plan::text AS "plan!" FROM team WHERE id = $1"#,+ &team_id,+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(row.plan, "growth");++ let missing_team_id = macro_uuid::string_to_uuid("63333333-3333-3333-3333-333333333333")?;+ let err = team_repo+ .patch_team_plan(&missing_team_id, TeamPlan::Idea)+ .await+ .err()+ .unwrap();+ assert!(err.to_string().contains("does not exist"));++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("teams"))