feat(billing): 20-min trial cap + activate-plan-now upgrade flow
- 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
This commit is contained in:
parent
d298f69f12
commit
c0ad5e0de8
6 changed files with 151 additions and 9 deletions
|
|
@ -153,6 +153,28 @@ async def create_checkout(body: CheckoutRequest, request: Request):
|
||||||
return {"url": session.url}
|
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")
|
@router.post("/api/billing/portal")
|
||||||
async def create_portal(request: Request):
|
async def create_portal(request: Request):
|
||||||
user = await get_current_user_required(request)
|
user = await get_current_user_required(request)
|
||||||
|
|
|
||||||
|
|
@ -28,9 +28,15 @@ PLAN_MINUTES = {
|
||||||
}
|
}
|
||||||
|
|
||||||
# Free trial length (days) for new subscriptions. Card required; auto-charges at
|
# 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
|
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
|
# 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
|
# (~$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 —
|
# thumbnail generation batch consumes this many minutes from the plan quota —
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@ from decimal import Decimal
|
||||||
|
|
||||||
from sqlalchemy import select, update, func, and_
|
from sqlalchemy import select, update, func, and_
|
||||||
|
|
||||||
from . import database
|
from . import config, database
|
||||||
from .models import User, Subscription, CreditTopup, UsageLedger
|
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)."""
|
"""Return a dict of the user's current minute balance (read-only)."""
|
||||||
sub = await _active_subscription(session, user_id)
|
sub = await _active_subscription(session, user_id)
|
||||||
plan_allowance = _D(sub.minutes_per_period) if sub else _D(0)
|
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
|
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_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)
|
plan_remaining = max(_D(0), plan_allowance - plan_used)
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ import UGCGallery from './components/UGCGallery';
|
||||||
import ScheduleWeekModal from './components/ScheduleWeekModal';
|
import ScheduleWeekModal from './components/ScheduleWeekModal';
|
||||||
import UsageMeter from './components/UsageMeter';
|
import UsageMeter from './components/UsageMeter';
|
||||||
import TopUpModal from './components/TopUpModal';
|
import TopUpModal from './components/TopUpModal';
|
||||||
|
import TrialUpgradeModal from './components/TrialUpgradeModal';
|
||||||
import LoginModal from './components/LoginModal';
|
import LoginModal from './components/LoginModal';
|
||||||
import TrialGate from './components/TrialGate';
|
import TrialGate from './components/TrialGate';
|
||||||
import AdvancedBanner from './components/AdvancedBanner';
|
import AdvancedBanner from './components/AdvancedBanner';
|
||||||
|
|
@ -144,9 +145,10 @@ const pollJob = async (jobId) => {
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
// Cloud auth/billing session (inert when billing is disabled).
|
// 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 [showLogin, setShowLogin] = useState(false);
|
||||||
const [showTopUp, setShowTopUp] = useState(false);
|
const [showTopUp, setShowTopUp] = useState(false);
|
||||||
|
const [showTrialUpgrade, setShowTrialUpgrade] = useState(false);
|
||||||
const [topUpInfo, setTopUpInfo] = useState({});
|
const [topUpInfo, setTopUpInfo] = useState({});
|
||||||
|
|
||||||
const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || '');
|
const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || '');
|
||||||
|
|
@ -396,8 +398,14 @@ function App() {
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof QuotaError) {
|
if (e instanceof QuotaError) {
|
||||||
setStatus('idle');
|
setStatus('idle');
|
||||||
|
// 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 });
|
setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining });
|
||||||
setShowTopUp(true);
|
setShowTopUp(true);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setStatus('error');
|
setStatus('error');
|
||||||
|
|
@ -1230,6 +1238,13 @@ function App() {
|
||||||
remaining={topUpInfo.remaining}
|
remaining={topUpInfo.remaining}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{showTrialUpgrade && (
|
||||||
|
<TrialUpgradeModal
|
||||||
|
plan={plan}
|
||||||
|
onActivated={refreshMe}
|
||||||
|
onClose={() => setShowTrialUpgrade(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -72,10 +72,12 @@ export default function Legal() {
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<strong className="text-white">Free trial:</strong> new subscriptions start with a{' '}
|
<strong className="text-white">Free trial:</strong> new subscriptions start with a{' '}
|
||||||
<strong className="text-white">3-day free trial</strong>. You provide a payment method up front
|
<strong className="text-white">3-day free trial</strong> that includes up to{' '}
|
||||||
but are <strong className="text-white">not charged during the trial</strong>. If you do not
|
<strong className="text-white">20 minutes</strong> of video processing. You provide a payment
|
||||||
cancel before the trial ends, your subscription automatically begins and your payment method is
|
method up front but are <strong className="text-white">not charged during the trial</strong>. If
|
||||||
charged the plan price. You can cancel at any time from your account.
|
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.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<strong className="text-white">Auto-renewal:</strong> subscriptions renew automatically each
|
<strong className="text-white">Auto-renewal:</strong> subscriptions renew automatically each
|
||||||
|
|
|
||||||
93
dashboard/src/components/TrialUpgradeModal.jsx
Normal file
93
dashboard/src/components/TrialUpgradeModal.jsx
Normal file
|
|
@ -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 (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4">
|
||||||
|
<div className="bg-surface border border-white/10 rounded-2xl p-8 w-full max-w-md relative">
|
||||||
|
<button onClick={onClose} className="absolute right-4 top-4 text-zinc-400 hover:text-white"><X size={20} /></button>
|
||||||
|
|
||||||
|
{done ? (
|
||||||
|
<div className="text-center py-4">
|
||||||
|
<div className="inline-flex p-3 bg-green-500/20 rounded-full text-green-400 mb-4"><CheckCircle2 size={24} /></div>
|
||||||
|
<h2 className="text-xl font-bold mb-1">You're all set 🎉</h2>
|
||||||
|
<p className="text-zinc-400 text-sm">Your plan is active{planMinutes ? ` with ${planMinutes} minutes` : ''}. Go ahead and generate your clips.</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="inline-flex p-3 bg-primary/20 rounded-full text-primary mb-4"><Rocket size={24} /></div>
|
||||||
|
<h2 className="text-xl font-bold mb-1">You've used your free trial minutes</h2>
|
||||||
|
<p className="text-zinc-400 text-sm mb-6">
|
||||||
|
Activate your{plan ? <> <span className="capitalize font-semibold text-white">{plan}</span></> : ''} plan now to unlock{' '}
|
||||||
|
{planMinutes ? <><b className="text-white">{planMinutes} minutes</b> every month</> : 'your full monthly minutes'} and keep creating.
|
||||||
|
Your card is charged today and your 3-day trial ends now.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{error && <p className="text-amber-400 text-xs mb-4">{error}</p>}
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={activate}
|
||||||
|
disabled={busy}
|
||||||
|
className="w-full btn-primary py-3 flex items-center justify-center gap-2 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{busy ? <><Loader2 size={18} className="animate-spin" /> Activating…</> : <>Activate my plan now</>}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
disabled={busy}
|
||||||
|
className="w-full mt-2 text-zinc-400 hover:text-white text-sm py-2 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
Maybe later
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue