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.

31.3 KB
Raw Blame
//! Contains the models for teams

use std::collections::{HashMap, HashSet};

use chrono::{DateTime, Utc};
use macro_user_id::{
    cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserIdStr,
};
use model_user::Language;
use models_permissions::share_permission::LinkShare;
use roles_and_permissions::domain::model::{ProductTier, RoleId, UserRolesAndPermissionsError};

use crate::domain::owned_entity_cleanup::OwnedEntityCleanupError;

mod invite_link;

pub use invite_link::{
    JoinTeamByInviteLinkError, JoinTeamByInviteLinkOutcome, ManageTeamInviteLinkError,
    TeamInviteLinkTeam, TeamInviteLinkToken,
};

/// 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,
}

/// Slug assigned when a team name cannot be converted to a valid team slug.
pub const DEFAULT_TEAM_SLUG: &str = "MACRO";

const MAX_TEAM_SLUG_LEN: usize = 20;

pub(crate) fn normalize_team_slug(slug: &str) -> Result<String, TeamError> {
    let mut normalized = String::new();
    let mut last_was_separator = false;

    for ch in slug.chars() {
        let normalized_char = if ch.is_ascii_alphabetic() {
            ch.to_ascii_uppercase()
        } else if ch == '_' || ch == '-' || ch.is_ascii_whitespace() {
            '_'
        } else {
            return Err(TeamError::BadRequest(
                "team slug may only contain ASCII letters, spaces, hyphens, and underscores"
                    .to_string(),
            ));
        };

        if normalized_char == '_' {
            if !normalized.is_empty() && !last_was_separator {
                normalized.push('_');
            }
            last_was_separator = true;
        } else {
            normalized.push(normalized_char);
            last_was_separator = false;
        }
    }

    while normalized.ends_with('_') {
        normalized.pop();
    }

    if normalized.is_empty() {
        return Err(TeamError::BadRequest(
            "team slug cannot be empty".to_string(),
        ));
    }

    if normalized.len() > MAX_TEAM_SLUG_LEN {
        return Err(TeamError::BadRequest(format!(
            "team slug cannot be longer than {MAX_TEAM_SLUG_LEN} characters"
        )));
    }

    Ok(normalized)
}

pub(crate) fn team_slug_from_name(team_name: &str) -> String {
    normalize_team_slug(team_name).unwrap_or_else(|_| DEFAULT_TEAM_SLUG.to_string())
}

#[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_role\"", rename_all = "lowercase")
)]
#[serde(rename_all = "lowercase")]
/// Ordered from least to most access top -> bottom
pub enum TeamRole {
    /// The user is a member of the team
    Member,
    /// The user is an admin of the team
    Admin,
    /// The user is the owner of the team
    Owner,
}

impl std::fmt::Display for TeamRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TeamRole::Member => write!(f, "member"),
            TeamRole::Admin => write!(f, "admin"),
            TeamRole::Owner => write!(f, "owner"),
        }
    }
}

/// The paid plan a seat is billed at. Every member of a paying team has one;
/// a team may mix them, and its Stripe subscription carries one seat item per
/// plan in use.
#[derive(Eq, PartialEq, Debug, Clone, Copy, Hash, 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 = "\"seat_plan\"", rename_all = "snake_case")
)]
#[serde(rename_all = "snake_case")]
pub enum SeatPlan {
    /// The $40/seat/month plan.
    Premium,
    /// The $200/seat/month plan with a larger AI allowance.
    Max,
}

impl SeatPlan {
    /// Every plan.
    pub const ALL: [SeatPlan; 2] = [SeatPlan::Premium, SeatPlan::Max];

    /// Plans available for a new purchase or plan move.
    pub const PURCHASABLE: [SeatPlan; 2] = Self::ALL;

    /// The role tier recorded on a user holding this seat.
    pub fn product_tier(self) -> ProductTier {
        match self {
            SeatPlan::Premium => ProductTier::Opus,
            SeatPlan::Max => ProductTier::Max,
        }
    }

    /// The subscription role that records this seat's tier on a user.
    pub fn role(self) -> RoleId {
        self.product_tier().role()
    }

