From c0ad5e0de88297731e3ede7555f9f57a4bc9528d Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 16 Jul 2026 02:13:55 +0200 Subject: [PATCH] feat(billing): 20-min trial cap + activate-plan-now upgrade flow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - config: TRIAL_MINUTE_CAP=20 — trial allowance capped across all plans - metering: apply the cap in _balance while status=trialing (full minutes once active) - billing: POST /api/billing/end-trial ends the Stripe trial immediately (charge now, unlock full minutes); webhook flips status→active - frontend: hitting the cap while trialing opens TrialUpgradeModal (activate plan now) instead of the top-up modal; polls /api/me until active - Legal: disclose the 20-minute trial allowance --- cloud/billing.py | 22 +++++ cloud/config.py | 8 +- cloud/metering.py | 6 +- dashboard/src/App.jsx | 21 ++++- dashboard/src/Legal.jsx | 10 +- .../src/components/TrialUpgradeModal.jsx | 93 +++++++++++++++++++ 6 files changed, 151 insertions(+), 9 deletions(-) create mode 100644 dashboard/src/components/TrialUpgradeModal.jsx diff --git a/cloud/billing.py b/cloud/billing.py index 3c87403..b80b483 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -153,6 +153,28 @@ async def create_checkout(body: CheckoutRequest, request: Request): return {"url": session.url} +@router.post("/api/billing/end-trial") +async def end_trial(request: Request): + """End the free trial immediately: charge the card now and unlock full plan + minutes. Used when a trialing user hits the trial minute cap and chooses to + activate their plan right away. The subscription webhook flips status→active + (and thus the full ``minutes_per_period`` allowance) once Stripe confirms.""" + user = await get_current_user_required(request) + async with database.session() as session: + sub = (await session.execute( + select(Subscription).where(Subscription.user_id == user.id) + )).scalar_one_or_none() + if not sub or sub.status != "trialing": + raise HTTPException(status_code=409, detail="No active trial to convert.") + try: + updated = await asyncio.to_thread(lambda: stripe.Subscription.modify( + sub.stripe_subscription_id, trial_end="now", + )) + except Exception: + raise HTTPException(status_code=502, detail="Could not activate your plan. Try again.") + return {"status": updated.get("status", "active")} + + @router.post("/api/billing/portal") async def create_portal(request: Request): user = await get_current_user_required(request) diff --git a/cloud/config.py b/cloud/config.py index c702e42..7dd8b9c 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -28,9 +28,15 @@ PLAN_MINUTES = { } # Free trial length (days) for new subscriptions. Card required; auto-charges at -# the end. No minute cap during the trial — the card + Stripe Radar deter abuse. +# the end. TRIAL_DAYS = 3 +# Minute cap DURING the trial (across all plans). Enough to evaluate the product, +# but bounds the free managed-compute / proxy exposure per sign-up so a +# cancel-before-charge account can't burn a full plan's worth of minutes. Once the +# trial converts to an active subscription the full plan allowance applies. +TRIAL_MINUTE_CAP = 20 + # Gemini IMAGE generation (thumbnails) is the one expensive managed Gemini call # (~$0.04/image, batch of ~3). It isn't naturally minute-metered, so each # thumbnail generation batch consumes this many minutes from the plan quota — diff --git a/cloud/metering.py b/cloud/metering.py index c0cb4eb..fcd7c88 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -26,7 +26,7 @@ from decimal import Decimal from sqlalchemy import select, update, func, and_ -from . import database +from . import config, database from .models import User, Subscription, CreditTopup, UsageLedger @@ -143,6 +143,10 @@ async def _balance(session, user_id): """Return a dict of the user's current minute balance (read-only).""" sub = await _active_subscription(session, user_id) plan_allowance = _D(sub.minutes_per_period) if sub else _D(0) + # During the trial, cap the allowance so a cancel-before-charge account can't + # burn a whole plan's worth of managed minutes. Full allowance once active. + if sub and sub.status == "trialing": + plan_allowance = min(plan_allowance, _D(config.TRIAL_MINUTE_CAP)) period_end = sub.current_period_end if sub else None plan_used = await _plan_used_this_period(session, user_id, period_end) if sub else _D(0) plan_remaining = max(_D(0), plan_allowance - plan_used) diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 39e9390..67e3c61 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -11,6 +11,7 @@ import UGCGallery from './components/UGCGallery'; import ScheduleWeekModal from './components/ScheduleWeekModal'; import UsageMeter from './components/UsageMeter'; import TopUpModal from './components/TopUpModal'; +import TrialUpgradeModal from './components/TrialUpgradeModal'; import LoginModal from './components/LoginModal'; import TrialGate from './components/TrialGate'; import AdvancedBanner from './components/AdvancedBanner'; @@ -144,9 +145,10 @@ const pollJob = async (jobId) => { function App() { // Cloud auth/billing session (inert when billing is disabled). - const { billingEnabled, isManaged, isSignedIn, signingIn } = useAuth(); + const { billingEnabled, isManaged, isSignedIn, signingIn, me, plan, refreshMe } = useAuth(); const [showLogin, setShowLogin] = useState(false); const [showTopUp, setShowTopUp] = useState(false); + const [showTrialUpgrade, setShowTrialUpgrade] = useState(false); const [topUpInfo, setTopUpInfo] = useState({}); const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || ''); @@ -396,8 +398,14 @@ function App() { } catch (e) { if (e instanceof QuotaError) { setStatus('idle'); - setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining }); - setShowTopUp(true); + // Trial users hit the trial minute cap → prompt them to activate the plan + // now (unlocks full minutes). Active users → offer a top-up. + if (me?.status === 'trialing') { + setShowTrialUpgrade(true); + } else { + setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining }); + setShowTopUp(true); + } return; } setStatus('error'); @@ -1230,6 +1238,13 @@ function App() { remaining={topUpInfo.remaining} /> )} + {showTrialUpgrade && ( + setShowTrialUpgrade(false)} + /> + )} ); } diff --git a/dashboard/src/Legal.jsx b/dashboard/src/Legal.jsx index 3bcdd35..f721a16 100644 --- a/dashboard/src/Legal.jsx +++ b/dashboard/src/Legal.jsx @@ -72,10 +72,12 @@ export default function Legal() {

