From 42942aecfec6fc600a398e8c6245f31819c3acd1 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Mon, 28 Sep 2026 18:27:00 +0200 Subject: [PATCH] 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. --- CLAUDE.md | 25 +++ cloud/__init__.py | 6 +- cloud/account.py | 5 +- cloud/auth.py | 3 + cloud/billing.py | 8 +- cloud/cancellation.py | 148 ++++++++++++++++ cloud/models.py | 36 ++++ cloud/onboarding.py | 113 ++++++++++++ dashboard/src/App.jsx | 11 +- dashboard/src/components/AccountPage.jsx | 24 +++ dashboard/src/components/CancelPlanModal.jsx | 166 ++++++++++++++++++ dashboard/src/components/OnboardingSurvey.jsx | 131 ++++++++++++++ tests/test_cancellation.py | 147 ++++++++++++++++ tests/test_onboarding_survey.py | 52 ++++++ 14 files changed, 870 insertions(+), 5 deletions(-) create mode 100644 cloud/cancellation.py create mode 100644 cloud/onboarding.py create mode 100644 dashboard/src/components/CancelPlanModal.jsx create mode 100644 dashboard/src/components/OnboardingSurvey.jsx create mode 100644 tests/test_cancellation.py create mode 100644 tests/test_onboarding_survey.py diff --git a/CLAUDE.md b/CLAUDE.md index 51e40b1..6569eaf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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_` 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 diff --git a/cloud/__init__.py b/cloud/__init__.py index 221106c..982cd70 100644 --- a/cloud/__init__.py +++ b/cloud/__init__.py @@ -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) diff --git a/cloud/account.py b/cloud/account.py index 1727677..7012a9b 100644 --- a/cloud/account.py +++ b/cloud/account.py @@ -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 diff --git a/cloud/auth.py b/cloud/auth.py index 60b783e..fc9df81 100644 --- a/cloud/auth.py +++ b/cloud/auth.py @@ -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, } diff --git a/cloud/billing.py b/cloud/billing.py index 3ccf44d..9190ea3 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -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.", diff --git a/cloud/cancellation.py b/cloud/cancellation.py new file mode 100644 index 0000000..5045e34 --- /dev/null +++ b/cloud/cancellation.py @@ -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()} diff --git a/cloud/models.py b/cloud/models.py index 4831e62..5a209a4 100644 --- a/cloud/models.py +++ b/cloud/models.py @@ -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. diff --git a/cloud/onboarding.py b/cloud/onboarding.py new file mode 100644 index 0000000..27c808d --- /dev/null +++ b/cloud/onboarding.py @@ -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} diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index f207516..78ce7cd 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -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 && setShowLogin(false)} queued={typeof peekPendingJob()?.data?.payload === 'string'} />} - {tutorialPhase && ( + {showSurvey && setSurveyDone(true)} />} + {tutorialPhase && !showSurvey && ( 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() { {fmt1(m.remaining)} min + + {/* 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 && ( +
+ +
+ )} + {cancelOpen && ( + setCancelOpen(false)} + onCanceled={() => { setCancelOpen(false); refreshMe(); }} + /> + )} + {/* Only accounts that ever had a Stripe relationship can have invoices. */} {me.has_billing_account && } diff --git a/dashboard/src/components/CancelPlanModal.jsx b/dashboard/src/components/CancelPlanModal.jsx new file mode 100644 index 0000000..82f5d43 --- /dev/null +++ b/dashboard/src/components/CancelPlanModal.jsx @@ -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 ( + + {step === 0 && ( +
+

Your answer goes straight to the people building OpenShorts.

+
+ {REASONS.map(([value, label]) => ( + + ))} +
+ {reason && ( +