    /// The tier roles of every other plan, to drop when a seat moves here.
    pub fn other_tier_roles(self) -> Vec<RoleId> {
        let keep = self.role();
        ProductTier::ALL
            .iter()
            .map(ProductTier::role)
            .filter(|role| *role != keep)
            .collect()
    }

    /// The plan a user's roles say they are on. `sub_max` wins; any other
    /// (or no) paid role is Premium, the plan every seat starts on.
    pub fn from_roles(roles: &HashSet<RoleId>) -> Self {
        if roles.contains(&RoleId::SubMax) {
            SeatPlan::Max
        } else {
            SeatPlan::Premium
        }
    }
}

impl std::fmt::Display for SeatPlan {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SeatPlan::Premium => write!(f, "premium"),
            SeatPlan::Max => write!(f, "max"),
        }
    }
}

/// The Stripe price ids behind each plan's per-seat subscription item.
#[derive(Debug, Clone)]
pub struct SeatPrices {
    /// Premium seat price.
    pub premium: String,
    /// Max seat price, when the plan is sold.
    pub max: Option<String>,
}

impl SeatPrices {
    /// The price a seat on `plan` is billed at.
    pub fn price_id(&self, plan: SeatPlan) -> Result<&str, CustomerError> {
        match plan {
            SeatPlan::Premium => Ok(&self.premium),
            SeatPlan::Max => self
                .max
                .as_deref()
                .ok_or(CustomerError::PlanUnavailable(plan)),
        }
    }

    /// Which plan a subscription item's price belongs to, if any.
    pub fn plan_for_price(&self, price_id: &str) -> Option<SeatPlan> {
        if price_id == self.premium {
            Some(SeatPlan::Premium)
        } else if self.max.as_deref() == Some(price_id) {
            Some(SeatPlan::Max)
        } else {
            None
        }
    }

    /// Every price that carries a seat item.
    pub fn all(&self) -> Vec<String> {
        std::iter::once(self.premium.clone())
            .chain(self.max.clone())
            .collect()
    }
}

/// Request body for `PATCH /team/members/{member_user_id}/plan`.
#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
pub struct PatchTeamMemberPlanRequest {
    /// The plan to bill the member's seat at from now on.
    pub plan: SeatPlan,
}

/// The team member struct
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
pub struct TeamMember<'a> {
    /// The id of the team
    pub team_id: uuid::Uuid,
    /// The user id of the team member
    #[cfg_attr(feature = "axum", schema(value_type = String))]
    pub user_id: MacroUserIdStr<'a>,
    /// The role of the team member
    pub role: TeamRole,
    /// The paid plan the member's seat is billed at. Meaningful on paying
    /// and enterprise teams; free-team members carry the default.
    pub plan: SeatPlan,
}

impl TeamMember<'_> {
    /// Detach the member from any borrowed user id.
    pub fn into_owned(self) -> TeamMember<'static> {
        TeamMember {
            team_id: self.team_id,
            user_id: self.user_id.into_owned(),
            role: self.role,
            plan: self.plan,
        }
    }
}

/// A team with its members
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
pub struct TeamWithMembers {
    /// The team
    pub team: Team,
    /// The members of the team
    pub members: Vec<TeamMember<'static>>,
    /// Provider-confirmed pending seat changes, keyed by member user ID.
    /// Empty when no changes apply to this viewer; absent when the lookup fails.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduled_seat_plans: Option<HashMap<String, ScheduledSeatPlan>>,
}

/// Current and invited members for a team.
#[derive(Debug, Clone, serde::Serialize)]
pub struct TeamMembers {
    /// Current accepted members of the team.
    pub members: Vec<TeamMember<'static>>,
    /// Pending invites for the team.
    pub invited: Vec<TeamInviteDetails>,
}

/// Request body for `PATCH /team/crm`.
#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
pub struct PatchTeamCrmSettingsRequest {
    /// The desired CRM state for the team.
    pub enabled: bool,
    /// On a disabled → enabled transition, whether to backfill the CRM
    /// from members' existing email history. Ignored when disabling.
    #[serde(default = "default_crm_backfill")]
    #[cfg_attr(feature = "axum", schema(default = true))]
    pub backfill: bool,
}

