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(billing): bill Max immediately instead of inheriting a Pro trial (#8848)

Jacob Beckermanc5ec4792d7e8
diff --git a/apps/web/src/features/paywall/PaywallComponent.tsx b/apps/web/src/features/paywall/PaywallComponent.tsx
index 7a0a0f0824..d2b3e4df01 100644
--- a/apps/web/src/features/paywall/PaywallComponent.tsx
+++ b/apps/web/src/features/paywall/PaywallComponent.tsx
@@ -3,7 +3,7 @@ import { useHasPaidAccess } from '@core/auth';
import { enableAiUsageBilling } from '@core/constant/featureFlags';
import { type PaywallKey, PaywallMessages } from '@core/constant/PaywallState';
import { useSettingsState } from '@core/constant/SettingsState';
-import { useUserId } from '@core/context/user';
+import { useLicenseStatus, useUserId } from '@core/context/user';
import { fireAndForget } from '@core/util/fireAndForget';
import {
useAiBillingSummaryQuery,
@@ -23,6 +23,7 @@ export interface PaywallProps {
const PaywallComponent = (props: PaywallProps) => {
const { openSettings } = useSettingsState();
const hasPaid = useHasPaidAccess();
+ const licenseStatus = useLicenseStatus();
const userId = useUserId();
const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);
const team = useCurrentTeamQuery();
@@ -59,6 +60,7 @@ const PaywallComponent = (props: PaywallProps) => {
trialEligibility.isSuccess && queryReadyGate(trialEligibility)
? trialEligibility.data.eligible
: undefined,
+ trialing: licenseStatus() === 'trialing',
});
};
diff --git a/apps/web/src/features/settings/Billing.test.tsx b/apps/web/src/features/settings/Billing.test.tsx
index c8b658e566..98224138a5 100644
--- a/apps/web/src/features/settings/Billing.test.tsx
+++ b/apps/web/src/features/settings/Billing.test.tsx
@@ -29,6 +29,7 @@ vi.mock('@core/constant/featureFlags', () => ({
vi.mock('@core/context/user', () => ({
usePermissions: () => () => ['write:stripe_subscription'],
useUserId: () => () => 'macro|[email protected]',
+ useLicenseStatus: () => () => 'inactive',
}));
vi.mock('@queries/team/teams', () => ({
useCurrentTeamQuery: () => ({
diff --git a/apps/web/src/features/settings/Billing.tsx b/apps/web/src/features/settings/Billing.tsx
index 5aac28e3bc..38f63ef6b9 100644
--- a/apps/web/src/features/settings/Billing.tsx
+++ b/apps/web/src/features/settings/Billing.tsx
@@ -4,7 +4,11 @@ import { useHasPaidAccess } from '@core/auth';
import { toast } from '@core/component/Toast/Toast';
import { enableAiUsageBilling, LOCAL_ONLY } from '@core/constant/featureFlags';
import { PERMISSION_IDS } from '@core/constant/permissions';
-import { usePermissions, useUserId } from '@core/context/user';
+import {
+ useLicenseStatus,
+ usePermissions,
+ useUserId,
+} from '@core/context/user';
import { fireAndForget } from '@core/util/fireAndForget';
import { lazyNamed } from '@core/util/lazyNamed';
import {
@@ -47,6 +51,7 @@ function LiveBilling(props: { controls?: JSX.Element }) {
const permissions = usePermissions();
const analytics = useAnalytics();
const hasPaid = useHasPaidAccess();
+ const licenseStatus = useLicenseStatus();
const userId = useUserId();
const team = useCurrentTeamQuery();
const summary = useAiBillingSummaryQuery();
@@ -112,6 +117,7 @@ function LiveBilling(props: { controls?: JSX.Element }) {
trialEligibility.isSuccess && queryReadyGate(trialEligibility)
? trialEligibility.data.eligible
: undefined,
+ trialing: licenseStatus() === 'trialing',
});
const handleCheckout = async (plan: PaidPlan) => {
diff --git a/apps/web/src/features/settings/components/billing-plan-card.tsx b/apps/web/src/features/settings/components/billing-plan-card.tsx
index 5962da00a3..e3676ecbf2 100644
--- a/apps/web/src/features/settings/components/billing-plan-card.tsx
+++ b/apps/web/src/features/settings/components/billing-plan-card.tsx
@@ -47,7 +47,12 @@ export function BillingPlanCard(props: {
plan: PaidPlanTier;
state: Pick<
BillingState,
- 'hasPaid' | 'teamRole' | 'aiUsageEnabled' | 'pending' | 'trialEligible'
+ | 'hasPaid'
+ | 'teamRole'
+ | 'aiUsageEnabled'
+ | 'pending'
+ | 'trialEligible'
+ | 'trialing'
>;
onSelectPlan?: (plan: PaidPlanTier) => void;
}) {
@@ -122,7 +127,9 @@ export function BillingPlanCard(props: {
>
<p class="text-xs text-ink-extra-muted">
<Show when={props.plan === 'max'}>
- Prorated for the rest of this period.
+ {props.state.trialing
+ ? 'Charged today. The Pro trial ends.'
+ : 'Prorated for the rest of this period.'}
</Show>
<Show when={props.state.teamRole === 'owner'}>
{' '}
diff --git a/apps/web/src/features/settings/core/billing-state.ts b/apps/web/src/features/settings/core/billing-state.ts
index 6f947cc6f9..7474bfff5a 100644
--- a/apps/web/src/features/settings/core/billing-state.ts
+++ b/apps/web/src/features/settings/core/billing-state.ts
@@ -12,6 +12,8 @@ export type BillingInput = {
/** Undefined until the server confirms eligibility; never advertise a trial then. */
trialEligible?: boolean;
existingSubscription?: boolean;
+ /** The current paid license is still the Pro trial. Max does not inherit it. */
+ trialing?: boolean;
};
/** The billing summary's tier wins; without it, paid access implies Pro. */
diff --git a/crates/teams/AGENTS.md b/crates/teams/AGENTS.md
index dceee9d416..b4ba498397 100644
--- a/crates/teams/AGENTS.md
+++ b/crates/teams/AGENTS.md
@@ -51,6 +51,13 @@ event contract (schema, sanitization, delivery semantics).
- Repair missed teammate DMs: `just crates/teams/backfill_teammate_dms_local`
(see README's "Delivery semantics" for when this is needed).
+## Gotchas
+
+- A trialing subscription that gains its first Max seat ends the trial and
+ starts a new billing cycle immediately. Every other seat change keeps the
+ trial, including on a subscription already trialing on Max, so its scheduled
+ downgrades still apply at the trial's end.
+
## Checks
- `cargo test -p teams` (`SQLX_OFFLINE` unset).
diff --git a/crates/teams/src/domain/customer_repo.rs b/crates/teams/src/domain/customer_repo.rs
index 50df411530..6cf858bf91 100644
--- a/crates/teams/src/domain/customer_repo.rs
+++ b/crates/teams/src/domain/customer_repo.rs
@@ -100,10 +100,15 @@ pub trait CustomerRepository: Clone + Send + Sync + 'static {
/// Cancel any pending downgrade and replace the personal price atomically with
/// respect to other provider mutations, invoicing proration immediately.
+ ///
+ /// When `end_trial` is set, end an in-progress trial and start the new plan's
+ /// billing cycle now. A Max upgrade sets this while the subscription is still
+ /// trialing so the trial cannot move onto the Max price.
fn upgrade_personal_plan(
&self,
subscription: &stripe::SubscriptionId,
plan: SeatPlan,
+ end_trial: bool,
) -> impl Future<Output = Result<(), CustomerError>> + Send;
/// Member plans whose scheduled phase has actually started at the provider.
diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rs
index b42836f33f..7ca0dd998c 100644
--- a/crates/teams/src/domain/team_service/test.rs
+++ b/crates/teams/src/domain/team_service/test.rs
@@ -1078,6 +1078,7 @@ impl CustomerRepository for MockCustomerRepository {
&self,
_: &stripe::SubscriptionId,
_: SeatPlan,
+ _: bool,
) -> Result<(), CustomerError> {
Ok(())
}
diff --git a/crates/teams/src/outbound/customer_repo.rs b/crates/teams/src/outbound/customer_repo.rs
index 30dfd067e9..63e55cb806 100644
--- a/crates/teams/src/outbound/customer_repo.rs
+++ b/crates/teams/src/outbound/customer_repo.rs
@@ -316,13 +316,17 @@ impl CustomerRepositoryImpl {
let subscription = stripe::Subscription::retrieve(&self.client, subscription_id, &[])
.await
.map_err(storage)?;
+ let end_trial = subscription.status == stripe::SubscriptionStatus::Trialing
+ && self.adds_first_max_seat(&subscription, &items)?;
if let Some(schedule_id) = subscription.schedule.as_ref().map(|s| s.id()) {
let schedule = stripe::SubscriptionSchedule::retrieve(&self.client, &schedule_id, &[])
.await
.map_err(storage)?;
require_owned_schedule(&schedule)?;
let pending = self.pending_changes(&schedule, &subscription).await?;
- if pending.at > subscription.current_period_start {
+ // A Pro trial gaining Max ends now. With no Max seat before, no seat
+ // is waiting to downgrade, so release the schedule and bill directly.
+ if !end_trial && pending.at > subscription.current_period_start {
let current = current_phase(&schedule, &subscription)?;
let mut phase = phase_parameters(current)?;
let mut quantities = subscription
@@ -364,13 +368,19 @@ impl CustomerRepositoryImpl {
// an immediate upgrade; acknowledging old metadata cannot undo it.
self.release_schedule(&schedule.id).await?;
}
- let update_params = UpdateSubscription {
+ let mut update_params = UpdateSubscription {
items: Some(items),
proration_behavior: Some(
stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice,
),
..Default::default()
};
+ if end_trial {
+ // A trial has no paid remainder to prorate. Reset the cycle so Max
+ // bills a full period today instead of inheriting the trial end.
+ update_params.trial_end = Some(stripe::Scheduled::now());
+ update_params.billing_cycle_anchor = Some(stripe::SubscriptionBillingCycleAnchor::Now);
+ }
stripe::Subscription::update(&self.client, subscription_id, update_params)
.await
@@ -378,6 +388,59 @@ impl CustomerRepositoryImpl {
Ok(())
}
+
+ /// Whether the seat update gives a subscription without Max seats its first
+ /// one. A subscription already trialing on Max keeps its trial terms, and
+ /// its scheduled downgrades, through other seat changes.
+ fn adds_first_max_seat(
+ &self,
+ subscription: &stripe::Subscription,
+ items: &[UpdateSubscriptionItems],
+ ) -> Result<bool, CustomerError> {
+ let Ok(max) = self.seat_prices.price_id(SeatPlan::Max) else {
+ return Ok(false);
+ };
+ let max_items: Vec<_> = subscription
+ .items
+ .data
+ .iter()
+ .filter(|item| {
+ item.price
+ .as_ref()
+ .is_some_and(|price| price.id.as_str() == max)
+ })
+ .collect();
+ let mut quantity = max_items
+ .iter()
+ .map(|item| item.quantity.unwrap_or(1))
+ .sum::<u64>();
+ if quantity > 0 {
+ return Ok(false);
+ }
+ for update in items {
+ if let Some(price) = &update.price {
+ if price.as_str() == max {
+ quantity = quantity.saturating_add(update.quantity.unwrap_or(1));
+ }
+ continue;
+ }
+ let Some(id) = &update.id else {
+ continue;
+ };
+ let Some(existing) = max_items.iter().find(|item| item.id.as_str() == id) else {
+ continue;
+ };
+ quantity = quantity.saturating_sub(existing.quantity.unwrap_or(1));
+ if update.deleted != Some(true) {
+ quantity = quantity.saturating_add(
+ update
+ .quantity
+ .unwrap_or_else(|| existing.quantity.unwrap_or(1)),
+ );
+ }
+ }
+ Ok(quantity > 0)
+ }
}
impl CustomerRepository for CustomerRepositoryImpl {
@@ -569,6 +632,7 @@ impl CustomerRepository for CustomerRepositoryImpl {
&self,
id: &stripe::SubscriptionId,
plan: SeatPlan,
+ end_trial: bool,
) -> Result<(), CustomerError> {
let _billing = self.subscription_guard(id).await?;
let subscription = stripe::Subscription::retrieve(&self.client, id, &[])
@@ -594,11 +658,16 @@ impl CustomerRepository for CustomerRepositoryImpl {
.is_some_and(|p| self.seat_prices.plan_for_price(p.id.as_str()).is_some())
})
.ok_or(CustomerError::NoMatchingLineItem)?;
- let params = UpdateSubscription {
+ let end_trial = end_trial && subscription.status == stripe::SubscriptionStatus::Trialing;
+ let mut params = UpdateSubscription {
items: Some(vec![UpdateSubscriptionItems { id: Some(item.id.to_string()), price: Some(self.seat_prices.price_id(plan)?.to_string()), ..Default::default() }]),
metadata: Some(HashMap::from([("macro_plan_change_at".to_string(), chrono::Utc::now().to_rfc3339()), (APPLIED_KEY.to_string(), String::new())])),
proration_behavior: Some(stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice), ..Default::default()
};
+ if end_trial {
+ params.trial_end = Some(stripe::Scheduled::now());
+ params.billing_cycle_anchor = Some(stripe::SubscriptionBillingCycleAnchor::Now);
+ }
stripe::Subscription::update(&self.client, id, params)
.await
.map_err(storage)?;
diff --git a/crates/teams/src/outbound/customer_repo/test.rs b/crates/teams/src/outbound/customer_repo/test.rs
index 85e31a71d6..987062e1ce 100644
--- a/crates/teams/src/outbound/customer_repo/test.rs
+++ b/crates/teams/src/outbound/customer_repo/test.rs
@@ -530,7 +530,7 @@ async fn personal_upgrade_replaces_the_existing_item_and_invoices_proration(pool
.await;
mount(&server, "POST", "/v1/subscriptions/sub_team", &sub, 1).await;
repo(&server, pool)
- .upgrade_personal_plan(&sub.id, SeatPlan::Max)
+ .upgrade_personal_plan(&sub.id, SeatPlan::Max, false)
.await
.unwrap();
let requests = server.received_requests().await.unwrap();
@@ -543,6 +543,8 @@ async fn personal_upgrade_replaces_the_existing_item_and_invoices_proration(pool
assert_eq!(update["items[0][id]"], "si_personal");
assert_eq!(update["items[0][price]"], "price_max");
assert_eq!(update["proration_behavior"], "always_invoice");
+ assert!(update.get("trial_end").is_none());
+ assert!(update.get("billing_cycle_anchor").is_none());
let release = requests
.iter()
.position(|request| request.url.path().ends_with("/release"))
@@ -559,6 +561,170 @@ async fn personal_upgrade_replaces_the_existing_item_and_invoices_proration(pool
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn pro_trial_upgrade_to_max_ends_the_trial_and_bills_now(pool: sqlx::PgPool) {
+ let server = MockServer::start().await;
+ let mut sub = subscription();
+ sub.status = stripe::SubscriptionStatus::Trialing;
+ sub.items.data = vec![item("si_personal", "price_pro", 1)];
+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;
+ mount(&server, "POST", "/v1/subscriptions/sub_team", &sub, 1).await;
+ repo(&server, pool)
+ .upgrade_personal_plan(&sub.id, SeatPlan::Max, true)
+ .await
+ .unwrap();
+ let requests = server.received_requests().await.unwrap();
+ let update = form(
+ requests
+ .iter()
+ .find(|r| r.method.as_str() == "POST" && r.url.path() == "/v1/subscriptions/sub_team")
+ .unwrap(),
+ );
+ assert_eq!(update["items[0][price]"], "price_max");
+ assert_eq!(update["trial_end"], "now");
+ assert_eq!(update["billing_cycle_anchor"], "now");
+ assert_eq!(update["proration_behavior"], "always_invoice");
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn moving_a_trial_seat_to_max_ends_the_trial(pool: sqlx::PgPool) {
+ let server = MockServer::start().await;
+ let mut sub = subscription();
+ sub.status = stripe::SubscriptionStatus::Trialing;
+ sub.items.data = vec![item("si_pro", "price_pro", 1)];
+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;
+ mount(&server, "POST", "/v1/subscriptions/sub_team", &sub, 1).await;
+ repo(&server, pool)
+ .move_seat(&sub.id, SeatPlan::Premium, SeatPlan::Max)
+ .await
+ .unwrap();
+ let requests = server.received_requests().await.unwrap();
+ let update = form(
+ requests
+ .iter()
+ .find(|r| r.method.as_str() == "POST" && r.url.path() == "/v1/subscriptions/sub_team")
+ .unwrap(),
+ );
+ assert_eq!(update["trial_end"], "now");
+ assert_eq!(update["billing_cycle_anchor"], "now");
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn adding_a_pro_seat_during_a_trial_keeps_the_trial(pool: sqlx::PgPool) {
+ let server = MockServer::start().await;
+ let mut sub = subscription();
+ sub.status = stripe::SubscriptionStatus::Trialing;
+ sub.items.data = vec![item("si_pro", "price_pro", 1)];
+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;
+ mount(&server, "POST", "/v1/subscriptions/sub_team", &sub, 1).await;
+ repo(&server, pool)
+ .increment_seat_count(&sub.id, SeatPlan::Premium, 1)
+ .await
+ .unwrap();
+ let requests = server.received_requests().await.unwrap();
+ let update = form(
+ requests
+ .iter()
+ .find(|r| r.method.as_str() == "POST" && r.url.path() == "/v1/subscriptions/sub_team")
+ .unwrap(),
+ );
+ assert!(update.get("trial_end").is_none());
+ assert!(update.get("billing_cycle_anchor").is_none());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn seat_changes_on_a_max_trial_keep_the_trial(pool: sqlx::PgPool) {
+ let server = MockServer::start().await;
+ let mut sub = subscription();
+ sub.status = stripe::SubscriptionStatus::Trialing;
+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;
+ mount(&server, "POST", "/v1/subscriptions/sub_team", &sub, 1).await;
+ let repo = repo(&server, pool);
+ repo.increment_seat_count(&sub.id, SeatPlan::Premium, 1)
+ .await
+ .unwrap();
+ repo.decrement_seat_count(&sub.id, SeatPlan::Premium, 1)
+ .await
+ .unwrap();
+ repo.increment_seat_count(&sub.id, SeatPlan::Max, 1)
+ .await
+ .unwrap();
+ repo.move_seat(&sub.id, SeatPlan::Premium, SeatPlan::Max)
+ .await
+ .unwrap();
+ let updates = server
+ .received_requests()
+ .await
+ .unwrap()
+ .iter()
+ .filter(|r| r.method.as_str() == "POST" && r.url.path() == "/v1/subscriptions/sub_team")
+ .map(form)
+ .collect::<Vec<_>>();
+ assert_eq!(updates.len(), 4);
+ for update in updates {
+ assert!(update.get("trial_end").is_none());
+ assert!(update.get("billing_cycle_anchor").is_none());
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_max_trial_seat_change_keeps_scheduled_downgrades(pool: sqlx::PgPool) {
+ let server = MockServer::start().await;
+ let mut sub = subscription();
+ sub.status = stripe::SubscriptionStatus::Trialing;
+ let mut sched = schedule();
+ let id = macro_uuid::generate_uuid_v7();
+ let at = chrono::DateTime::from_timestamp(sub.current_period_end, 0).unwrap();
+ let members = json!({"macro|[email protected]": "premium"});
+ sqlx::query!("INSERT INTO subscription_plan_schedule (id, subscription_id, effective_at, member_plans) VALUES ($1, 'sub_team', $2, $3)", id, at, members).execute(&pool).await.unwrap();
+ sched
+ .metadata
+ .as_mut()
+ .unwrap()
+ .insert(PENDING_KEY.into(), id.to_string());
+ sub.schedule = Some(stripe::Expandable::Id(sched.id.clone()));
+ mount(&server, "GET", "/v1/subscriptions/sub_team", &sub, 1).await;
+ mount(
+ &server,
+ "GET",
+ "/v1/subscription_schedules/sub_sched_test",
+ &sched,
+ 1,
+ )
+ .await;
+ mount(
+ &server,
+ "POST",
+ "/v1/subscription_schedules/sub_sched_test",
+ &sched,
+ 1,
+ )
+ .await;
+ repo(&server, pool)
+ .increment_seat_count(&sub.id, SeatPlan::Max, 1)
+ .await
+ .unwrap();
+ let requests = server.received_requests().await.unwrap();
+ assert!(!requests.iter().any(|r| r.url.path().ends_with("/release")));
+ assert!(
+ !requests
+ .iter()
+ .any(|r| r.method.as_str() == "POST" && r.url.path() == "/v1/subscriptions/sub_team")
+ );
+ let update = form(
+ requests
+ .iter()
+ .find(|r| {
+ r.method.as_str() == "POST"
+ && r.url.path() == "/v1/subscription_schedules/sub_sched_test"
+ })
+ .unwrap(),
+ );
+ assert_eq!(update["phases[0][items][0][quantity]"], "3");
+ assert_eq!(update["phases[1][items][0][quantity]"], "2");
+ assert_eq!(update["phases[1][items][1][quantity]"], "3");
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn concurrent_instances_preserve_all_scheduled_members_and_seat_additions(
pool: sqlx::PgPool,
diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.md
index 63ee82b8c2..755a061bcd 100644
--- a/docs/agent-guide/login.md
+++ b/docs/agent-guide/login.md
@@ -251,7 +251,8 @@ from the billing catalog and describes Max as 10× Pro usage, without displaying
dollar-denominated included AI allowances. Monthly prices use the compact
`/usr/mo` unit on one line; Free email branding reads “Sent with Macro”.
Free completes onboarding without a
-card. Pro returns to the account-specific Pro offer; Max starts standard paid checkout.
+card. Pro returns to the account-specific Pro offer; Max starts standard paid
+checkout with no trial period. The trial copy and button stay on the Pro offer.
The trial button requests 30 days free through Stripe Checkout, with no coupon
required. Stripe collects the payment method for billing after the trial. Only a
customer's first subscription qualifies, including canceled subscriptions in that
diff --git a/docs/agent-guide/onboarding.md b/docs/agent-guide/onboarding.md
index 8c1973b9c7..5704382434 100644
--- a/docs/agent-guide/onboarding.md
+++ b/docs/agent-guide/onboarding.md
@@ -29,4 +29,6 @@ promotions keep their own terms. Accounts with an existing subscription see
`Manage subscription`, which opens Stripe billing management instead of creating
a replacement subscription. The comparison below the offer includes Free,
Pro, and Max (see [login](login.md#desktop-onboarding)). Customers can also
-purchase plans afterwards in **Settings → Billing**.
+purchase plans afterwards in **Settings → Billing**. Max in that comparison
+starts paid checkout with no trial. A later switch from a Pro trial to Max
+ends the trial and charges Max immediately.
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
index 2c5d78e4a4..32ea4028fa 100644
--- a/docs/agent-guide/settings.md
+++ b/docs/agent-guide/settings.md
@@ -473,7 +473,9 @@ Reference captures from the isolated billing fixture: [returning customer](media
and [subscription recovery](media/billing/subscription-recovery.png). These show
phone-width layouts; payment-provider interactions are covered separately.
-`Get Max` keeps standard paid terms. Prices read `/ month` for solo users and
+`Get Max` keeps standard paid terms and never offers a trial. A Pro trial that
+upgrades to Max is charged today; the card says `Charged today. The Pro trial ends.`
+A paid Pro upgrade stays prorated for the rest of the period. Prices read `/ month` for solo users and
`per seat / month` for team accounts. Each card puts its button beside the price when wide enough and below
the price when narrow. Free lists 2 connected email accounts; Pro and Max list
unlimited connected email accounts. Pro users see a Max card (`Upgrade to Max`); Max
@@ -512,7 +514,9 @@ Team members who cannot manage billing see the notice without its action.
`Team → Members` (`/app/settings/team-members`; on a paid team each row shows the seat's plan,
and admins/owners can move a seat between Pro and Max with the `Seat plan`
-menu; Max upgrades are immediate and prorated, Pro downgrades start at renewal.
+menu; Max upgrades are immediate and prorated, except the first Max seat on a
+trialing team, which ends the trial and bills Max for a new cycle today.
+Pro downgrades start at renewal.
**Keep Max** appears only for a confirmed pending downgrade and cancels it;
failed scheduled-plan reads offer **Try again**, while teams without applicable
scheduled plans show no retry notice). CRM (a `Team CRM` switch that admins use to enable or disable it;
diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.md
index d0cff717b3..716fe85365 100644
--- a/services/authentication_service/AGENTS.md
+++ b/services/authentication_service/AGENTS.md
@@ -54,6 +54,10 @@ key issuance, and account merge/link flows.
- `GET /user/stripe/trial_eligibility` reads the authenticated customer's
eligibility without creating checkout. Any prior subscription disqualifies
the first-subscription trial, including canceled or incomplete subscriptions.
+ The trial is Pro only. Max checkout is paid immediately, and a trialing Pro
+ subscription that moves to Max ends the trial and starts a Max billing cycle
+ now. A team's first Max seat does the same; seat changes on a subscription
+ already trialing on Max keep its trial.
- Nonterminal subscriptions (including past due, unpaid, paused, and incomplete)
require management; only canceled and incomplete-expired subscriptions allow
replacement. Eligibility includes `existingSubscription` for recovery UI.
diff --git a/services/authentication_service/src/outbound/subscription_checkout.rs b/services/authentication_service/src/outbound/subscription_checkout.rs
index 4fb1f5f89a..f2ac262ebc 100644
--- a/services/authentication_service/src/outbound/subscription_checkout.rs
+++ b/services/authentication_service/src/outbound/subscription_checkout.rs
@@ -6,7 +6,7 @@ use gtm_invite::domain::{models::GtmInviteError, ports::GtmInviteService};
use macro_user_id::user_id::MacroUserIdStr;
use sha2::{Digest, Sha256};
use sqlx::PgPool;
-use teams::domain::model::{CustomerError, SeatPrices};
+use teams::domain::model::{CustomerError, SeatPlan, SeatPrices};
use thiserror::Error;
use tracing::Instrument;
@@ -195,6 +195,11 @@ impl<I> StripeCheckoutGateway<I> {
terms: CheckoutTerms,
promotion: Option<stripe::PromotionCodeId>,
) -> Result<String, StripeCheckoutError> {
+ // Trial days are attached only for the Pro price. Max checkout is paid
+ // up front; a Trial term for any other plan is a caller bug.
+ if terms == CheckoutTerms::Trial && request.plan != SeatPlan::Premium {
+ return Err(StripeCheckoutError::TrialUnavailable);
+ }
let mut params = checkout_params(
customer.clone(),
&request,
diff --git a/services/authentication_service/src/outbound/subscription_checkout/test.rs b/services/authentication_service/src/outbound/subscription_checkout/test.rs
index c097119ab9..258a5a2764 100644
--- a/services/authentication_service/src/outbound/subscription_checkout/test.rs
+++ b/services/authentication_service/src/outbound/subscription_checkout/test.rs
@@ -75,6 +75,27 @@ fn trial_keeps_team_and_conversion_metadata() {
);
}
+#[test]
+fn max_checkout_payload_has_no_trial() {
+ let mut input = request();
+ input.plan = SeatPlan::Max;
+ let params = checkout_params(
+ "cus_test".parse().unwrap(),
+ &input,
+ "price_max",
+ CheckoutTerms::Paid,
+ None,
+ );
+ let json = serde_json::to_value(params).unwrap();
+ assert_eq!(json["line_items"][0]["price"], "price_max");
+ assert!(
+ json["subscription_data"]
+ .get("trial_period_days")
+ .is_none_or(serde_json::Value::is_null)
+ );
+ assert!(json.get("metadata").is_none_or(serde_json::Value::is_null));
+}
+
#[test]
fn ordinary_paid_checkout_does_not_acquire_a_trial() {
let input = request();
@@ -362,6 +383,24 @@ async fn history_includes_canceled_subscriptions_and_every_page() {
assert!(requests[1].contains("starting_after=sub_canceled"));
}
+#[tokio::test]
+async fn max_trial_terms_never_reach_stripe() {
+ let (gateway, stub, task) = stub_gateway(vec![]).await;
+ let mut input = request();
+ input.plan = SeatPlan::Max;
+ let error = gateway
+ .checkout(
+ "cus_test".parse().unwrap(),
+ input,
+ CheckoutTerms::Trial,
+ None,
+ )
+ .await;
+ task.abort();
+ assert!(matches!(error, Err(StripeCheckoutError::TrialUnavailable)));
+ assert!(stub.requests.lock().unwrap().is_empty());
+}
+
fn empty_history() -> serde_json::Value {
serde_json::json!({"object":"list", "url":"/v1/subscriptions", "data":[], "has_more":false})
}
diff --git a/services/authentication_service/src/outbound/subscription_plan.rs b/services/authentication_service/src/outbound/subscription_plan.rs
index 7c64f8af91..9a3aded271 100644
--- a/services/authentication_service/src/outbound/subscription_plan.rs
+++ b/services/authentication_service/src/outbound/subscription_plan.rs
@@ -105,6 +105,7 @@ impl<C: CustomerRepository> PlanGateway for StripePlanGateway<C> {
Ok(PersonalSubscription {
id: subscription.id.to_string(),
plan,
+ trialing: subscription.status == stripe::SubscriptionStatus::Trialing,
})
}
async fn apply(
@@ -125,7 +126,11 @@ impl<C: CustomerRepository> PlanGateway for StripePlanGateway<C> {
.await
}
PlanAction::KeepCurrent => self.customer.schedule_seat_plan(&id, user, None).await,
- PlanAction::Upgrade => self.customer.upgrade_personal_plan(&id, target).await,
+ PlanAction::Upgrade { end_trial } => {
+ self.customer
+ .upgrade_personal_plan(&id, target, end_trial)
+ .await
+ }
}
.map_err(anyhow::Error::from)?;
Ok(())
diff --git a/services/authentication_service/src/service/subscription_plan.rs b/services/authentication_service/src/service/subscription_plan.rs
index 493e7b4b08..fe468628ab 100644
--- a/services/authentication_service/src/service/subscription_plan.rs
+++ b/services/authentication_service/src/service/subscription_plan.rs
@@ -8,12 +8,17 @@ pub struct PersonalSubscription {
pub id: String,
/// Currently effective tier, excluding future phases.
pub plan: SeatPlan,
+ /// The introductory Pro trial is still running. Max cannot inherit it.
+ pub trialing: bool,
}
/// Operation selected by the service, never by an untrusted client.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlanAction {
- /// Apply and prorate the higher plan immediately.
- Upgrade,
+ /// Apply the higher plan immediately. A Pro trial ends and bills now.
+ Upgrade {
+ /// End the trial and start the new billing cycle instead of carrying it over.
+ end_trial: bool,
+ },
/// Apply the lower plan at the next renewal.
ScheduleDowngrade,
/// Cancel a pending downgrade without changing the current price.
@@ -68,8 +73,8 @@ impl<G: PlanGateway> PlanService<G> {
return Err(PlanChangeError::PlanUnavailable);
}
let subscription = self.gateway.personal_subscription(user).await?;
- let action = action(subscription.plan, target);
- let active = if action == PlanAction::Upgrade {
+ let action = action(subscription.plan, target, subscription.trialing);
+ let active = if matches!(action, PlanAction::Upgrade { .. }) {
target
} else {
subscription.plan
@@ -80,11 +85,13 @@ impl<G: PlanGateway> PlanService<G> {
Ok(active)
}
}
-fn action(current: SeatPlan, target: SeatPlan) -> PlanAction {
+fn action(current: SeatPlan, target: SeatPlan, trialing: bool) -> PlanAction {
if current == target {
PlanAction::KeepCurrent
} else if target == SeatPlan::Max {
- PlanAction::Upgrade
+ PlanAction::Upgrade {
+ end_trial: trialing,
+ }
} else {
PlanAction::ScheduleDowngrade
}
@@ -104,6 +111,7 @@ mod test {
Ok(PersonalSubscription {
id: "sub_test".into(),
plan: SeatPlan::Max,
+ trialing: false,
})
}
async fn apply(
@@ -139,8 +147,16 @@ mod test {
#[test]
fn pro_max_is_an_immediate_upgrade() {
assert_eq!(
- action(SeatPlan::Premium, SeatPlan::Max),
- PlanAction::Upgrade
+ action(SeatPlan::Premium, SeatPlan::Max, false),
+ PlanAction::Upgrade { end_trial: false }
+ );
+ }
+
+ #[test]
+ fn pro_trial_to_max_ends_the_trial_instead_of_carrying_it() {
+ assert_eq!(
+ action(SeatPlan::Premium, SeatPlan::Max, true),
+ PlanAction::Upgrade { end_trial: true }
);
}
}