feat(feedback): in-app cancel flow with reason + review, and a sign-up survey

- POST /api/billing/cancel: closed-list reason, optional detail, 1-5 rating and
  review; cancels at period end in Stripe with cancellation_details, then stores
  cancellation_feedback. Account page opens CancelPlanModal (3 steps).
- Portal cancellations: churn alert now carries Stripe's feedback value.
- POST /api/onboarding/survey + /api/me onboarding_survey_pending: accounts under
  7 days get one skippable screen before the clip tutorial (what they want to
  make, where they heard of us, who they are). Stored in onboarding_surveys and
  tracked as SignupSurveyAnswered with per-goal props.
- Both new tables are user-owned and erased with the account.
This commit is contained in:
juancarlos.cavero 2026-09-28 18:27:00 +02:00
parent 9837228365
commit 42942aecfe
14 changed files with 870 additions and 5 deletions

View file

@ -219,6 +219,31 @@ tick. All four are commercial: `emails.send_commercial_email` skips
The Stripe webhook endpoint must have `checkout.session.expired` enabled.
Promotion codes and coupon ids live in the env / Stripe, never in this repo.
### Cancel flow (`cloud/cancellation.py`, `CancelPlanModal.jsx`)
Account → "Cancel subscription" opens three steps: reason (closed list,
`CANCEL_REASONS`, plus an optional detail box), a 1-5 rating with an optional
review (and an "OK to quote publicly" box), then confirm.
`POST /api/billing/cancel` sets `cancel_at_period_end` in Stripe with
`cancellation_details` (our reason mapped to Stripe's feedback enum), and only
after Stripe accepts writes a `cancellation_feedback` row (user-owned, erased
with the account) and flips the local row, so the webhook sees no transition
and the generic churn alert does not fire twice. The alert names the reason and
rating, never the written text (Telegram, see `alerts.user_ref`): read reviews
in the table. The Stripe portal can still cancel without the form; its alert
carries Stripe's own feedback value when the portal asked for one.
### Sign-up survey (`cloud/onboarding.py`, `OnboardingSurvey.jsx`)
`signup_attribution` says which page a user came from, not why. Accounts
younger than 7 days get one skippable screen before the clip tutorial (never
over a running job): what they want to make (multi-select: clips, AI avatar /
UGC videos, autopilot, thumbnails...), how they heard of us, and who they are.
Closed lists mirrored in the JSX (a test checks), stored in
`onboarding_surveys` (user-owned; a skip is a row too, so it is asked once),
and tracked as `SignupSurveyAnswered` with one `goal_<x>` prop per goal so
OpenPanel can break conversion down by what people came for.
### How many clips a job returns (`clip_selection.py`)
The count is not a setting, it is derived, and every stage of the derivation

View file

@ -27,12 +27,16 @@ def setup_sync(app):
app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret)
from . import (auth, oauth, billing, social_profiles, videos, api_keys,
account, mcp_oauth, marketing, autopilot, lifecycle) # noqa: F401
account, mcp_oauth, marketing, autopilot, lifecycle, cancellation, onboarding) # noqa: F401
oauth.register()
billing._init_stripe()
app.include_router(auth.router)
app.include_router(oauth.router)
app.include_router(billing.router)
# Cancel flow with reason + review (the portal can still cancel too).
app.include_router(cancellation.router)
# Sign-up survey: source, what they came to make, who they are.
app.include_router(onboarding.router)
app.include_router(social_profiles.router)
app.include_router(videos.router)
app.include_router(api_keys.router)

View file

@ -42,7 +42,7 @@ from .models import (
User, Subscription, CreditTopup, UsageLedger, MagicLinkToken,
SignupAttribution, ApiKey, UploadPostProfile, UserVideo, ClipExpiryWarning,
Project, AccountDeletion, OAuthCode, AutopilotRun, AutopilotSettings,
LifecycleEmail,
LifecycleEmail, CancellationFeedback, OnboardingSurvey,
)
# Every table that holds rows belonging to a user, child-first (clip_expiry_
@ -57,7 +57,8 @@ from .models import (
USER_OWNED_TABLES = (
ClipExpiryWarning, UserVideo, Project, UsageLedger, CreditTopup,
Subscription, ApiKey, SignupAttribution, UploadPostProfile, OAuthCode,
AutopilotRun, AutopilotSettings, LifecycleEmail,
AutopilotRun, AutopilotSettings, LifecycleEmail, CancellationFeedback,
OnboardingSurvey,
)
# The optional "why are you leaving" answer, as a closed list. It was a free

View file

@ -364,6 +364,8 @@ async def get_me(request: Request):
async with database.session() as session:
bal = await metering._balance(session, user.id)
sub = bal["_sub"]
from .onboarding import is_pending as _survey_pending
survey_pending = await _survey_pending(session, user)
# Report the entitling subscription when there is one; otherwise fall back to
# a row that needs the customer's attention (card declined, payment never
# finished). Without this a past_due customer sees a plain free account and
@ -392,4 +394,5 @@ async def get_me(request: Request):
"remaining": bal["remaining"],
},
"upload_post_profile": user.upload_post_profile,
"onboarding_survey_pending": survey_pending,
}