fn default_crm_backfill() -> bool {
    true
}

/// Response for `PATCH /team/crm`. Reports both the resulting state
/// and whether this call changed it; for the enable-flip case it also
/// reports the backfill fan-out tallies.
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
pub struct PatchTeamCrmSettingsResponse {
    /// The resulting `crm_enabled` value after the call.
    pub enabled: bool,
    /// True if this call flipped the value (false → true or true →
    /// false). False if the team was already at the requested state.
    pub changed: bool,
    /// Number of members for whom a `PopulateCrmForUser` message was
    /// enqueued. Non-zero only on a disabled → enabled transition;
    /// per-user enqueue failures are logged and swallowed.
    pub backfill_enqueued: usize,
    /// Number of members whose enqueue failed (and was swallowed).
    /// Non-zero only on a disabled → enabled transition.
    pub backfill_failed: usize,
}

/// Detailed information about a team invite
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
pub struct TeamInviteDetails {
    /// The invite id
    pub id: uuid::Uuid,
    /// The invited email
    pub email: String,
    /// The team id
    pub team_id: uuid::Uuid,
    /// The role being invited as
    pub team_role: TeamRole,
    /// The user who sent the invitation
    pub invited_by: String,
    /// When the invite was created
    pub created_at: DateTime<Utc>,
    /// When the invite was last sent
    pub last_sent_at: DateTime<Utc>,
    /// Whether the invite creates an agent account
    pub is_agent: bool,
}

/// Deserializes an optional field while preserving explicit `null` values.
fn double_option<'de, T, D>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
where
    T: serde::Deserialize<'de>,
    D: serde::Deserializer<'de>,
{
    serde::Deserialize::deserialize(deserializer).map(Some)
}

/// Request to update a team
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
pub struct PatchTeamRequest {
    /// The new name for the team
    pub name: Option<String>,
    /// The new slug for the team. This is normalized to SCREAMING_SNAKE_CASE.
    pub slug: Option<String>,
    /// Role updates to apply to team users
    pub user_role_updates: Option<Vec<PatchTeamUserRole>>,
    /// The default link-share scope for items owned by the team. Omit to
    /// leave unchanged or pass `null` to default to link sharing off.
    #[serde(default, deserialize_with = "double_option")]
    pub default_link_share: Option<Option<LinkShare>>,
    /// The interface language for the team's members. Omit to leave
    /// unchanged or pass `null` to let each member's browser decide.
    #[serde(default, deserialize_with = "double_option")]
    pub language: Option<Option<Language>>,
}

/// 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))]
pub struct PatchTeamUserRole {
    /// The team user you are updating
    #[cfg_attr(feature = "axum", schema(value_type = String))]
    pub team_user_id: MacroUserIdStr<'static>,
    /// The new role of the team user
    pub role: TeamRole,
}

/// Team checkout session metadata
#[derive(Debug, Default, serde::Deserialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
pub struct TeamCheckoutSessionMetadata {
    /// Google Analytics client ID for conversion tracking
    pub ga_client_id: Option<String>,
    /// Meta (Facebook) browser ID from _fbp cookie
    pub fbp: Option<String>,
    /// Meta (Facebook) click ID from _fbc cookie
    pub fbc: Option<String>,
}

/// Team checkout session request
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
pub struct TeamCheckoutSessionRequest {
    /// The URL to redirect to on successful checkout
    pub success_url: String,
    /// The URL to redirect to if checkout is cancelled
    pub cancel_url: String,
    /// Optional discount/promo code to apply
    pub discount: Option<String>,
    /// Tracking metadata for conversion attribution
    #[serde(default)]
    pub metadata: TeamCheckoutSessionMetadata,
    /// The team plan the user wants to purchase for their team
    pub team_plan: TeamPlan,
}

// Teams may not enable automatic domain joining for generic domains — a
// match on e.g. `gmail.com` would auto-join complete strangers to the
// team. The list lives in its own crate so lightweight consumers (the
// onboarding flow's team suggestion) share the same judgment.
pub use generic_email_domains::{GENERIC_EMAIL_DOMAINS, is_generic_email_domain};