Free trial: new subscriptions start with a{' '} - 3-day free trial. You provide a payment method up front - but are not charged during the trial. If you do not - cancel before the trial ends, your subscription automatically begins and your payment method is - charged the plan price. You can cancel at any time from your account. + 3-day free trial that includes up to{' '} + 20 minutes of video processing. You provide a payment + method up front but are not charged during the trial. If + you do not cancel before the trial ends, your subscription automatically begins, your full plan + minutes unlock, and your payment method is charged the plan price. You can cancel at any time from + your account.

Auto-renewal: subscriptions renew automatically each diff --git a/dashboard/src/components/TrialUpgradeModal.jsx b/dashboard/src/components/TrialUpgradeModal.jsx new file mode 100644 index 0000000..3c39460 --- /dev/null +++ b/dashboard/src/components/TrialUpgradeModal.jsx @@ -0,0 +1,93 @@ +import React, { useState, useEffect } from 'react'; +import { X, Loader2, Rocket, CheckCircle2 } from 'lucide-react'; +import { apiJson } from '../lib/api'; + +// Shown when a TRIALING user hits the trial minute cap. Lets them end the trial +// and activate the paid plan right away (charges the card now, unlocks the full +// monthly minutes). The subscription webhook flips status→active server-side. +export default function TrialUpgradeModal({ plan, onActivated, onClose }) { + const [busy, setBusy] = useState(false); + const [done, setDone] = useState(false); + const [error, setError] = useState(''); + const [planMinutes, setPlanMinutes] = useState(null); + + // Look up the full monthly minutes for the current plan (to show what unlocks). + useEffect(() => { + apiJson('/api/billing/plans') + .then((d) => { + const match = (d.plans || []).find((p) => p.plan === plan && p.interval === 'month'); + if (match) setPlanMinutes(match.minutes); + }) + .catch(() => {}); + }, [plan]); + + const activate = async () => { + setBusy(true); + setError(''); + try { + const res = await apiJson('/api/billing/end-trial', { method: 'POST' }); + // Poll /api/me until the webhook flips the subscription to active. + let ok = res?.status === 'active'; + for (let i = 0; i < 10 && !ok; i++) { + await new Promise((r) => setTimeout(r, 1500)); + const me = await onActivated(); + ok = me?.status === 'active'; + } + if (ok) { + setDone(true); + setTimeout(onClose, 1800); + } else { + // Charge is processing (or card needs attention) — let them proceed anyway. + await onActivated(); + setError('Almost there — your plan is activating. If it doesn\'t unlock in a minute, check your billing details.'); + } + } catch (e) { + setError('Could not activate your plan. Please try again or manage billing from your account.'); + } finally { + setBusy(false); + } + }; + + return ( +

+
+ + + {done ? ( +
+
+

You're all set 🎉

+

Your plan is active{planMinutes ? ` with ${planMinutes} minutes` : ''}. Go ahead and generate your clips.

+
+ ) : ( + <> +
+

You've used your free trial minutes

+

+ Activate your{plan ? <> {plan} : ''} plan now to unlock{' '} + {planMinutes ? <>{planMinutes} minutes every month : 'your full monthly minutes'} and keep creating. + Your card is charged today and your 3-day trial ends now. +

+ + {error &&

{error}

} + + + + + )} +
+
+ ); +}