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
use std::collections::HashMap;
use std::str::FromStr;
use crate::api::context::ApiContext;
use crate::api::user::stripe::PaidPlan;
use ai_billing::BillingService;
use ai_billing::outbound::stripe_gateway::{
PURPOSE_AI_CREDIT_RELOAD, PURPOSE_AI_OVERAGE, PURPOSE_METADATA_KEY, RELOAD_METADATA_KEY,
};
use analytics_client::{AnalyticsClient, MetaActionSource, MetaUserData};
use anyhow::Context;
use axum::{
body::Bytes,
extract::State,
http::{HeaderMap, StatusCode},
response::{IntoResponse, Json, Response},
};
use gtm_invite::domain::ports::GtmInviteService;
use macro_user_id::email::Email;
use macro_user_id::lowercased::Lowercase;
use macro_user_id::user_id::MacroUserIdStr;
use miniserde::json::Value as JsonValue;
use model::response::ErrorResponse;
use roles_and_permissions::domain::{
model::{ProductTier, SubscriptionStatus},
port::UserRolesAndPermissionsService,
};
use serde::Serialize;
use stripe_webhook::{EventObject, EventType};
use teams::domain::team_repo::TeamService;
use tracing::Instrument;
mod billing;
#[cfg(test)]
mod test;
use billing::{
BillingEvent, TeamPlanSync, handle_checkout_session_completed, period_from_timestamps,
subscription_periods, sync_personal_billing_period, sync_team_billing_period,
};
/// Extracts the previous status from the previous_attributes JSON value.
fn extract_previous_status(previous_attributes: &Option<JsonValue>) -> Option<String> {
let attrs = previous_attributes.as_ref()?;
match attrs {
JsonValue::Object(map) => match map.get("status")? {
JsonValue::String(s) => Some(s.clone()),
_ => None,
},
_ => None,
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum PaymentEventOutcome {
RevokePremiumAccess,
RestorePremiumAccess,
}
impl PaymentEventOutcome {
fn from_event_type(event_type: &EventType) -> Option<Self> {
match event_type {
EventType::InvoicePaymentFailed => Some(Self::RevokePremiumAccess),
EventType::InvoicePaymentSucceeded | EventType::InvoicePaid => {
Some(Self::RestorePremiumAccess)
}
_ => None,
}
}
fn personal_subscription_status(self) -> SubscriptionStatus {
match self {
Self::RevokePremiumAccess => SubscriptionStatus::PastDue,
Self::RestorePremiumAccess => SubscriptionStatus::Active,
}
}
fn team_subscription_status(self) -> &'static str {
match self {
Self::RevokePremiumAccess => "past_due",
Self::RestorePremiumAccess => "active",
}
}
fn is_revoke(self) -> bool {
matches!(self, Self::RevokePremiumAccess)
}
}
fn is_active_subscription_status(status: &stripe::SubscriptionStatus) -> bool {
matches!(
*status,
stripe::SubscriptionStatus::Active | stripe::SubscriptionStatus::Trialing
)
}
fn is_active_subscription_except_current(
subscription_id: &str,
status: &stripe::SubscriptionStatus,
current_subscription_id: &str,
) -> bool {
subscription_id != current_subscription_id && is_active_subscription_status(status)
}
/// The main entrypoint for all stripe webhook events handling
#[tracing::instrument(skip(ctx, headers, body))]
pub async fn handler(
State(ctx): State<ApiContext>,
headers: HeaderMap,
body: Bytes,
) -> Result<Response, Response> {
tracing::info!("stripe_webhook");
let signature = headers
.get("stripe-signature")
.and_then(|v| v.to_str().ok())
.ok_or_else(|| {
tracing::error!("missing stripe-signature header");
(
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
message: "Missing Stripe-Signature header".into(),
}),
)
.into_response()
})?;
let payload = std::str::from_utf8(&body).map_err(|e| {
tracing::error!(error=?e, "invalid UTF-8 in webhook body");
(
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
message: "Invalid webhook payload encoding".into(),
}),
)
.into_response()
})?;
// Construct and verify the event
let event = stripe_webhook::Webhook::construct_event(
payload,
signature,
ctx.stripe_webhook_secret.as_ref(),
)
.map_err(|e| {
tracing::error!(error=?e, "failed to construct stripe event");
(
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
message: "failed to construct stripe event".into(),
}),
)
.into_response()
})?;
tracing::info!(
event_id = %event.id,
event_type = ?event.type_,
event_api_version = ?event.api_version,
library_api_version = %"1.0.0-alpha.4 (targets 2025-09-30.clover)",
"processing stripe event"
);
let billing_event = BillingEvent::from_verified_payload(payload).map_err(|error| {
tracing::error!(?error, "invalid verified billing event");
(StatusCode::BAD_REQUEST, "invalid billing event").into_response()
})?;
let event_type = event.type_.clone();
let previous_attributes = event.data.previous_attributes.clone();
match event.type_ {
EventType::CustomerSubscriptionCreated
| EventType::CustomerSubscriptionUpdated
| EventType::CustomerSubscriptionDeleted
| EventType::CustomerSubscriptionPaused => {
handle_customer_subscription_event(
&ctx,
event.data.object,
event_type,
previous_attributes,
&billing_event,
)
.await
}
EventType::InvoicePaymentFailed
| EventType::InvoicePaymentSucceeded
| EventType::InvoicePaid => {
handle_payment_event(&ctx, event.data.object, event_type, &billing_event).await
}
// A credit pack paid with a delayed method (bank debit, etc.) completes
// its session unpaid and reports the money later; both events book
// through the same idempotent path.
EventType::CheckoutSessionCompleted | EventType::CheckoutSessionAsyncPaymentSucceeded => {
handle_checkout_session_completed(&ctx, event.data.object).await
}
_ => {
tracing::error!(event_type=?event_type, "unexpected event type");
Ok(())
}
}
.map_err(|e| {
tracing::error!(error=?e, "unable to handle stripe event");
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
})?;
Ok(StatusCode::OK.into_response())
}
#[tracing::instrument(skip(ctx, event_object, billing_event), err, ret)]
async fn handle_payment_event(
ctx: &ApiContext,
event_object: EventObject,
event_type: EventType,
billing_event: &BillingEvent,
) -> anyhow::Result<()> {
let invoice = match event_object {
EventObject::InvoicePaymentFailed(invoice) => invoice,
EventObject::InvoicePaymentSucceeded(invoice) => invoice,
EventObject::InvoicePaid(invoice) => invoice,
_ => {
anyhow::bail!("expected invoice payment event");
}
};
let outcome = PaymentEventOutcome::from_event_type(&event_type)
.context("expected invoice payment event type")?;
let Some(webhook_subscription_id) = invoice
.subscription
.as_ref()
.map(|subscription| subscription.id().as_str())
else {
// Our own one-off invoices: AI overage chunks and automatic credit
// reloads. Their outcome drives whether the payer keeps overage or
// automatic reloads; they never touch plan roles.
let macro_purpose = invoice
.metadata
.as_ref()
.and_then(|m| m.get(PURPOSE_METADATA_KEY))
.map(String::as_str);
let paid = !outcome.is_revoke();
if let Some(invoice_id) = invoice.id.as_ref() {
match macro_purpose {
Some(PURPOSE_AI_OVERAGE) => {
tracing::info!(
event_type = ?event_type,
invoice_id = %invoice_id,
paid,
"processing ai overage invoice event"
);
ctx.ai_billing_service
.mark_overage_invoice(invoice_id.as_str(), paid)
.await
.context("failed to record ai overage invoice outcome")?;
return Ok(());
}
Some(PURPOSE_AI_CREDIT_RELOAD) => {
tracing::info!(
event_type = ?event_type,
invoice_id = %invoice_id,
paid,
"processing ai credit reload invoice event"
);
// The reload id finds a paid invoice whose id never
// reached its row.
let reload_id = invoice
.metadata
.as_ref()
.and_then(|m| m.get(RELOAD_METADATA_KEY))
.and_then(|id| macro_uuid::string_to_uuid(id).ok());
ctx.ai_billing_service
.mark_credit_reload_invoice(invoice_id.as_str(), reload_id, paid)
.await
.context("failed to record ai credit reload invoice outcome")?;
return Ok(());
}
_ => {}
}
}
tracing::info!(
event_type = ?event_type,
invoice_id = ?invoice.id.as_ref().map(|id| id.as_str()),
"acknowledging invoice payment event without subscription"
);
return Ok(());
};
let subscription_id: stripe::SubscriptionId = webhook_subscription_id
.parse()
.context("expected subscription id")?;
let subscription =
stripe::Subscription::retrieve(&ctx.stripe_client, &subscription_id, &[]).await?;
let customer_id = subscription.customer.id();
let customer = stripe::Customer::retrieve(&ctx.stripe_client, &customer_id, &[]).await?;
tracing::trace!(customer=?customer, "retrieved customer");
if customer.deleted {
return Ok(());
}
let email = customer.email.context("expected customer email")?;
let email = Email::parse_from_str(&email)
.context("expected customer email")?
.lowercase();
let subscription_id = subscription.id.as_str();
let subscription_status = outcome.team_subscription_status();
let stripe_subscription_status = subscription.status.as_str();
let subscription_currency = Some(subscription.currency.to_string());
let subscription_value: i64 = subscription
.items
.data
.iter()
.filter_map(|item| {
let price = item.price.as_ref()?;
let unit_amount = price.unit_amount?;
let quantity = item.quantity.unwrap_or(1) as i64;
Some(unit_amount * quantity)
})
.sum();
let subscription_value = if subscription_value > 0 {
Some(subscription_value)
} else {
None
};
let ga_client_id = subscription.metadata.get("ga_client_id").cloned();
let fbp = subscription.metadata.get("fbp").cloned();
let fbc = subscription.metadata.get("fbc").cloned();
tracing::info!(
email=%email.as_ref(),
event_type = ?event_type,
outcome = ?outcome,
subscription_id,
payment_derived_subscription_status = subscription_status,
stripe_subscription_status,
ga_client_id=?ga_client_id,
fbp=?fbp,
fbc=?fbc,
"processing stripe invoice payment event"
);
let plan = subscription
.items
.data
.iter()
.filter_map(|item| item.price.as_ref())
.find_map(|price| ctx.stripe_prices.plan_for_price(price.id.as_str()));
// This subscription was fetched with the `stripe` client, which pins its
// own (older) API version where the current period still lives on the
// subscription. Webhook payloads arrive on the endpoint's newer version,
// where it moved onto the items; `handle_customer_subscription_event`
// reads it from there.
let period = period_from_timestamps(
subscription.current_period_start,
subscription.current_period_end,
);
let verified = subscription_periods(
billing_event,
&serde_json::to_value(&subscription)?,
Some(&billing_event.object),
);
if let Some(team_id) = subscription.metadata.get("team_id") {
let team_id = macro_uuid::string_to_uuid(team_id)?;
let owner = subscription
.metadata
.get("owner_id")
.and_then(|id| MacroUserIdStr::try_from(id.clone()).ok());
return handle_team_subscription_event(
ctx,
subscription_id,
subscription_status,
&team_id,
&email,
TeamPlanSync {
owner,
period,
verified,
},
SubscriptionTrackingData {
ga_client_id: ga_client_id.clone(),
fbp: fbp.clone(),
fbc: fbc.clone(),
email: email.as_ref().to_string(),
value_cents: subscription_value,
currency: subscription_currency,
status: subscription_status.to_string(),
is_new: false,
team_id: Some(team_id),
},
)
.await;
}
if outcome.is_revoke() {
let mut list_subscriptions = stripe::ListSubscriptions::new();
list_subscriptions.customer = Some(customer_id.clone());
list_subscriptions.limit = Some(10);
let all_subscriptions =
stripe::Subscription::list(&ctx.stripe_client, &list_subscriptions).await?;
let has_other_active_personal_subscription =
all_subscriptions.data.iter().any(|subscription| {
!subscription.metadata.contains_key("team_id")
&& is_active_subscription_except_current(
subscription.id.as_str(),
&subscription.status,
subscription_id,
)
});
if has_other_active_personal_subscription {
tracing::info!(
customer_id = %customer_id,
subscription_id,
"invoice payment failed but user still has another active subscription - not revoking permissions"
);
return Ok(());
}
}
ctx.user_roles_and_permissions_service
.update_user_roles_and_permissions_for_subscription(
email.clone(),
outcome.personal_subscription_status(),
plan.map(PaidPlan::product_tier)
.unwrap_or(ProductTier::Opus),
)
.await?;
sync_personal_billing_period(ctx, &email, period, verified).await?;
Ok(())
}
#[tracing::instrument(skip(ctx, event_object, previous_attributes, billing_event), err, ret)]
async fn handle_customer_subscription_event(
ctx: &ApiContext,
event_object: EventObject,
event_type: EventType,
previous_attributes: Option<JsonValue>,
billing_event: &BillingEvent,
) -> anyhow::Result<()> {
let subscription = match event_object {
EventObject::CustomerSubscriptionCreated(subscription) => subscription,
EventObject::CustomerSubscriptionUpdated(subscription) => subscription,
EventObject::CustomerSubscriptionDeleted(subscription) => subscription,
EventObject::CustomerSubscriptionPaused(subscription) => subscription,
_ => {
anyhow::bail!("expected subscription");
}
};
let current_status = subscription.status.as_str();
// Skip processing if the subscription is still incomplete
if current_status == "incomplete" {
tracing::info!(
current_status = current_status,
"skipping incomplete subscription"
);
return Ok(());
}
// For subscription.updated events, check if we're transitioning from incomplete
// to active/trialing. If so, this is effectively a "new" subscription activation.
let previous_status = extract_previous_status(&previous_attributes);
tracing::info!(
event_type = ?event_type,
current_status = current_status,
previous_status = ?previous_status,
previous_attributes_raw = ?previous_attributes,
"subscription event status details"
);
let is_transition_from_incomplete =
matches!(event_type, EventType::CustomerSubscriptionUpdated)
&& previous_status.as_deref() == Some("incomplete")
&& matches!(current_status, "active" | "trialing");
if is_transition_from_incomplete {
tracing::info!(
previous_status = ?previous_status,
current_status = current_status,
"subscription transitioned from incomplete to active state"
);
} else if matches!(event_type, EventType::CustomerSubscriptionUpdated) {
tracing::info!(
previous_status = ?previous_status,
current_status = current_status,
is_transition_from_incomplete = is_transition_from_incomplete,
"subscription update did not qualify as incomplete transition"
);
}
// Stripe CustomerId and subscription CustomerId are not the same type...
let customer_id = subscription
.customer
.into_id()
.parse()
.context("expected customer id")?;
let customer = stripe::Customer::retrieve(&ctx.stripe_client, &customer_id, &[]).await?;
tracing::trace!(customer=?customer, "retrieved customer");
if customer.deleted {
return Ok(());
}
let email = customer.email.context("expected customer email")?;
let email = Email::parse_from_str(&email)
.context("expected customer email")?
.lowercase();
let subscription_id = subscription.id.as_str();
let subscription_status = subscription.status.as_str();
// Extract subscription value and currency for analytics
let subscription_currency = Some(subscription.currency.to_string());
let subscription_value: i64 = subscription
.items
.data
.iter()
.filter_map(|item| {
let unit_amount = item.price.unit_amount?;
let quantity = item.quantity.unwrap_or(1) as i64;
Some(unit_amount * quantity)
})
.sum();
let subscription_value = if subscription_value > 0 {
Some(subscription_value)
} else {
None
};
// Extract tracking IDs from subscription metadata for analytics
let ga_client_id = subscription.metadata.get("ga_client_id").cloned();
let fbp = subscription.metadata.get("fbp").cloned();
let fbc = subscription.metadata.get("fbc").cloned();
tracing::info!(
email=%email.as_ref(),
subscription_id,
subscription_status,
ga_client_id=?ga_client_id,
fbp=?fbp,
fbc=?fbc,
"processing stripe subscription"
);
// Determine if this should be treated as a new subscription for analytics purposes.
// A subscription is "new" if it's a CustomerSubscriptionCreated event OR if it
// transitioned from incomplete to active/trialing (meaning payment succeeded).
let is_new_subscription = matches!(event_type, EventType::CustomerSubscriptionCreated)
|| is_transition_from_incomplete;
// An account that signed up through a GTM invite link converted the moment
// its subscription — personal or team — is live. Tracking only: never
// fails the webhook.
if matches!(subscription_status, "active" | "trialing") {
mark_gtm_invite_converted(ctx, &email, subscription_id).await;
}
// For a personal subscription the seat price says which plan this is (a
// team subscription may carry one item per plan; its members' plans are
// recorded on the team). The first item carries the current period on
// this API version.
let plan = subscription
.items
.data
.iter()
.find_map(|item| ctx.stripe_prices.plan_for_price(item.price.id.as_str()));
let period = subscription.items.data.first().and_then(|item| {
period_from_timestamps(item.current_period_start, item.current_period_end)
});
let verified = subscription_periods(billing_event, &billing_event.object, None);
// Get subscription metadata, if this is a team subscription then we need to handle it
// separately.
if let Some(team_id) = subscription.metadata.get("team_id") {
let team_id = macro_uuid::string_to_uuid(team_id)?;
let owner = subscription
.metadata
.get("owner_id")
.and_then(|id| MacroUserIdStr::try_from(id.clone()).ok());
// We need to handle team subscriptions differently than regular subscriptions.
return handle_team_subscription_event(
ctx,
subscription_id,
subscription_status,
&team_id,
&email,
TeamPlanSync {
owner,
period,
verified,
},
SubscriptionTrackingData {
ga_client_id: ga_client_id.clone(),
fbp: fbp.clone(),
fbc: fbc.clone(),
email: email.as_ref().to_string(),
value_cents: subscription_value,
currency: subscription_currency,
status: subscription_status.to_string(),
is_new: is_new_subscription,
team_id: Some(team_id),
},
)
.await;
}
// Check for duplicate subscriptions
let mut list_subscriptions = stripe::ListSubscriptions::new();
list_subscriptions.customer = Some(customer_id.clone());
list_subscriptions.limit = Some(10);
let all_subscriptions =
stripe::Subscription::list(&ctx.stripe_client, &list_subscriptions).await?;
let active_subscriptions: Vec<_> = all_subscriptions
.data
.iter()
.filter(|sub| is_active_subscription_status(&sub.status))
.collect();
// If this is a new active/trialing subscription and there are multiple active subscriptions,
// cancel the newer one (keep the oldest)
if matches!(subscription_status, "active" | "trialing") && active_subscriptions.len() > 1 {
// Find the oldest subscription by created timestamp
let oldest_subscription = active_subscriptions
.iter()
.min_by_key(|sub| sub.created)
.map(|sub| sub.id.as_str());
// If the current subscription is not the oldest, cancel it
if oldest_subscription != Some(subscription_id) {
tracing::warn!(
customer_id = %customer_id,
subscription_id = subscription_id,
oldest_subscription_id = ?oldest_subscription,
total_active = active_subscriptions.len(),
"Cancelling duplicate subscription - keeping oldest"
);
let sub_id: stripe::SubscriptionId = subscription_id.parse()?;
stripe::Subscription::cancel(
&ctx.stripe_client,
&sub_id,
stripe::CancelSubscription::default(),
)
.await?;
// Return early - don't update permissions for a cancelled duplicate
return Ok(());
}
}
// If subscription is being deleted/canceled, check if there's another active subscription
// before revoking permissions
if subscription_status == "canceled" && !active_subscriptions.is_empty() {
tracing::info!(
customer_id = %customer_id,
subscription_id = subscription_id,
remaining_active = active_subscriptions.len(),
"Subscription deleted but user still has active subscription(s) - not revoking permissions"
);
return Ok(());
}
if subscription_status == "trialing" {
// set has_trialed in macro_user table
macro_db_client::user::patch::update_macro_user_has_trialed(&ctx.db, &email, true).await?;
// Add has_trialed: true to stripe customer metadata
let mut params = stripe::UpdateCustomer::new();
let mut metadata = HashMap::new();
metadata.insert("has_trialed".to_string(), "true".to_string());
params.metadata = Some(metadata);
stripe::Customer::update(&ctx.stripe_client, &customer_id, params).await?;
tracing::info!(
customer_id=%customer_id,
"updated customer metadata with has_trialed=true"
);
}
// Unknown prices (legacy or manually created subscriptions) keep the
// Premium entitlements.
let product_tier = plan
.map(PaidPlan::product_tier)
.unwrap_or(ProductTier::Opus);
ctx.user_roles_and_permissions_service
.update_user_roles_and_permissions_for_subscription(
email.clone(),
subscription_status.try_into()?,
product_tier,
)
.await?;
sync_personal_billing_period(ctx, &email, period, verified).await?;
if let Some(change) =
billing::personal_plan_change(billing_event, &ctx.stripe_prices, is_new_subscription)
{
let user = MacroUserIdStr::try_from_email(email.as_ref())?;
ctx.ai_billing_service
.change_plan(&user, change)
.await
.context("failed to reset upgraded personal seat usage")?;
}
// Track conversion events to GA and Meta (fire-and-forget)
let subscription_id = stripe::SubscriptionId::from_str(subscription_id).unwrap();
track_stripe_subscription(
ctx.analytics_client.clone(),
&subscription_id,
SubscriptionTrackingData {
ga_client_id,
fbp,
fbc,
email: email.as_ref().to_string(),
value_cents: subscription_value,
currency: subscription_currency,
status: subscription_status.to_string(),
is_new: is_new_subscription,
team_id: None,
},
);
Ok(())
}
/// Records the subscriber's redeemed GTM invite link, if they hold one, as
/// converted into this subscription.
#[tracing::instrument(skip(ctx, email), fields(subscription_id))]
async fn mark_gtm_invite_converted(
ctx: &ApiContext,
email: &Email<macro_user_id::lowercased::Lowercase<'_>>,
subscription_id: &str,
) {
let user_id = match macro_user_id::user_id::MacroUserIdStr::try_from_email(email.as_ref()) {
Ok(user_id) => user_id,
Err(e) => {
tracing::error!(error=?e, "customer email is not a valid macro user id");
return;
}
};
match ctx
.gtm_invite_service
.mark_converted(&user_id, subscription_id)
.await
{
Ok(true) => tracing::info!("marked GTM invite link as converted"),
Ok(false) => {}
Err(e) => tracing::error!(error=?e, "failed to mark GTM invite link as converted"),
}
}
/// Handles team subscription events.
/// NOTE: We use strs here because there is a mismatch between stripe crate and
/// stripe_webhook crate for these types. *sigh*
#[tracing::instrument(skip(ctx, tracking_data), err, ret)]
async fn handle_team_subscription_event<'a>(
ctx: &ApiContext,
subscription_id: &str,
subscription_status: &str,
team_id: &uuid::Uuid,
email: &Email<Lowercase<'a>>,
plan_sync: TeamPlanSync,
tracking_data: SubscriptionTrackingData,
) -> anyhow::Result<()> {
tracing::trace!("handling team subscription");
if subscription_status == "trialing" {
// set has_trialed in macro_user table
macro_db_client::user::patch::update_macro_user_has_trialed(&ctx.db, email, true).await?;
}
billing::complete_subscription_webhook(
billing::sync_team_usage_policy(ctx, &plan_sync),
async {
let subscription_id = stripe::SubscriptionId::from_str(subscription_id).unwrap();
ctx.teams_service
.patch_team_subscription_id(team_id, &subscription_id)
.await?;
match subscription_status {
"active" | "trialing" => {
// Restore stamps every member (owner included) with the team
// subscriber role and the tier role of their own seat's plan.
ctx.teams_service
.restore_permissions_for_team_members(
team_id,
tracking_data
.is_new
.then(|| {
plan_sync.verified.first().map(|facts| {
teams::domain::open_seat_release::SubscriptionStart {
at: facts.event_at,
period_start: facts.period.start,
period_end: facts.period.end,
}
})
})
.flatten(),
)
.await?;
sync_team_billing_period(ctx, &plan_sync).await?;
ctx.teams_service
.patch_team_payment_status(team_id, true)
.await?;
track_stripe_subscription(
ctx.analytics_client.clone(),
&subscription_id,
tracking_data,
);
Ok(())
}
"canceled" | "incomplete" | "incomplete_expired" | "past_due" | "paused"
| "unpaid" => {
ctx.teams_service
.revoke_permissions_for_team_members(team_id)
.await?;
sync_team_billing_period(ctx, &plan_sync).await?;
ctx.teams_service
.patch_team_payment_status(team_id, false)
.await?;
track_stripe_subscription(
ctx.analytics_client.clone(),
&subscription_id,
SubscriptionTrackingData {
is_new: false,
..tracking_data
},
);
Ok(())
}
_ => {
anyhow::bail!("unexpected subscription status for team subscription");
}
}
},
)
.await
}
#[derive(Debug, Clone, Serialize)]
struct SubscriptionEvent {
transaction_id: String,
value: f64,
currency: String,
}
/// PostHog properties for a subscription event. GA and Meta get the bare
/// [`SubscriptionEvent`]; only PostHog receives the team and its group.
#[derive(Debug, Serialize)]
struct PostHogSubscriptionEvent<'a> {
#[serde(flatten)]
event: &'a SubscriptionEvent,
#[serde(skip_serializing_if = "Option::is_none")]
team_id: Option<uuid::Uuid>,
#[serde(rename = "$groups", skip_serializing_if = "Option::is_none")]
groups: Option<PostHogTeamGroup>,
}
/// Attributes the event to the team in PostHog group analytics.
#[derive(Debug, Serialize)]
struct PostHogTeamGroup {
team: uuid::Uuid,
}
#[derive(Debug, Clone)]
struct SubscriptionTrackingData {
ga_client_id: Option<String>,
fbp: Option<String>,
fbc: Option<String>,
email: String,
value_cents: Option<i64>,
currency: Option<String>,
status: String,
is_new: bool,
/// Set for team subscriptions (the `team_id` subscription metadata).
team_id: Option<uuid::Uuid>,
}
/// Tracks a Stripe subscription event to GA and Meta (fire-and-forget).
#[tracing::instrument(skip(client, data), fields(subscription_id, email = %data.email, status = %data.status, is_new = data.is_new))]
fn track_stripe_subscription(
client: std::sync::Arc<AnalyticsClient>,
subscription_id: &stripe::SubscriptionId,
data: SubscriptionTrackingData,
) {
let Some(value_cents) = data.value_cents else {
tracing::warn!("skipping analytics tracking: missing value_cents");
return;
};
let Some(currency) = data.currency else {
tracing::warn!("skipping analytics tracking: missing currency");
return;
};
// Create a child span for the spawned task, linked to the current span
let task_span = tracing::info_span!(
parent: tracing::Span::current(),
"track_stripe_subscription_task"
);
let subscription_id = subscription_id.to_string();
tracing::info!(
value_cents = value_cents,
currency = %currency,
is_new = data.is_new,
status = %data.status,
"spawning analytics tracking task"
);
tokio::spawn(
async move {
let event = SubscriptionEvent {
transaction_id: subscription_id.clone(),
value: value_cents as f64 / 100.0,
currency: currency.to_uppercase(),
};
let user_data = MetaUserData {
email: Some(data.email.clone()),
fbp: data.fbp.clone(),
fbc: data.fbc.clone(),
..MetaUserData::default()
};
let event_id = Some(subscription_id.as_str());
let posthog_event = PostHogSubscriptionEvent {
event: &event,
team_id: data.team_id,
groups: data.team_id.map(|team| PostHogTeamGroup { team }),
};
// PostHog distinct id must be the "macro|{email}" id the app
// identifies with; a bare email lands events on orphaned person
// profiles disconnected from product usage. This only links to the
// right person when the Stripe customer email matches the Macro
// account email — if a customer's billing email diverges from
// their login email, the event lands on an orphaned profile.
let posthog_distinct_id = MacroUserIdStr::try_from_email(&data.email)
.map(String::from)
.unwrap_or_else(|e| {
tracing::warn!(error = ?e, "failed to build macro user id for PostHog; falling back to email");
data.email.clone()
});
tracing::info!(
status = %data.status,
is_new = data.is_new,
ga_client_id = ?data.ga_client_id,
"analytics tracking task started"
);
match (data.status.as_str(), data.is_new) {
("active" | "trialing", true) => {
if let Some(ref ga_client_id) = data.ga_client_id {
let _ = client.track_ga(ga_client_id, "purchase", &event)
.await
.inspect_err(|e| tracing::warn!(error = ?e, "failed to track GA purchase event"));
} else {
tracing::debug!("skipping GA purchase tracking: no ga_client_id");
}
let _ = client
.track_meta(
"Purchase",
&user_data,
MetaActionSource::Website,
event_id,
&event,
)
.await
.inspect_err(|e| tracing::warn!(error = ?e, "failed to track Meta purchase event"));
let _ = client
.track_posthog(&posthog_distinct_id, "subscription_created", &posthog_event)
.await
.inspect_err(|e| tracing::warn!(error = ?e, "failed to track PostHog subscription_created event"));
}
("canceled", _) => {
if let Some(ref ga_client_id) = data.ga_client_id {
let _ = client.track_ga(ga_client_id, "refund", &event)
.await
.inspect_err(|e| tracing::warn!(error = ?e, "failed to track GA refund event"));
} else {
tracing::debug!("skipping GA refund tracking: no ga_client_id");
}
let _ = client
.track_meta(
"CancelSubscription",
&user_data,
MetaActionSource::Website,
event_id,
&event,
)
.await
.inspect_err(|e| tracing::warn!(error = ?e, "failed to track Meta cancel event"));
let _ = client
.track_posthog(&posthog_distinct_id, "subscription_canceled", &posthog_event)
.await
.inspect_err(|e| tracing::warn!(error = ?e, "failed to track PostHog subscription_canceled event"));
}
_ => {
tracing::debug!(status = %data.status, is_new = data.is_new, "skipping analytics tracking: unhandled status/is_new combination");
}
}
}
.instrument(task_span),
);
}