/// The Team struct
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
pub struct Team {
    pub(crate) id: uuid::Uuid,
    pub(crate) name: String,
    pub(crate) slug: String,
    #[cfg_attr(feature = "axum", schema(value_type = String))]
    pub(crate) owner_id: MacroUserIdStr<'static>,
    /// Whether the CRM is enabled for this team (from `team_crm_settings`;
    /// `false` when no row exists).
    pub(crate) crm_enabled: bool,
    /// The email domain new users are automatically joined to this team
    /// with, when automatic domain joining is enabled (None otherwise).
    pub(crate) auto_join_domain: Option<String>,
    /// Whether this team is on an enterprise license. Enterprise teams are
    /// billed out-of-band; membership changes skip all Stripe subscription
    /// bookkeeping (no seat counts, no subscription backfill, no paying check).
    pub(crate) enterprise: bool,
    /// Whether non-admin members may invite users to the team. Defaults to
    /// true; admins can turn it off so only admins/owners may invite.
    pub(crate) allow_non_admin_invites: bool,
    /// The default link-share scope applied when items owned by the team are
    /// shared via link without an explicit choice. `None` means link sharing
    /// is off by default. Defaults to [`LinkShare::Team`].
    pub(crate) default_link_share: Option<LinkShare>,
    /// The interface language for the team's members, unless a member picks
    /// their own. `None` lets each member's browser decide.
    pub(crate) language: Option<Language>,
}

impl Team {
    /// Creates a new Team. New teams start without an auto-join domain;
    /// it is toggled on later via the auto-join domain endpoint.
    pub fn new(
        id: uuid::Uuid,
        name: String,
        slug: String,
        owner_id: MacroUserIdStr<'static>,
        crm_enabled: bool,
        enterprise: bool,
    ) -> Self {
        Self {
            id,
            name,
            slug,
            owner_id,
            crm_enabled,
            auto_join_domain: None,
            enterprise,
            allow_non_admin_invites: true,
            default_link_share: Some(LinkShare::Team),
            language: None,
        }
    }
}

impl Team {
    /// The id of the team
    pub fn id(&self) -> &uuid::Uuid {
        &self.id
    }

    /// The name of the team
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The slug of the team
    pub fn slug(&self) -> &str {
        &self.slug
    }

    /// The owner id of the team
    pub fn owner_id(&self) -> &str {
        self.owner_id.as_ref()
    }

    /// Whether the CRM is enabled for this team
    pub fn crm_enabled(&self) -> bool {
        self.crm_enabled
    }

    /// The team's auto-join domain, when automatic domain joining is enabled
    pub fn auto_join_domain(&self) -> Option<&str> {
        self.auto_join_domain.as_deref()
    }

    /// Whether this team is on an enterprise license
    pub fn enterprise(&self) -> bool {
        self.enterprise
    }

    /// Whether non-admin members may invite users to the team
    pub fn allow_non_admin_invites(&self) -> bool {
        self.allow_non_admin_invites
    }

    /// The default link-share scope for items owned by the team, or `None`
    /// when link sharing is off by default
    pub fn default_link_share(&self) -> Option<LinkShare> {
        self.default_link_share
    }

    /// The interface language for the team's members, or `None` when each
    /// member's browser decides.
    pub fn language(&self) -> Option<Language> {
        self.language
    }
}

/// Request to create a new team
pub struct CreateTeamRequest {
    name: String,
}

impl CreateTeamRequest {
    /// Creates a new CreateTeamRequest
    pub fn new(name: String) -> Self {
        Self { name }
    }

    /// The name of the team
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// The team invite struct
#[derive(Debug, Clone)]
pub struct TeamInvite<'a> {
    /// The team id
    pub team_id: uuid::Uuid,
    /// The team invite id
    pub team_invite_id: uuid::Uuid,
    /// The email of the user
    pub email: Email<Lowercase<'a>>,
    /// Whether the invite creates an agent account
    pub is_agent: bool,
}

impl TeamInvite<'static> {
    /// Converts the team invite to a statically allocated team invite
    pub fn into_owned(&self) -> TeamInvite<'static> {
        TeamInvite {
            team_id: self.team_id,
            team_invite_id: self.team_invite_id,
            email: self.email.to_owned(),
            is_agent: self.is_agent,
        }
    }
}

/// An unanswered team invite whose reminder email is due, claimed by the
/// reminder sweep. Claiming already counted the reminder as sent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DueInviteReminder {
    /// The team invite id
    pub team_invite_id: uuid::Uuid,
    /// The team id
    pub team_id: uuid::Uuid,
    /// The team name
    pub team_name: String,
    /// The invited email
    pub email: String,
    /// The user who sent the invitation
    pub invited_by: String,
    /// Which reminder this is, starting at 1
    pub reminder_number: u8,
    /// Whether the team is an enterprise team
    pub enterprise: bool,
    /// Whether the team is in good standing
    pub paying: bool,
    /// Whether the team has a subscription
    pub has_subscription: bool,
    /// Whether the invite creates an agent account
    pub is_agent: bool,
}

/// Snapshot of a team invite before it is accepted.
#[derive(Debug, Clone)]
pub struct TeamInviteSnapshot<'a> {
    /// The invite id
    pub id: uuid::Uuid,
    /// The team id
    pub team_id: uuid::Uuid,
    /// The invited email
    pub email: Email<Lowercase<'a>>,
    /// The role being invited as
    pub team_role: TeamRole,
    /// The user who sent the invitation
    pub invited_by: MacroUserIdStr<'a>,
    /// When the invite was created
    pub created_at: DateTime<Utc>,
    /// When the invite was last sent
    pub last_sent_at: DateTime<Utc>,
    /// Whether the invite creates an agent account
    pub is_agent: bool,
}

/// Result of accepting a team invite, including the data needed to roll it back.
#[derive(Debug, Clone)]
pub struct AcceptedTeamInvite<'a> {
    /// The accepted team member
    pub member: TeamMember<'a>,
    /// Snapshot of the invite before it was accepted
    pub invite: TeamInviteSnapshot<'a>,
}

