Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(ai-billing): stop treating canceled team subscriptions as paid (#9145)

Peter Chinman03ca5ec26623
diff --git a/crates/ai_billing/Cargo.toml b/crates/ai_billing/Cargo.toml
index 8bdc983389..3c143356ab 100644
--- a/crates/ai_billing/Cargo.toml
+++ b/crates/ai_billing/Cargo.toml
@@ -41,5 +41,9 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
+roles_and_permissions = { path = "../roles_and_permissions", default-features = false, features = [
+ "outbound",
+] }
+teams = { path = "../teams", default-features = false, features = ["outbound"] }
tracing-subscriber = { workspace = true }
wiremock = { workspace = true }
diff --git a/crates/ai_billing/fixtures/entitlement_teams.sql b/crates/ai_billing/fixtures/entitlement_teams.sql
new file mode 100644
index 0000000000..cd18706c73
--- /dev/null
+++ b/crates/ai_billing/fixtures/entitlement_teams.sql
@@ -0,0 +1,27 @@
+INSERT INTO "macro_user" (id, username, email, stripe_customer_id)
+VALUES
+ ('b1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'cus_paid_owner'),
+ ('b2222222-2222-2222-2222-222222222222', '[email protected]', '[email protected]', 'cus_paid_member'),
+ ('b3333333-3333-3333-3333-333333333333', '[email protected]', '[email protected]', 'cus_canceled_owner'),
+ ('b4444444-4444-4444-4444-444444444444', '[email protected]', '[email protected]', 'cus_canceled_member');
+
+INSERT INTO "User" ("id", "email", "name", "stripeCustomerId", "macro_user_id")
+VALUES
+ ('macro|[email protected]', '[email protected]', 'Paid Owner', NULL, 'b1111111-1111-1111-1111-111111111111'),
+ ('macro|[email protected]', '[email protected]', 'Paid Member', NULL, 'b2222222-2222-2222-2222-222222222222'),
+ ('macro|[email protected]', '[email protected]', 'Canceled Owner', NULL, 'b3333333-3333-3333-3333-333333333333'),
+ ('macro|[email protected]', '[email protected]', 'Canceled Member', 'cus_canceled_member', 'b4444444-4444-4444-4444-444444444444');
+
+-- The canceled team keeps the id of its ended subscription, as the Stripe
+-- webhook leaves it.
+INSERT INTO team (id, name, owner_id, subscription_id, seat_count, paying)
+VALUES
+ ('11111111-1111-1111-1111-111111111111', 'paid', 'macro|[email protected]', 'sub_paid', 2, true),
+ ('22222222-2222-2222-2222-222222222222', 'canceled', 'macro|[email protected]', 'sub_canceled', 2, false);
+
+INSERT INTO team_user (team_id, user_id, team_role)
+VALUES
+ ('11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'owner'),
+ ('11111111-1111-1111-1111-111111111111', 'macro|[email protected]', 'member'),
+ ('22222222-2222-2222-2222-222222222222', 'macro|[email protected]', 'owner'),
+ ('22222222-2222-2222-2222-222222222222', 'macro|[email protected]', 'member');
diff --git a/crates/ai_billing/src/outbound/entitlement.rs b/crates/ai_billing/src/outbound/entitlement.rs
index 3d65a3e831..c6bbe0bf27 100644
--- a/crates/ai_billing/src/outbound/entitlement.rs
+++ b/crates/ai_billing/src/outbound/entitlement.rs
@@ -6,9 +6,12 @@ use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use roles_and_permissions::domain::port::UserRolesAndPermissionsService;
-use teams::domain::model::TeamError;
+use teams::domain::model::{Team, TeamError};
use teams::domain::team_repo::TeamRepository;
+#[cfg(test)]
+mod test;
+
/// [`EntitlementSource`] over the roles service and the teams repository.
///
/// - A member of a paying (or enterprise) team is billed through the team
@@ -47,6 +50,36 @@ where
.map_err(entitlement_err)?;
Ok(PlanTier::from_roles(&roles))
}
+
+ /// Whether the team bills its members' seats: an enterprise team, or a
+ /// paying team with a subscription (`TeamService::team_bills_per_seat`).
+ /// A canceled subscription leaves its id on the team, so the id alone
+ /// does not mean the team pays.
+ #[tracing::instrument(
+ skip(self, team),
+ fields(team_id = %team.id(), bills_seats = tracing::field::Empty),
+ err
+ )]
+ async fn team_bills_seats(&self, team: &Team) -> Result<bool> {
+ let bills_seats = if team.enterprise() {
+ true
+ } else {
+ let paying = self
+ .teams
+ .get_team_payment_status(team.id())
+ .await
+ .map_err(entitlement_err)?;
+ paying
+ && self
+ .teams
+ .get_team_subscription_id(team.id())
+ .await
+ .map_err(entitlement_err)?
+ .is_some()
+ };
+ tracing::Span::current().record("bills_seats", bills_seats);
+ Ok(bills_seats)
+ }
}
impl<P, T> PeriodBindingSource for RolesTeamsEntitlementSource<P, T>
@@ -81,14 +114,7 @@ where
.await
.map_err(entitlement_err)?
{
- if team.enterprise()
- || self
- .teams
- .get_team_subscription_id(team.id())
- .await
- .map_err(entitlement_err)?
- .is_some()
- {
+ if self.team_bills_seats(&team).await? {
return Ok(None);
}
}
@@ -150,13 +176,9 @@ where
return Ok(Entitlement::personal(user_owned, own_tier));
};
- let subscription = self
- .teams
- .get_team_subscription_id(team.id())
- .await
- .map_err(entitlement_err)?;
- if !team.enterprise() && subscription.is_none() {
- // A free team: everyone pays for themself.
+ if !self.team_bills_seats(&team).await? {
+ // A free team, or one whose subscription ended: everyone pays for
+ // themself.
return Ok(Entitlement::personal(user_owned, own_tier));
}
diff --git a/crates/ai_billing/src/outbound/entitlement/test.rs b/crates/ai_billing/src/outbound/entitlement/test.rs
new file mode 100644
index 0000000000..fb3ce84520
--- /dev/null
+++ b/crates/ai_billing/src/outbound/entitlement/test.rs
@@ -0,0 +1,84 @@
+use super::*;
+use crate::domain::BillingPeriod;
+use crate::domain::period::{PeriodEvidence, SubscriptionActivity};
+use chrono::{DateTime, Duration};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl;
+use roles_and_permissions::outbound::pgpool::MacroDB;
+use sqlx::PgPool;
+use teams::outbound::team_repo::TeamRepositoryImpl;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("entitlement_teams"))
+)]
+async fn only_a_paying_team_bills_its_members_seats(pool: PgPool) {
+ let entitlements = RolesTeamsEntitlementSource::new(
+ UserRolesAndPermissionsServiceImpl::new(
+ MacroDB::new(pool.clone()),
+ MacroDB::new(pool.clone()),
+ ),
+ TeamRepositoryImpl::new(pool),
+ );
+
+ let paid_member =
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ let paid = entitlements.entitlement(&paid_member).await.unwrap();
+ assert_eq!(paid.tier, PlanTier::Premium);
+ assert_eq!(
+ paid.scope,
+ PayerScope::TeamMember {
+ team_id: Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(),
+ }
+ );
+
+ let canceled_member =
+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ assert_eq!(
+ entitlements.entitlement(&canceled_member).await.unwrap(),
+ Entitlement::personal(canceled_member, PlanTier::Free)
+ );
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("entitlement_teams"))
+)]
+async fn a_canceled_team_does_not_block_a_members_personal_subscription(pool: PgPool) {
+ let entitlements = RolesTeamsEntitlementSource::new(
+ UserRolesAndPermissionsServiceImpl::new(
+ MacroDB::new(pool.clone()),
+ MacroDB::new(pool.clone()),
+ ),
+ TeamRepositoryImpl::new(pool),
+ );
+ let at = DateTime::from_timestamp(1_800_000_000, 0).unwrap();
+ let personal = SubscriptionPeriod {
+ event_id: "evt_personal".parse().unwrap(),
+ event_at: at,
+ subscription_id: "sub_personal".parse().unwrap(),
+ subscription_created_at: at,
+ customer_id: "cus_canceled_member".parse().unwrap(),
+ team_id: None,
+ quantity: 1,
+ item_count: 1,
+ item_id: "si_personal".parse().unwrap(),
+ price_id: "price_40".parse().unwrap(),
+ product_id: "prod_40".parse().unwrap(),
+ unit_amount: Some(4_000),
+ currency: "usd".into(),
+ monthly: true,
+ activity: SubscriptionActivity::Active,
+ period: BillingPeriod {
+ start: at,
+ end: at + Duration::days(30),
+ },
+ evidence: PeriodEvidence::Snapshot,
+ };
+
+ let member = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();
+ assert_eq!(
+ entitlements.seats(&member, &personal).await.unwrap(),
+ Some(vec![member])
+ );
+}
diff --git a/tooling/seed_cli/src/entity/scenario/apply.rs b/tooling/seed_cli/src/entity/scenario/apply.rs
index dcc861a1ba..8eec8570c6 100644
--- a/tooling/seed_cli/src/entity/scenario/apply.rs
+++ b/tooling/seed_cli/src/entity/scenario/apply.rs
@@ -287,6 +287,7 @@ async fn seed_teams(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result
sql_string(&spec.user_id(&team.owner)),
sql_string(&format!("sub_seed_{}_{key}", spec.scenario)),
(team.members.len() + 1).to_string(),
+ "true".to_string(),
]
}));
@@ -320,7 +321,7 @@ async fn seed_teams(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result
let statements = vec![
format!(
- "INSERT INTO team (id, name, owner_id, subscription_id, seat_count) VALUES\n {team_values}"
+ "INSERT INTO team (id, name, owner_id, subscription_id, seat_count, paying) VALUES\n {team_values}"
),
format!("INSERT INTO team_user (user_id, team_id, team_role) VALUES\n {member_values}"),
format!("INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES\n {crm_values}"),