View file

@ -591,9 +591,15 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime):
if just_canceled:
from .alerts import send_admin_alert
from .config import VIDEO_RETENTION_GRACE_DAYS
# Cancelled in the Stripe portal, not the dashboard flow (which flips
# the row itself and sends its own alert). The portal's reason, if it
# asked for one, is the only feedback there is. The comment is free
# text and stays out of Telegram (alerts.user_ref).
feedback = (sub_obj.get("cancellation_details") or {}).get("feedback")
await send_admin_alert(
"🔻 Subscription canceled",
f"A {plan} subscriber just canceled.\n"
f"A {plan} subscriber just canceled in the Stripe portal"
f"{f' (reason: {feedback})' if feedback else ''}.\n"
f"Access continues until {end_dt:%Y-%m-%d}. Google-authed users then "
f"drop to the free plan (clips expire after 7 days); others keep their "
f"videos {VIDEO_RETENTION_GRACE_DAYS} more days before deletion.",

148
cloud/cancellation.py Normal file
View file

@ -0,0 +1,148 @@
"""In-app cancellation: ask why, ask for a review, then cancel.
Cancelling used to happen only inside the Stripe Customer Portal, so the one
moment a paying customer tells us what went wrong produced nothing but a
"🔻 Subscription canceled" alert with no reason in it. This endpoint is the
dashboard's cancel flow: the reason (closed list, so it can be counted), an
optional free-text detail, a 1-5 rating and an optional review, stored in
``cancellation_feedback`` and then passed on to Stripe as
``cancellation_details`` so the Stripe dashboard shows the same reason.
The cancel is ``cancel_at_period_end``, never immediate: they paid for the
period and keep it. The portal stays available and can still cancel without
this form; the webhook alert carries Stripe's own ``cancellation_details`` for
those.
Unlike ``account.DELETION_REASONS``, free text is fine here: these rows belong
to the user (``account.USER_OWNED_TABLES``) and go with the account. What must
not happen is the text reaching Telegram (see ``alerts.user_ref``), so the
alert says how long the review is, never what it says.
"""
import asyncio
from typing import Optional
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
from sqlalchemy import select
from . import analytics, database
from .auth import get_current_user_required
from .models import CancellationFeedback, Subscription
router = APIRouter()
# Mirrors the REASONS list in dashboard/src/components/CancelPlanModal.jsx.
# Each maps to the closest value of Stripe's own cancellation_details.feedback
# enum, so the reason also shows up on the subscription in Stripe.
CANCEL_REASONS = {
"too_expensive": "too_expensive",
"not_using_it": "unused",
"clip_quality": "low_quality",
"missing_feature": "missing_features",
"found_alternative": "switched_service",
"too_complex": "too_complex",
"support": "customer_service",
"one_off_project": "unused",
"other": "other",
}
# States in which there is a renewal to stop. past_due is included: a customer
# whose card failed and who wants out should not have to fix the card first.
CANCELLABLE_STATES = ("active", "trialing", "past_due")
MAX_TEXT = 2000
class CancelRequest(BaseModel):
reason: str
details: Optional[str] = Field(default=None, max_length=MAX_TEXT)
rating: Optional[int] = Field(default=None, ge=1, le=5)
review: Optional[str] = Field(default=None, max_length=MAX_TEXT)
review_public_ok: bool = False
def _stripe_cancel_at_period_end(subscription_id: str, feedback: str, comment: str):
# Imported here so the module (and its tests) load where stripe is not
# installed, as in CI.
import stripe
stripe.Subscription.modify(
subscription_id,
cancel_at_period_end=True,
cancellation_details={"feedback": feedback, "comment": comment},
)
def _clean(text: Optional[str]) -> Optional[str]:
text = (text or "").strip()
return text or None
@router.post("/api/billing/cancel")
async def cancel_subscription(body: CancelRequest, request: Request):
user = await get_current_user_required(request)
if body.reason not in CANCEL_REASONS:
raise HTTPException(status_code=422, detail="Pick a reason from the list.")
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 not in CANCELLABLE_STATES:
raise HTTPException(status_code=409, detail="There is no active subscription to cancel.")
if sub.cancel_at_period_end:
raise HTTPException(status_code=409, detail="Your subscription is already set to cancel.")
details, review = _clean(body.details), _clean(body.review)
# Stripe caps the comment at 5000 chars; ours are 2000 each.
comment = " | ".join(x for x in (details, review) if x) or None
try:
await asyncio.to_thread(
_stripe_cancel_at_period_end, sub.stripe_subscription_id,
CANCEL_REASONS[body.reason], comment or "")
except Exception as e:
print(f"⚠️ Stripe cancel failed for {user.id}: {e}")
raise HTTPException(status_code=502, detail=(
"We couldn't cancel your subscription right now. Please try again, "
"or email info@openshorts.app."))
# Written after Stripe accepted the cancel, so a failed call leaves no
# feedback row claiming a cancellation that never happened. Flipping
# cancel_at_period_end here (instead of waiting for the webhook) makes the
# account page show it at once, and makes the webhook see no False -> True
# transition, so the generic churn alert does not fire on top of this one.
async with database.session() as session:
async with session.begin():
session.add(CancellationFeedback(
user_id=user.id,
stripe_subscription_id=sub.stripe_subscription_id,
plan=sub.plan, interval=sub.interval,
reason=body.reason, details=details,
rating=body.rating, review=review,
review_public_ok=bool(body.review_public_ok and review),
))
row = (await session.execute(
select(Subscription).where(Subscription.id == sub.id).with_for_update()
)).scalar_one_or_none()
if row is not None:
row.cancel_at_period_end = True
analytics.track("SubscriptionCanceled", user_id=user.id, plan=sub.plan,
interval=sub.interval, reason=body.reason, rating=body.rating,
has_review=bool(review))
from .alerts import send_admin_alert, user_ref
stars = f"{body.rating}/5" if body.rating else "no rating"
written = []
if details:
written.append(f"detail {len(details)} chars")
if review:
written.append(f"review {len(review)} chars"
+ (", OK to quote" if body.review_public_ok else ""))
await send_admin_alert(
"🔻 Subscription canceled",
f"{user_ref(user.id)} canceled the {sub.plan} ({sub.interval}) plan.\n"
f"Reason: {body.reason}. Rating: {stars}.\n"
f"{'; '.join(written) or 'No written feedback'} (cancellation_feedback table).\n"
f"Access continues until {sub.current_period_end:%Y-%m-%d}.",
)
return {"ok": True, "period_end": sub.current_period_end.isoformat()}

View file

@ -413,6 +413,42 @@ class LifecycleEmail(Base):
)
class CancellationFeedback(Base):
"""Why a subscriber cancelled, and their review (cloud/cancellation.py).
One row per cancellation made through the dashboard flow. User-owned: the
free text belongs to the account and is erased with it, which is why it is
allowed here and not in ``account_deletions``.
"""
__tablename__ = "cancellation_feedback"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
nullable=False, index=True)
stripe_subscription_id = Column(Text, nullable=True)
plan = Column(String(20), nullable=True)
interval = Column(String(10), nullable=True)
reason = Column(String(32), nullable=False) # one of cancellation.CANCEL_REASONS
details = Column(Text, nullable=True)
rating = Column(Integer, nullable=True) # 1-5
review = Column(Text, nullable=True)
review_public_ok = Column(Boolean, nullable=False, default=False)
created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True)
class OnboardingSurvey(Base):
"""The sign-up survey (cloud/onboarding.py): where they heard of us, what
they came to make, who they are. One row per account, a skip included."""
__tablename__ = "onboarding_surveys"
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
primary_key=True)
skipped = Column(Boolean, nullable=False, default=False)
source = Column(String(32), nullable=True, index=True) # one of onboarding.SOURCES
source_other = Column(Text, nullable=True)
goals = Column(JSONB, nullable=True) # list of onboarding.GOALS
role = Column(String(32), nullable=True, index=True) # one of onboarding.ROLES
created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True)
class FirstVideoGrant(Base):
"""One free first video clipped whole (app.free_overflow), by client IP.

113
cloud/onboarding.py Normal file
View file

@ -0,0 +1,113 @@
"""Sign-up survey: where the user heard of us and what they came to make.
``signup_attribution`` records the referrer, and 94% of it is brand traffic
from the GitHub repo or a direct visit, which says nothing about *why*: a
creator who wants clips from a podcast and one who wants AI avatar ads land on
the same page. Three closed questions asked once, right after sign-up, answer
that. One screen, skippable; a skip is stored too so it is never asked twice
and the skip rate is itself measurable.
Closed lists so the answers can be counted; the only free text is the "other"
source, capped short. The row is user-owned and goes with the account.
"""
from datetime import datetime, timedelta, timezone
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
from sqlalchemy import select
from . import analytics, database
from .auth import get_current_user_required
from .models import OnboardingSurvey, User
router = APIRouter()
# Mirror the lists in dashboard/src/components/OnboardingSurvey.jsx.
SOURCES = (
"google", "ai_assistant", "youtube", "tiktok_instagram", "x_twitter", "reddit",
"github", "friend", "directory", "newsletter_blog", "other",
)
GOALS = (
"clips_from_long_videos", "ai_avatar_videos", "autopilot_posting", "thumbnails",
"subtitles", "dubbing", "api_agents", "self_host",
)
ROLES = (
"creator", "podcaster", "streamer_gamer", "agency", "business_marketing",
"educator", "developer", "other",
)
# Only accounts this young are asked. Everyone who signed up before the survey
# shipped would otherwise get it on their next visit, and a returning user's
# "how did you hear about us" is a memory, not an attribution.
SURVEY_MAX_ACCOUNT_AGE = timedelta(days=7)
OTHER_MAX = 120
class SurveyAnswer(BaseModel):
skipped: bool = False
source: Optional[str] = None
source_other: Optional[str] = Field(default=None, max_length=OTHER_MAX)
goals: List[str] = Field(default_factory=list, max_length=len(GOALS))
role: Optional[str] = None
def _validate(a: SurveyAnswer):
if a.skipped:
return
if a.source is not None and a.source not in SOURCES:
raise HTTPException(status_code=422, detail="Unknown source.")
if a.role is not None and a.role not in ROLES:
raise HTTPException(status_code=422, detail="Unknown role.")
if any(g not in GOALS for g in a.goals):
raise HTTPException(status_code=422, detail="Unknown goal.")
if not (a.source or a.goals or a.role):
raise HTTPException(status_code=422, detail="Answer at least one question, or skip.")
def survey_pending(user_created_at: Optional[datetime], answered: bool) -> bool:
"""Whether /api/me should ask the dashboard to show the survey."""
if answered or user_created_at is None:
return False
return datetime.now(timezone.utc) - user_created_at <= SURVEY_MAX_ACCOUNT_AGE
async def is_pending(session, user) -> bool:
answered = (await session.execute(
select(OnboardingSurvey.user_id).where(OnboardingSurvey.user_id == user.id)
)).scalar_one_or_none() is not None
created = (await session.execute(
select(User.created_at).where(User.id == user.id)
)).scalar_one_or_none()
return survey_pending(created, answered)
@router.post("/api/onboarding/survey")
async def answer_survey(body: SurveyAnswer, request: Request):
from sqlalchemy.dialects.postgresql import insert as pg_insert
user = await get_current_user_required(request)
_validate(body)
goals = [] if body.skipped else list(dict.fromkeys(body.goals))
source = None if body.skipped else body.source
other = (body.source_other or "").strip()[:OTHER_MAX] or None
if source != "other":
other = None
role = None if body.skipped else body.role
async with database.session() as session:
async with session.begin():
# First answer wins: two tabs, or a double click, must not overwrite.
await session.execute(pg_insert(OnboardingSurvey).values(
user_id=user.id, skipped=body.skipped, source=source,
source_other=other, goals=goals, role=role,
).on_conflict_do_nothing(index_elements=["user_id"]))
if body.skipped:
analytics.track("SignupSurveySkipped", user_id=user.id)
else:
# One flat prop per goal so OpenPanel can break the event down by each,
# which it cannot do with a list.
analytics.track("SignupSurveyAnswered", user_id=user.id, source=source,
role=role, goals=",".join(goals) or None,
**{f"goal_{g}": True for g in goals})
return {"ok": True}

View file

@ -17,6 +17,7 @@ import TopUpModal from './components/TopUpModal';
import StarBanner from './components/StarBanner';
import PlanChoiceModal from './components/PlanChoiceModal';
import ClipTutorial from './components/ClipTutorial';
import OnboardingSurvey from './components/OnboardingSurvey';
import TrialUpgradeModal from './components/TrialUpgradeModal';
import LoginModal from './components/LoginModal';
import TrialGate from './components/TrialGate';
@ -849,6 +850,13 @@ function App() {
const tutorialLock = tutorialPhase === 'intro' || tutorialPhase === 'coach' || tutorialPhase === 'celebrate';
// Sign-up survey (cloud/onboarding.py): before the tutorial intro, never on
// top of a job that is already running (a parked request resuming, or the
// coach phase) or of the celebration.
const [surveyDone, setSurveyDone] = useState(false);
const showSurvey = billingEnabled && !!me?.onboarding_survey_pending && !surveyDone
&& (tutorialPhase === null || tutorialPhase === 'intro') && status === 'idle';
useEffect(() => {
if (tutorialLock && activeTab !== 'dashboard') setActiveTab('dashboard');
}, [tutorialLock, activeTab]);
@ -2403,7 +2411,8 @@ function App() {
/>
)}
{showLogin && <LoginModal onClose={() => setShowLogin(false)} queued={typeof peekPendingJob()?.data?.payload === 'string'} />}
{tutorialPhase && (
{showSurvey && <OnboardingSurvey onDone={() => setSurveyDone(true)} />}
{tutorialPhase && !showSurvey && (
<ClipTutorial
phase={tutorialPhase}
jobStatus={status}

View file

@ -8,12 +8,15 @@ import McpConnectCard from './McpConnectCard';
import DeleteAccountCard from './DeleteAccountCard';
import SocialAnalyticsCard from './SocialAnalyticsCard';
import InvoicesCard from './InvoicesCard';
import CancelPlanModal from './CancelPlanModal';
const fmt1 = (n) => Math.round((n || 0) * 10) / 10;
// Mirrors cloud/config.BILLING_ATTENTION_STATES: states where the customer has
// to do something (fix a card, finish a payment) before minutes come back.
const PAYMENT_ISSUE_STATES = ['past_due', 'unpaid', 'incomplete', 'paused'];
// Mirrors cloud/cancellation.CANCELLABLE_STATES.
const CANCELLABLE_STATES = ['active', 'trialing', 'past_due'];
// Account/billing page: plan, usage meter, top-ups, manage billing, logout.
export default function AccountPage() {
@ -21,6 +24,7 @@ export default function AccountPage() {
const [busy, setBusy] = useState(false);
const [topups, setTopups] = useState([]);
const [activating, setActivating] = useState(false);
const [cancelOpen, setCancelOpen] = useState(false);
// After returning from Checkout the webhook may lag — poll /api/me briefly.
useEffect(() => {
@ -183,8 +187,28 @@ export default function AccountPage() {
<span className="text-brass font-medium">{fmt1(m.remaining)} min</span>
</div>
</div>
{/* Our own cancel flow (reason + review) rather than the portal's, so
the one moment a customer says what went wrong is not lost. */}
{me.has_billing_account && CANCELLABLE_STATES.includes(me.status) && !me.cancel_at_period_end && (
<div className="pt-4 mt-4 border-t border-rule text-right">
<button onClick={() => { track('CancelFlowOpened', { props: { plan } }); setCancelOpen(true); }}
className="text-xs text-muted underline underline-offset-2 hover:text-ink">
Cancel subscription
</button>
</div>
)}
</div>
{cancelOpen && (
<CancelPlanModal
plan={plan}
periodEnd={me.period_end}
onClose={() => setCancelOpen(false)}
onCanceled={() => { setCancelOpen(false); refreshMe(); }}
/>
)}
{/* Only accounts that ever had a Stripe relationship can have invoices. */}
{me.has_billing_account && <InvoicesCard />}

View file

@ -0,0 +1,166 @@
import React, { useState, useRef } from 'react';
import { Loader2, Star } from 'lucide-react';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import Modal from './ui/Modal';
// Mirrors cloud/cancellation.CANCEL_REASONS. A closed list so churn can be
// counted; the text box under it is where the specifics go.
const REASONS = [
['too_expensive', 'Too expensive'],
['not_using_it', "I'm not using it enough"],
['one_off_project', 'I only needed it for one project'],
['clip_quality', "The clips weren't good enough"],
['missing_feature', 'Missing a feature I need'],
['too_complex', 'Too hard to use'],
['found_alternative', 'I found something better'],
['support', 'Bad experience with support'],
['other', 'Something else'],
];
const DETAIL_PROMPT = {
too_expensive: 'What price would have worked for you?',
clip_quality: 'What was wrong with the clips?',
missing_feature: 'Which feature were you missing?',
found_alternative: 'Which tool are you moving to, and what does it do better?',
too_complex: 'Where did you get stuck?',
support: 'What happened?',
};
const fmtDate = (iso) => {
if (!iso) return 'the end of your billing period';
try {
return new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
} catch (_) { return 'the end of your billing period'; }
};
// Cancel flow: reason -> review -> confirm. The cancel only happens on the
// last step, and at period end (backend: cloud/cancellation.py), so every
// "keep my plan" exit leaves the subscription untouched.
export default function CancelPlanModal({ plan, periodEnd, onClose, onCanceled }) {
const [step, setStep] = useState(0);
const [reason, setReason] = useState('');
const [details, setDetails] = useState('');
const [rating, setRating] = useState(0);
const [hover, setHover] = useState(0);
const [review, setReview] = useState('');
const [publicOk, setPublicOk] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const sending = useRef(false);
const keep = () => {
track('CancelFlowAbandoned', { props: { step, reason: reason || undefined } });
onClose();
};
const submit = async () => {
if (sending.current) return;
sending.current = true;
setBusy(true);
setError('');
try {
await apiJson('/api/billing/cancel', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
reason,
details: details.trim() || undefined,
rating: rating || undefined,
review: review.trim() || undefined,
review_public_ok: publicOk,
}),
});
track('SubscriptionCanceled', { props: { plan, reason, rating: rating || undefined } });
onCanceled();
} catch (e) {
setError(e?.detail || 'Could not cancel. Please try again or email info@openshorts.app.');
sending.current = false;
setBusy(false);
}
};
const shown = hover || rating;
return (
<Modal isOpen onClose={busy ? undefined : keep} eyebrow={`CANCEL PLAN · ${step + 1}/3`}
title={['Why are you cancelling?', 'How was OpenShorts?', 'Confirm cancellation'][step]}>
{step === 0 && (
<div className="space-y-4">
<p className="text-sm text-muted">Your answer goes straight to the people building OpenShorts.</p>
<div className="space-y-1.5">
{REASONS.map(([value, label]) => (
<label key={value}
className={`flex items-center gap-2.5 rounded-card border px-3 py-2 text-sm cursor-pointer transition-colors
${reason === value ? 'border-brass text-ink' : 'border-rule text-ink2 hover:border-brass/60'}`}>
<input type="radio" name="cancel-reason" value={value} checked={reason === value}
onChange={() => setReason(value)} />
{label}
</label>
))}
</div>
{reason && (
<label className="block">
<span className="text-sm text-muted">{DETAIL_PROMPT[reason] || 'Anything else we should know?'} (optional)</span>
<textarea value={details} onChange={(e) => setDetails(e.target.value)} maxLength={2000} rows={3}
className="input-field w-full text-sm mt-1" />
</label>
)}
<div className="flex items-center justify-between gap-2 pt-1">
<button onClick={keep} className="btn-quiet">Keep my plan</button>
<button onClick={() => setStep(1)} disabled={!reason} className="btn-ghost px-4 py-2">Continue</button>
</div>
</div>
)}
{step === 1 && (
<div className="space-y-4">
<p className="text-sm text-muted">Rate your experience and leave a short review. It takes ten seconds and helps us more than anything else.</p>
<div className="flex items-center gap-1" onMouseLeave={() => setHover(0)}>
{[1, 2, 3, 4, 5].map((n) => (
<button key={n} type="button" aria-label={`${n} star${n > 1 ? 's' : ''}`}
onClick={() => setRating(n)} onMouseEnter={() => setHover(n)} className="p-1">
<Star size={26} className={n <= shown ? 'text-brass fill-current' : 'text-muted'} />
</button>
))}
</div>
<label className="block">
<span className="text-sm text-muted">Your review</span>
<textarea value={review} onChange={(e) => setReview(e.target.value)} maxLength={2000} rows={4}
placeholder="What worked, what didn't, who you'd recommend it to…"
className="input-field w-full text-sm mt-1" />
</label>
{review.trim() && (
<label className="flex items-start gap-2 text-sm text-ink2 cursor-pointer">
<input type="checkbox" checked={publicOk} onChange={(e) => setPublicOk(e.target.checked)} className="mt-0.5" />
OpenShorts may quote this review publicly (first name only).
</label>
)}
<div className="flex items-center justify-between gap-2 pt-1">
<button onClick={() => setStep(0)} className="btn-quiet">Back</button>
<button onClick={() => setStep(2)} disabled={!rating} className="btn-ghost px-4 py-2">Continue</button>
</div>
</div>
)}
{step === 2 && (
<div className="space-y-4 text-sm text-ink2">
<p>
Your {plan ? <b className="text-ink capitalize">{plan}</b> : null} plan stays active until{' '}
<b className="text-ink">{fmtDate(periodEnd)}</b>, with every minute you have left.
You won't be charged again.
</p>
<p>You can undo this from <i>Manage billing</i> any time before then.</p>
{error && <p className="text-danger">{error}</p>}
<div className="flex items-center justify-between gap-2 pt-1">
<button onClick={keep} disabled={busy} className="btn-primary px-4 py-2 text-xs">Keep my plan</button>
<button onClick={submit} disabled={busy} className="btn-danger px-4 py-2">
{busy && <Loader2 size={16} className="animate-spin" />}
{busy ? 'Cancelling…' : 'Cancel subscription'}
</button>
</div>
</div>
)}
</Modal>
);
}

View file

@ -0,0 +1,131 @@
import React, { useState, useRef } from 'react';
import { Loader2 } from 'lucide-react';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import Modal from './ui/Modal';
// Mirror cloud/onboarding.SOURCES / GOALS / ROLES.
const SOURCES = [
['google', 'Google search'],
['ai_assistant', 'ChatGPT, Claude or another AI'],
['youtube', 'YouTube'],
['tiktok_instagram', 'TikTok or Instagram'],
['x_twitter', 'X (Twitter)'],
['reddit', 'Reddit'],
['github', 'GitHub'],
['friend', 'A friend or colleague'],
['directory', 'Product Hunt or a tools directory'],
['newsletter_blog', 'A newsletter or blog'],
['other', 'Somewhere else'],
];
const GOALS = [
['clips_from_long_videos', 'Clips from my long videos'],
['ai_avatar_videos', 'AI avatar / UGC videos'],
['autopilot_posting', 'Auto-posting to my socials'],
['thumbnails', 'YouTube titles & thumbnails'],
['subtitles', 'Subtitles'],
['dubbing', 'Dubbing into other languages'],
['api_agents', 'API / AI agent integration'],
['self_host', 'Self-hosting OpenShorts'],
];
const ROLES = [
['creator', 'Creator / YouTuber'],
['podcaster', 'Podcaster'],
['streamer_gamer', 'Streamer / gamer'],
['agency', 'Agency or freelancer'],
['business_marketing', 'Business / marketing team'],
['educator', 'Educator / coach'],
['developer', 'Developer'],
['other', 'Other'],
];
const chip = (on) => `rounded-full border px-3 py-1.5 text-xs transition-colors ${
on ? 'border-brass bg-brass/10 text-ink' : 'border-rule text-ink2 hover:border-brass/60'}`;
// Asked once, right after sign-up, before the clip tutorial (backend:
// cloud/onboarding.py). One screen, every question optional, skippable: it
// must cost the new user seconds, not their first clip.
export default function OnboardingSurvey({ onDone }) {
const [source, setSource] = useState('');
const [sourceOther, setSourceOther] = useState('');
const [goals, setGoals] = useState([]);
const [role, setRole] = useState('');
const [busy, setBusy] = useState(false);
const sending = useRef(false);
const toggleGoal = (g) => setGoals((cur) => (cur.includes(g) ? cur.filter((x) => x !== g) : [...cur, g]));
const answered = !!(source || goals.length || role);
const send = async (skipped) => {
if (sending.current) return;
sending.current = true;
setBusy(true);
const body = skipped ? { skipped: true } : {
source: source || undefined,
source_other: source === 'other' ? sourceOther.trim() || undefined : undefined,
goals,
role: role || undefined,
};
try {
await apiJson('/api/onboarding/survey', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
});
} catch (_) { /* never block onboarding on the survey */ }
if (!skipped) track('SignupSurveyAnswered', { props: { source: source || undefined, role: role || undefined, goals: goals.join(',') || undefined } });
onDone();
};
return (
<Modal isOpen onClose={busy ? undefined : () => send(true)} eyebrow="WELCOME · 3 QUICK QUESTIONS"
title="Help us build what you need" size="lg"
footer={(
<div className="flex items-center justify-between gap-2">
<button onClick={() => send(true)} disabled={busy} className="btn-quiet">Skip</button>
<button onClick={() => send(false)} disabled={busy || !answered} className="btn-primary px-4 py-2 text-xs">
{busy && <Loader2 size={14} className="animate-spin" />} Continue
</button>
</div>
)}>
<div className="space-y-6">
<section>
<h3 className="text-sm text-ink mb-2">What do you want to make with OpenShorts? <span className="text-muted">(pick any)</span></h3>
<div className="flex flex-wrap gap-2">
{GOALS.map(([value, label]) => (
<button key={value} type="button" onClick={() => toggleGoal(value)} className={chip(goals.includes(value))}>
{label}
</button>
))}
</div>
</section>
<section>
<h3 className="text-sm text-ink mb-2">How did you hear about us?</h3>
<div className="flex flex-wrap gap-2">
{SOURCES.map(([value, label]) => (
<button key={value} type="button" onClick={() => setSource(source === value ? '' : value)} className={chip(source === value)}>
{label}
</button>
))}
</div>
{source === 'other' && (
<input value={sourceOther} onChange={(e) => setSourceOther(e.target.value)} maxLength={120}
placeholder="Where?" className="input-field w-full text-sm mt-2" />
)}
</section>
<section>
<h3 className="text-sm text-ink mb-2">What describes you best?</h3>
<div className="flex flex-wrap gap-2">
{ROLES.map(([value, label]) => (
<button key={value} type="button" onClick={() => setRole(role === value ? '' : value)} className={chip(role === value)}>
{label}
</button>
))}
</div>
</section>
</div>
</Modal>
);
}

147
tests/test_cancellation.py Normal file
View file

@ -0,0 +1,147 @@
"""The dashboard cancel flow (cloud/cancellation.py): reason + review, then a
cancel at period end.
What must hold: nothing is recorded unless Stripe accepted the cancel, the
reason reaches Stripe in its own vocabulary, the free text never reaches the
Telegram alert, and the UI offers exactly the reasons the server accepts.
"""
import asyncio
import os
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from cloud import alerts, cancellation
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class _Result:
def __init__(self, value):
self.value = value
def scalar_one_or_none(self):
return self.value
class _Session:
def __init__(self, sub, added):
self.sub, self.added = sub, added
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
def begin(self):
return self
async def execute(self, _stmt):
return _Result(self.sub)
def add(self, obj):
self.added.append(obj)
@pytest.fixture
def env(monkeypatch):
sub = SimpleNamespace(
id="sub-row", stripe_subscription_id="sub_123", plan="creator", interval="month",
status="active", cancel_at_period_end=False,
current_period_end=datetime.now(timezone.utc) + timedelta(days=12),
)
state = SimpleNamespace(sub=sub, added=[], stripe_calls=[], alerts=[], stripe_error=None)
user = SimpleNamespace(id="3f9a1c2b-0000-0000-0000-000000000000")
async def _user(_request):
return user
def _modify(sid, feedback, comment):
if state.stripe_error:
raise state.stripe_error
state.stripe_calls.append((sid, feedback, comment))
async def _alert(subject, body):
state.alerts.append((subject, body))
monkeypatch.setattr(cancellation, "get_current_user_required", _user)
monkeypatch.setattr(cancellation.database, "session", lambda: _Session(state.sub, state.added))
monkeypatch.setattr(cancellation, "_stripe_cancel_at_period_end", _modify)
monkeypatch.setattr(cancellation.analytics, "track", lambda *a, **k: None)
monkeypatch.setattr(alerts, "send_admin_alert", _alert)
return state
def _cancel(**body):
body.setdefault("reason", "too_expensive")
return asyncio.run(cancellation.cancel_subscription(
cancellation.CancelRequest(**body), request=None))
class TestCancel:
def test_cancels_at_period_end_with_the_reason_in_stripe_terms(self, env):
out = _cancel(reason="clip_quality", details="blurry", rating=2, review="meh")
assert out["ok"]
assert env.stripe_calls == [("sub_123", "low_quality", "blurry | meh")]
assert env.sub.cancel_at_period_end is True
def test_feedback_row_is_stored(self, env):
_cancel(reason="missing_feature", details=" ", rating=4, review="good",
review_public_ok=True)
(row,) = env.added
assert row.reason == "missing_feature"
assert row.details is None # whitespace is not feedback
assert row.rating == 4 and row.review == "good" and row.review_public_ok
def test_public_ok_without_a_review_is_not_recorded(self, env):
_cancel(rating=5, review_public_ok=True)
assert env.added[0].review_public_ok is False
def test_stripe_failure_records_nothing(self, env):
env.stripe_error = RuntimeError("stripe down")
with pytest.raises(HTTPException) as e:
_cancel()
assert e.value.status_code == 502
assert env.added == [] and env.alerts == []
assert env.sub.cancel_at_period_end is False
def test_unknown_reason_is_refused(self, env):
with pytest.raises(HTTPException) as e:
_cancel(reason="i hate it")
assert e.value.status_code == 422
assert env.stripe_calls == []
def test_already_canceling_is_refused(self, env):
env.sub.cancel_at_period_end = True
with pytest.raises(HTTPException) as e:
_cancel()
assert e.value.status_code == 409
@pytest.mark.parametrize("status", ["canceled", "incomplete", "incomplete_expired"])
def test_nothing_live_to_cancel(self, env, status):
env.sub.status = status
with pytest.raises(HTTPException) as e:
_cancel()
assert e.value.status_code == 409
def test_alert_never_carries_the_written_text(self, env):
_cancel(details="my name is Alice Smith", review="call me on 555-1234", rating=1)
(subject, body), = env.alerts
assert "Alice" not in body and "555" not in body
assert "3f9a1c2b" in body and "too_expensive" in body and "1/5" in body
class TestReasons:
def test_every_reason_maps_to_a_stripe_feedback_value(self):
stripe_enum = {"customer_service", "low_quality", "missing_features", "other",
"switched_service", "too_complex", "too_expensive", "unused"}
assert set(cancellation.CANCEL_REASONS.values()) <= stripe_enum
def test_the_ui_offers_exactly_the_reasons_the_server_accepts(self):
modal = open(os.path.join(REPO, "dashboard/src/components/CancelPlanModal.jsx")).read()
for value in cancellation.CANCEL_REASONS:
assert f"'{value}'" in modal, f"{value} is accepted but never offered"

View file

@ -0,0 +1,52 @@
"""Sign-up survey (cloud/onboarding.py): who gets asked, what is accepted, and
that the dashboard offers exactly the answers the server accepts."""
import os
from datetime import datetime, timedelta, timezone
import pytest
from fastapi import HTTPException
from cloud import onboarding
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class TestWhoIsAsked:
def test_a_new_account_is_asked(self):
now = datetime.now(timezone.utc)
assert onboarding.survey_pending(now - timedelta(minutes=2), answered=False)
def test_an_answer_or_a_skip_ends_it(self):
assert not onboarding.survey_pending(datetime.now(timezone.utc), answered=True)
def test_accounts_from_before_the_window_are_left_alone(self):
old = datetime.now(timezone.utc) - onboarding.SURVEY_MAX_ACCOUNT_AGE - timedelta(hours=1)
assert not onboarding.survey_pending(old, answered=False)
def test_unknown_creation_date_is_not_asked(self):
assert not onboarding.survey_pending(None, answered=False)
class TestValidation:
def test_a_skip_needs_nothing(self):
onboarding._validate(onboarding.SurveyAnswer(skipped=True))
def test_a_real_answer_passes(self):
onboarding._validate(onboarding.SurveyAnswer(
source="github", goals=["clips_from_long_videos", "ai_avatar_videos"], role="podcaster"))
@pytest.mark.parametrize("kw", [
{"source": "my cousin"}, {"role": "ceo"}, {"goals": ["world domination"]}, {},
])
def test_off_list_or_empty_answers_are_refused(self, kw):
with pytest.raises(HTTPException) as e:
onboarding._validate(onboarding.SurveyAnswer(**kw))
assert e.value.status_code == 422
class TestUiMatchesServer:
@pytest.mark.parametrize("values", [onboarding.SOURCES, onboarding.GOALS, onboarding.ROLES])
def test_every_accepted_value_is_offered(self, values):
ui = open(os.path.join(REPO, "dashboard/src/components/OnboardingSurvey.jsx")).read()
for value in values:
assert f"'{value}'" in ui, f"{value} is accepted but never offered"