/// Errors for team
#[derive(Debug, thiserror::Error)]
pub enum TeamError {
    /// The team does not exist
    #[error("The team does not exist")]
    TeamDoesNotExist,
    /// Team member was not found
    #[error("Team member not found for team {0}")]
    TeamMemberNotFound(uuid::Uuid),
    /// The subscription does not exist
    #[error("No subscription")]
    NoSubscription,
    /// The team subscription id is invalid
    #[error("Invalid subscription id")]
    InvalidSubscriptionId,
    /// The team invite does not exist
    #[error("The team invite does not exist")]
    TeamInviteDoesNotExist,
    /// The team is not paying
    #[error("The team is not paying")]
    TeamNotPaying,
    /// Underlying entity access error
    #[error("Access error")]
    AccessError(#[from] entity_access::domain::models::AccessError),
    /// Bad request
    #[error("Bad request: {0}")]
    BadRequest(String),
    /// Storage layer error
    #[error("Storage layer error {0}")]
    StorageLayerError(#[from] anyhow::Error),
}

/// Errors for creating team
#[derive(Debug, thiserror::Error)]
pub enum CreateTeamError {
    /// The team name is invalid
    #[error("The team name is invalid: {0}")]
    InvalidTeamName(String),
    /// Storage layer error
    #[error("Storage layer error {0}")]
    StorageLayerError(#[from] anyhow::Error),
}

/// Errors for inviting users to team
#[derive(Debug, thiserror::Error)]
pub enum InviteUsersToTeamError {
    /// The team has hit its daily limit on new invites
    #[error("the team has sent too many invites today")]
    TooManyEmails,
    /// The team only allows admins to invite and the caller is not an admin
    #[error("only team admins may invite users to this team")]
    NonAdminInvitesDisabled,
    /// Underlying team error
    #[error("Underlying team error {0}")]
    TeamError(#[from] TeamError),
    /// Underlying customer error
    #[error("Underlying customer error {0}")]
    CustomerError(#[from] CustomerError),
    /// Storage layer error
    #[error("Storage layer error {0}")]
    StorageLayerError(#[from] anyhow::Error),
}

/// Errors for removing a user from a team
#[derive(Debug, thiserror::Error)]
pub enum RemoveUserFromTeamError {
    /// The team does not exist
    #[error("The team does not exist")]
    TeamDoesNotExist,
    /// The user is not in the team
    #[error("The user is not in the team")]
    UserNotInTeam,
    /// Team error
    #[error("Team error")]
    TeamError(#[from] TeamError),
    /// There is no subscription for the team
    #[error("There is no subscription for the team")]
    NoSubscription,
    /// Underlying customer error
    #[error("Underlying customer error {0}")]
    CustomerError(#[from] CustomerError),
    /// The user is the owner of the team
    #[error("Cannot remove owner")]
    CannotRemoveOwner,
    /// Storage layer error
    #[error("Storage layer error")]
    StorageLayerError(#[from] anyhow::Error),
    /// Remove roles from user error
    #[error("Remove roles from user error")]
    RemoveRolesFromUserError(#[from] UserRolesAndPermissionsError),
    /// The removed member's open seat could not be released, and the removal was rolled back.
    #[error("failed to release the removed member's open seat")]
    OpenSeatRelease(#[source] Box<dyn std::error::Error + Send + Sync>),
}

/// Arguments for creating a subscription
#[derive(Debug, Clone)]
pub struct CreateSubscriptionArgs {
    /// The customer id
    pub customer_id: stripe::CustomerId,
    /// The quantity
    pub quantity: u64,
    /// The metadata to attach to the subscription
    pub metadata: Option<HashMap<String, String>>,
}

/// Errors for customer repository
#[derive(Debug, thiserror::Error)]
pub enum CustomerError {
    /// The subscription is neither active nor trialing
    #[error("Subscription is not active")]
    SubscriptionNotActive,
    /// Invalid promotion code
    #[error("Invalid promotion code {0}")]
    InvalidPromotionCode(String),
    /// No subscription line item matched the configured Stripe price id.
    #[error("No matching line item")]
    NoMatchingLineItem,
    /// The plan has no Stripe price configured.
    #[error("The {0} plan is not available")]
    PlanUnavailable(SeatPlan),
    /// Storage layer error
    #[error("Storage layer error {0}")]
    StorageLayerError(#[from] anyhow::Error),
}

/// Errors for moving a team member between seat plans.
#[derive(Debug, thiserror::Error)]
pub enum SetTeamMemberPlanError {
    /// Seat plans only apply to paying (or enterprise) teams.
    #[error("The team has no active subscription")]
    TeamNotPaying,
    /// Underlying team error
    #[error("{0}")]
    TeamError(#[from] TeamError),
    /// Underlying customer error
    #[error("{0}")]
    CustomerError(#[from] CustomerError),
    /// Usage could not be reset for the upgraded seat.
    #[error("failed to update seat usage after a plan change")]
    UsageReset(#[source] Box<dyn std::error::Error + Send + Sync>),
    /// Roles could not be updated
    #[error("Roles error: {0}")]
    RolesError(#[from] UserRolesAndPermissionsError),
}

/// Errors for removing a team invite
#[derive(Debug, thiserror::Error)]
pub enum RemoveTeamInviteError {
    /// The user is not invited to the team
    #[error("The user is not invited to the team")]
    UserNotInTeam,
    /// The team invite does not exist
    #[error("The team invite does not exist")]
    TeamInviteDoesNotExist,
    /// Storage layer error
    #[error("Storage layer error {0}")]
    StorageLayerError(#[from] anyhow::Error),
    /// Underlying team error
    #[error("Underlying team error {0}")]
    TeamError(#[from] TeamError),
    /// Underlying customer error
    #[error("Underlying customer error {0}")]
    CustomerError(#[from] CustomerError),
}

/// Errors for deleting a team
#[derive(Debug, thiserror::Error)]
pub enum DeleteTeamError {
    /// Storage layer error
    #[error("Storage layer error")]
    StorageLayerError(#[from] anyhow::Error),
    /// Underlying team error
    #[error("Underlying team error")]
    TeamError(#[from] TeamError),
    /// Underlying customer error
    #[error("Underlying customer error {0}")]
    CustomerError(#[from] CustomerError),
    /// Remove roles from user error
    #[error("Remove roles from user error")]
    RemoveRolesFromUserError(#[from] UserRolesAndPermissionsError),
    /// The team's content could not be purged, so the team was not deleted
    #[error("unable to purge the team's content")]
    OwnedEntityCleanup(#[from] OwnedEntityCleanupError),
}

/// Errors for detaching a user from every team ahead of account deletion
#[derive(Debug, thiserror::Error)]
pub enum RemoveUserFromAllTeamsError {
    /// Underlying team error
    #[error("Underlying team error")]
    TeamError(#[from] TeamError),
    /// A team the user owns could not be deleted
    #[error("Unable to delete a team the user owns")]
    DeleteTeam(#[from] DeleteTeamError),
    /// The user could not be removed from a team they belong to
    #[error("Unable to remove the user from a team")]
    RemoveUserFromTeam(#[from] RemoveUserFromTeamError),
}

/// Errors for joining a team
#[derive(Debug, thiserror::Error)]
pub enum JoinTeamError {
    /// Storage layer error
    #[error("Storage layer error")]
    StorageLayerError(#[from] anyhow::Error),
    /// Underlying team error
    #[error("Underlying team error")]
    TeamError(#[from] TeamError),
    /// Underlying customer error
    #[error("Underlying customer error {0}")]
    CustomerError(#[from] CustomerError),
    /// The user was not invited to the team
    #[error("User not invited")]
    UserNotInvited,
    #[error("Underlying user roles and permissions error")]
    /// Underlying user roles and permissions error
    AddRolesToUserError(#[from] UserRolesAndPermissionsError),
}

/// Errors for toggling a team's auto-join domain
#[derive(Debug, thiserror::Error)]
pub enum ToggleAutoJoinDomainError {
    /// The team owner's email domain is a generic email provider domain
    #[error("Auto-join isn't available for {0}")]
    GenericDomainNotAllowed(String),
    /// Underlying team error
    #[error("Underlying team error {0}")]
    TeamError(#[from] TeamError),
}

/// Errors for adding a user to a team without an email invite: by matching
/// the team's auto-join domain, or through the team's invite link.
#[derive(Debug, thiserror::Error)]
pub enum JoinTeamDirectlyError {
    /// Underlying team error
    #[error("Underlying team error {0}")]
    TeamError(#[from] TeamError),
    /// Underlying join team error
    #[error("Underlying join team error {0}")]
    JoinTeamError(#[from] JoinTeamError),
}

/// Errors for revoking permissions for team members
#[derive(Debug, thiserror::Error)]
pub enum RevokePermissionsForTeamMembersError {
    /// Underlying team error
    #[error("Underlying team error")]
    TeamError(#[from] TeamError),
    /// Underlying user roles and permissions error
    #[error("Underlying user roles and permissions error")]
    RemoveRolesFromUserError(#[from] UserRolesAndPermissionsError),
}

/// Error when restoring permissions for team members
#[derive(Debug, thiserror::Error)]
pub enum RestorePermissionsForTeamMembersError {
    /// Provider renewal state could not be read or acknowledged.
    #[error(transparent)]
    Customer(#[from] CustomerError),
    /// 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),
    /// Initial seat upgrade usage could not be reset; retry activation.
    #[error("failed to reset usage for an activated team seat")]
    UsageReset(#[source] Box<dyn std::error::Error + Send + Sync>),
}

/// Error when creating team checkout
#[derive(Debug, thiserror::Error)]
pub enum TeamCheckoutError {
    /// Team already has a plan
    #[error("Team already has a plan")]
    TeamAlreadyHasPlanError,
    /// Missing customer id
    #[error("User does not have a customer id")]
    MissingCustomerId,
    /// Underlying team error
    #[error("{0}")]
    TeamError(#[from] TeamError),
    /// Underlying customer error
    #[error("{0}")]
    CustomerError(#[from] CustomerError),
    /// Customer already has a subscription
    #[error("User already has an active subscription")]
    AlreadySubscribed,
}

#[cfg(test)]
mod test;
/// A seat's future plan in the subscription's currently attached schedule.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ScheduledSeatPlan {
    /// Plan that takes effect at renewal.
    pub plan: SeatPlan,
    /// Provider-confirmed time when the future phase starts.
    pub effective_at: chrono::DateTime<chrono::Utc>,
}