feat(cancel): retention offer as the last step, resume from the account page

The Stripe portal stops cancelling (its config, 2026-09-28), so the dashboard
flow is the only way out and carries the portal's retention coupon:
- GET /api/billing/retention-offer: live monthly plan, no discount on it, never
  offered before (retention_offer in the Stripe sub metadata). Any Stripe error
  means no offer, never a stuck flow. Coupon id from RETENTION_COUPON_ID.
- POST /api/billing/retention-offer/accept: applies the coupon, stores the
  feedback with outcome=retained, alerts "Cancel saved".
- POST /api/billing/resume + "Keep my subscription": undo a scheduled cancel,
  which the portal did with the cancel feature now off.
- cancellation_feedback.outcome (additive column).
This commit is contained in:
victorcavero14 2026-09-28 19:03:38 +02:00
parent 42942aecfe
commit 29c54fa04c
7 changed files with 368 additions and 28 deletions

View file

@ -230,8 +230,19 @@ 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 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 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 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 in the table.
carries Stripe's own feedback value when the portal asked for one.
The last step leads with a retention offer (`RETENTION_COUPON_ID` env, the
coupon the portal used to offer): `GET /api/billing/retention-offer` says
whether this subscription gets it (live monthly plan, no discount on it, never
offered before: `retention_offer` in the Stripe subscription metadata; any
Stripe error means no offer), `POST /api/billing/retention-offer/accept` applies
it and stores the feedback row with `outcome="retained"` (cancels store
`"canceled"`). Cancelling is OFF in the Stripe portal config since 2026-09-28,
so this flow is the only way to cancel; `POST /api/billing/resume` undoes a
scheduled cancel ("Keep my subscription" on the account page), since the
portal's renew went with its cancel feature. The webhook alert for a portal
cancel stays for cancels made from the Stripe Dashboard.
### Sign-up survey (`cloud/onboarding.py`, `OnboardingSurvey.jsx`) ### Sign-up survey (`cloud/onboarding.py`, `OnboardingSurvey.jsx`)

View file

@ -13,12 +13,22 @@ 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 this form; the webhook alert carries Stripe's own ``cancellation_details`` for
those. those.
Before the cancel, the last step offers the retention coupon (the portal's
"Stay with us: 50% off for 3 months", ``RETENTION_COUPON``). Cancelling was
turned off in the portal on 2026-09-28 so this flow, with its offer, is the only
way out. The offer is made once per subscription (``retention_offer`` in its
Stripe metadata), only on a live monthly plan with no discount on it: on a
yearly plan it would halve a whole year. Taking it stores the same feedback row
with ``outcome="retained"``. ``/api/billing/resume`` undoes a scheduled cancel,
since the portal's "renew" goes with its cancel feature.
Unlike ``account.DELETION_REASONS``, free text is fine here: these rows belong 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 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 not happen is the text reaching Telegram (see ``alerts.user_ref``), so the
alert says how long the review is, never what it says. alert says how long the review is, never what it says.
""" """
import asyncio import asyncio
import os
from typing import Optional from typing import Optional
from fastapi import APIRouter, HTTPException, Request from fastapi import APIRouter, HTTPException, Request
@ -52,6 +62,10 @@ CANCELLABLE_STATES = ("active", "trialing", "past_due")
MAX_TEXT = 2000 MAX_TEXT = 2000
# The Stripe coupon offered before a cancel (env, like every coupon id; see
# CLAUDE.md). Unset turns the offer off and the flow is reason -> review -> cancel.
RETENTION_COUPON = os.environ.get("RETENTION_COUPON_ID", "").strip()
class CancelRequest(BaseModel): class CancelRequest(BaseModel):
reason: str reason: str
@ -72,25 +86,162 @@ def _stripe_cancel_at_period_end(subscription_id: str, feedback: str, comment: s
) )
def _stripe_offer_blocked(subscription_id: str) -> bool:
"""True when this subscription already has a discount or had the offer."""
import stripe
live = stripe.Subscription.retrieve(subscription_id)
return bool(live.get("discounts") or live.get("discount")
or (live.get("metadata") or {}).get("retention_offer"))
_coupon_terms = {}
def _stripe_coupon_terms(coupon_id: str) -> dict:
if coupon_id not in _coupon_terms:
import stripe
c = stripe.Coupon.retrieve(coupon_id)
if not c.get("valid") or not c.get("percent_off"):
return {}
_coupon_terms[coupon_id] = {"percent_off": int(c["percent_off"]),
"months": c.get("duration_in_months")}
return _coupon_terms[coupon_id]
def _stripe_apply_retention(subscription_id: str, coupon_id: str):
import stripe
stripe.Subscription.modify(
subscription_id,
discounts=[{"coupon": coupon_id}],
metadata={"retention_offer": "accepted"},
)
def _stripe_resume(subscription_id: str):
import stripe
stripe.Subscription.modify(subscription_id, cancel_at_period_end=False)
def _clean(text: Optional[str]) -> Optional[str]: def _clean(text: Optional[str]) -> Optional[str]:
text = (text or "").strip() text = (text or "").strip()
return text or None return text or None
async def _renewing_sub(user_id) -> Subscription:
"""The user's subscription, if it is live and still set to renew."""
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.")
return sub
async def _offer_for(sub) -> Optional[dict]:
"""The retention offer's terms for this subscription, or None."""
if not RETENTION_COUPON or sub.status != "active" or sub.interval != "month":
return None
try:
if await asyncio.to_thread(_stripe_offer_blocked, sub.stripe_subscription_id):
return None
return await asyncio.to_thread(_stripe_coupon_terms, RETENTION_COUPON) or None
except Exception as e:
# No offer is better than a cancel flow that cannot reach its last step.
print(f"⚠️ Retention offer check failed for {sub.stripe_subscription_id}: {e}")
return None
@router.get("/api/billing/retention-offer")
async def retention_offer(request: Request):
user = await get_current_user_required(request)
sub = await _renewing_sub(user.id)
offer = await _offer_for(sub)
return {"eligible": bool(offer), **(offer or {})}
@router.post("/api/billing/retention-offer/accept")
async def accept_retention_offer(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.")
sub = await _renewing_sub(user.id)
offer = await _offer_for(sub)
if not offer:
raise HTTPException(status_code=409, detail="This offer is no longer available.")
try:
await asyncio.to_thread(_stripe_apply_retention, sub.stripe_subscription_id,
RETENTION_COUPON)
except Exception as e:
print(f"⚠️ Retention coupon failed for {user.id}: {e}")
raise HTTPException(status_code=502, detail=(
"We couldn't apply the discount right now. Please try again, "
"or email info@openshorts.app."))
details, review = _clean(body.details), _clean(body.review)
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),
outcome="retained",
))
analytics.track("RetentionOfferAccepted", user_id=user.id, plan=sub.plan,
reason=body.reason, rating=body.rating)
from .alerts import send_admin_alert, user_ref
term = f" for {offer['months']} months" if offer.get("months") else ""
await send_admin_alert(
"🛟 Cancel saved",
f"{user_ref(user.id)} was about to cancel the {sub.plan} plan "
f"(reason: {body.reason}) and took {offer['percent_off']}% off{term}.",
)
return {"ok": True, **offer}
@router.post("/api/billing/resume")
async def resume_subscription(request: Request):
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 not in CANCELLABLE_STATES or not sub.cancel_at_period_end:
raise HTTPException(status_code=409, detail="There is no scheduled cancellation to undo.")
try:
await asyncio.to_thread(_stripe_resume, sub.stripe_subscription_id)
except Exception as e:
print(f"⚠️ Stripe resume failed for {user.id}: {e}")
raise HTTPException(status_code=502, detail=(
"We couldn't resume your subscription right now. Please try again, "
"or email info@openshorts.app."))
async with database.session() as session:
async with session.begin():
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 = False
analytics.track("SubscriptionResumed", user_id=user.id, plan=sub.plan)
from .alerts import send_admin_alert, user_ref
await send_admin_alert("🔺 Cancel undone",
f"{user_ref(user.id)} resumed the {sub.plan} plan.")
return {"ok": True}
@router.post("/api/billing/cancel") @router.post("/api/billing/cancel")
async def cancel_subscription(body: CancelRequest, request: Request): async def cancel_subscription(body: CancelRequest, request: Request):
user = await get_current_user_required(request) user = await get_current_user_required(request)
if body.reason not in CANCEL_REASONS: if body.reason not in CANCEL_REASONS:
raise HTTPException(status_code=422, detail="Pick a reason from the list.") raise HTTPException(status_code=422, detail="Pick a reason from the list.")
sub = await _renewing_sub(user.id)
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) details, review = _clean(body.details), _clean(body.review)
# Stripe caps the comment at 5000 chars; ours are 2000 each. # Stripe caps the comment at 5000 chars; ours are 2000 each.
@ -119,6 +270,7 @@ async def cancel_subscription(body: CancelRequest, request: Request):
reason=body.reason, details=details, reason=body.reason, details=details,
rating=body.rating, review=review, rating=body.rating, review=review,
review_public_ok=bool(body.review_public_ok and review), review_public_ok=bool(body.review_public_ok and review),
outcome="canceled",
)) ))
row = (await session.execute( row = (await session.execute(
select(Subscription).where(Subscription.id == sub.id).with_for_update() select(Subscription).where(Subscription.id == sub.id).with_for_update()

View file

@ -20,6 +20,8 @@ _ADDITIVE_COLUMNS = (
"ALTER TABLE users ADD COLUMN IF NOT EXISTS free_plan_denied VARCHAR(32)", "ALTER TABLE users ADD COLUMN IF NOT EXISTS free_plan_denied VARCHAR(32)",
# The per-network first-video check joins first_video_grants on job_id. # The per-network first-video check joins first_video_grants on job_id.
"CREATE INDEX IF NOT EXISTS ix_usage_job_id ON usage_ledger (job_id)", "CREATE INDEX IF NOT EXISTS ix_usage_job_id ON usage_ledger (job_id)",
# cancellation_feedback shipped without it; rows before it are all cancels.
"ALTER TABLE cancellation_feedback ADD COLUMN IF NOT EXISTS outcome VARCHAR(16)",
) )

View file

@ -416,7 +416,8 @@ class LifecycleEmail(Base):
class CancellationFeedback(Base): class CancellationFeedback(Base):
"""Why a subscriber cancelled, and their review (cloud/cancellation.py). """Why a subscriber cancelled, and their review (cloud/cancellation.py).
One row per cancellation made through the dashboard flow. User-owned: the One row per pass through the dashboard flow that ended in a cancel or in
the retention offer being taken (``outcome``). User-owned: the
free text belongs to the account and is erased with it, which is why it is free text belongs to the account and is erased with it, which is why it is
allowed here and not in ``account_deletions``. allowed here and not in ``account_deletions``.
""" """
@ -432,6 +433,7 @@ class CancellationFeedback(Base):
rating = Column(Integer, nullable=True) # 1-5 rating = Column(Integer, nullable=True) # 1-5
review = Column(Text, nullable=True) review = Column(Text, nullable=True)
review_public_ok = Column(Boolean, nullable=False, default=False) review_public_ok = Column(Boolean, nullable=False, default=False)
outcome = Column(String(16), nullable=True) # canceled | retained
created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True) created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True)

View file

@ -89,6 +89,18 @@ export default function AccountPage() {
} catch (e) { setBusy(false); alert('Could not open billing portal.'); } } catch (e) { setBusy(false); alert('Could not open billing portal.'); }
}, []); }, []);
// The portal no longer cancels, and its "renew" went with that, so undoing
// a scheduled cancel happens here (cloud/cancellation.py).
const resume = useCallback(async () => {
setBusy(true);
try {
await apiJson('/api/billing/resume', { method: 'POST' });
track('SubscriptionResumed', { props: { plan } });
await refreshMe();
} catch (e) { alert(e?.detail || 'Could not resume your subscription.'); }
setBusy(false);
}, [plan, refreshMe]);
const buyTopup = useCallback(async (price_id) => { const buyTopup = useCallback(async (price_id) => {
setBusy(true); setBusy(true);
try { try {
@ -188,8 +200,8 @@ export default function AccountPage() {
</div> </div>
</div> </div>
{/* Our own cancel flow (reason + review) rather than the portal's, so {/* Our own cancel flow (reason + review + retention offer). The portal
the one moment a customer says what went wrong is not lost. */} cannot cancel (turned off in Stripe), so this is the only way out. */}
{me.has_billing_account && CANCELLABLE_STATES.includes(me.status) && !me.cancel_at_period_end && ( {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"> <div className="pt-4 mt-4 border-t border-rule text-right">
<button onClick={() => { track('CancelFlowOpened', { props: { plan } }); setCancelOpen(true); }} <button onClick={() => { track('CancelFlowOpened', { props: { plan } }); setCancelOpen(true); }}
@ -198,6 +210,14 @@ export default function AccountPage() {
</button> </button>
</div> </div>
)} )}
{me.has_billing_account && CANCELLABLE_STATES.includes(me.status) && me.cancel_at_period_end && (
<div className="pt-4 mt-4 border-t border-rule flex items-center justify-between gap-3 text-sm text-ink2">
<span>Your plan ends on {me.period_end ? new Date(me.period_end).toLocaleDateString('en-US', { month: 'long', day: 'numeric' }) : 'the end of the period'}.</span>
<button onClick={resume} disabled={busy} className="btn-ghost px-4 py-2 text-xs shrink-0">
Keep my subscription
</button>
</div>
)}
</div> </div>
{cancelOpen && ( {cancelOpen && (

View file

@ -1,4 +1,4 @@
import React, { useState, useRef } from 'react'; import React, { useState, useRef, useEffect } from 'react';
import { Loader2, Star } from 'lucide-react'; import { Loader2, Star } from 'lucide-react';
import { apiJson } from '../lib/api'; import { apiJson } from '../lib/api';
import { track } from '../lib/analytics'; import { track } from '../lib/analytics';
@ -36,7 +36,8 @@ const fmtDate = (iso) => {
// Cancel flow: reason -> review -> confirm. The cancel only happens on the // Cancel flow: reason -> review -> confirm. The cancel only happens on the
// last step, and at period end (backend: cloud/cancellation.py), so every // last step, and at period end (backend: cloud/cancellation.py), so every
// "keep my plan" exit leaves the subscription untouched. // "keep my plan" exit leaves the subscription untouched. The last step leads
// with the retention offer when the server says this subscription gets one.
export default function CancelPlanModal({ plan, periodEnd, onClose, onCanceled }) { export default function CancelPlanModal({ plan, periodEnd, onClose, onCanceled }) {
const [step, setStep] = useState(0); const [step, setStep] = useState(0);
const [reason, setReason] = useState(''); const [reason, setReason] = useState('');
@ -47,8 +48,49 @@ export default function CancelPlanModal({ plan, periodEnd, onClose, onCanceled }
const [publicOk, setPublicOk] = useState(false); const [publicOk, setPublicOk] = useState(false);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [offer, setOffer] = useState(null);
const [saved, setSaved] = useState(null);
const sending = useRef(false); const sending = useRef(false);
// Asked up front so the last step never waits on it; no answer means no offer.
useEffect(() => {
apiJson('/api/billing/retention-offer')
.then((o) => { if (o?.eligible) setOffer(o); })
.catch(() => {});
}, []);
useEffect(() => {
if (step === 2 && offer) track('RetentionOfferShown', { props: { plan, reason } });
}, [step, offer]); // eslint-disable-line react-hooks/exhaustive-deps
const feedback = () => JSON.stringify({
reason,
details: details.trim() || undefined,
rating: rating || undefined,
review: review.trim() || undefined,
review_public_ok: publicOk,
});
const acceptOffer = async () => {
if (sending.current) return;
sending.current = true;
setBusy(true);
setError('');
try {
const out = await apiJson('/api/billing/retention-offer/accept', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: feedback(),
});
track('RetentionOfferAccepted', { props: { plan, reason } });
setSaved(out);
} catch (e) {
setError(e?.detail || 'Could not apply the discount. Please try again or email info@openshorts.app.');
}
sending.current = false;
setBusy(false);
};
const keep = () => { const keep = () => {
track('CancelFlowAbandoned', { props: { step, reason: reason || undefined } }); track('CancelFlowAbandoned', { props: { step, reason: reason || undefined } });
onClose(); onClose();
@ -63,15 +105,9 @@ export default function CancelPlanModal({ plan, periodEnd, onClose, onCanceled }
await apiJson('/api/billing/cancel', { await apiJson('/api/billing/cancel', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: feedback(),
reason,
details: details.trim() || undefined,
rating: rating || undefined,
review: review.trim() || undefined,
review_public_ok: publicOk,
}),
}); });
track('SubscriptionCanceled', { props: { plan, reason, rating: rating || undefined } }); track('SubscriptionCanceled', { props: { plan, reason, rating: rating || undefined, offered: !!offer } });
onCanceled(); onCanceled();
} catch (e) { } catch (e) {
setError(e?.detail || 'Could not cancel. Please try again or email info@openshorts.app.'); setError(e?.detail || 'Could not cancel. Please try again or email info@openshorts.app.');
@ -81,10 +117,30 @@ export default function CancelPlanModal({ plan, periodEnd, onClose, onCanceled }
}; };
const shown = hover || rating; const shown = hover || rating;
const months = offer?.months ? ` for the next ${offer.months} months` : '';
if (saved) {
return (
<Modal isOpen onClose={onCanceled} eyebrow="YOU'RE STAYING" title="Discount applied">
<div className="space-y-4 text-sm text-ink2">
<p>
Thanks for giving us another go. Your plan stays as it is, and your next
{saved.months ? ` ${saved.months}` : ''} invoice{saved.months > 1 ? 's are' : ' is'}{' '}
<b className="text-ink">{saved.percent_off}% off</b>.
</p>
<p>We read every answer you gave us and will work on it.</p>
<div className="flex justify-end pt-1">
<button onClick={onCanceled} className="btn-primary px-4 py-2 text-xs">Done</button>
</div>
</div>
</Modal>
);
}
return ( return (
<Modal isOpen onClose={busy ? undefined : keep} eyebrow={`CANCEL PLAN · ${step + 1}/3`} <Modal isOpen onClose={busy ? undefined : keep} eyebrow={`CANCEL PLAN · ${step + 1}/3`}
title={['Why are you cancelling?', 'How was OpenShorts?', 'Confirm cancellation'][step]}> title={['Why are you cancelling?', 'How was OpenShorts?',
offer ? 'Before you go' : 'Confirm cancellation'][step]}>
{step === 0 && ( {step === 0 && (
<div className="space-y-4"> <div className="space-y-4">
<p className="text-sm text-muted">Your answer goes straight to the people building OpenShorts.</p> <p className="text-sm text-muted">Your answer goes straight to the people building OpenShorts.</p>
@ -145,15 +201,31 @@ export default function CancelPlanModal({ plan, periodEnd, onClose, onCanceled }
{step === 2 && ( {step === 2 && (
<div className="space-y-4 text-sm text-ink2"> <div className="space-y-4 text-sm text-ink2">
{offer && (
<div className="rounded-card border border-brass bg-brass/5 p-4 space-y-3">
<p className="text-ink">
Stay and get <b>{offer.percent_off}% off{months}</b>. Same plan, same
minutes, half the price.
</p>
<button onClick={acceptOffer} disabled={busy} className="btn-primary px-4 py-2 text-xs">
{busy && <Loader2 size={16} className="animate-spin" />}
Keep my plan with {offer.percent_off}% off
</button>
</div>
)}
<p> <p>
Your {plan ? <b className="text-ink capitalize">{plan}</b> : null} plan stays active until{' '} {offer ? 'If you still want to leave, your' : '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. <b className="text-ink">{fmtDate(periodEnd)}</b>, with every minute you have left.
You won't be charged again. You won't be charged again.
</p> </p>
<p>You can undo this from <i>Manage billing</i> any time before then.</p> <p>You can undo this from your account page any time before then.</p>
{error && <p className="text-danger">{error}</p>} {error && <p className="text-danger">{error}</p>}
<div className="flex items-center justify-between gap-2 pt-1"> <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={keep} disabled={busy}
className={offer ? 'btn-quiet' : 'btn-primary px-4 py-2 text-xs'}>
{offer ? 'Keep my plan at full price' : 'Keep my plan'}
</button>
<button onClick={submit} disabled={busy} className="btn-danger px-4 py-2"> <button onClick={submit} disabled={busy} className="btn-danger px-4 py-2">
{busy && <Loader2 size={16} className="animate-spin" />} {busy && <Loader2 size={16} className="animate-spin" />}
{busy ? 'Cancelling…' : 'Cancel subscription'} {busy ? 'Cancelling…' : 'Cancel subscription'}

View file

@ -71,6 +71,16 @@ def env(monkeypatch):
monkeypatch.setattr(cancellation, "get_current_user_required", _user) monkeypatch.setattr(cancellation, "get_current_user_required", _user)
monkeypatch.setattr(cancellation.database, "session", lambda: _Session(state.sub, state.added)) monkeypatch.setattr(cancellation.database, "session", lambda: _Session(state.sub, state.added))
monkeypatch.setattr(cancellation, "_stripe_cancel_at_period_end", _modify) monkeypatch.setattr(cancellation, "_stripe_cancel_at_period_end", _modify)
monkeypatch.setattr(cancellation, "RETENTION_COUPON", "coupon_test")
state.offer_blocked = False
state.applied = []
state.resumed = []
monkeypatch.setattr(cancellation, "_stripe_offer_blocked", lambda sid: state.offer_blocked)
monkeypatch.setattr(cancellation, "_stripe_coupon_terms",
lambda cid: {"percent_off": 50, "months": 3})
monkeypatch.setattr(cancellation, "_stripe_apply_retention",
lambda sid, cid: state.applied.append((sid, cid)))
monkeypatch.setattr(cancellation, "_stripe_resume", lambda sid: state.resumed.append(sid))
monkeypatch.setattr(cancellation.analytics, "track", lambda *a, **k: None) monkeypatch.setattr(cancellation.analytics, "track", lambda *a, **k: None)
monkeypatch.setattr(alerts, "send_admin_alert", _alert) monkeypatch.setattr(alerts, "send_admin_alert", _alert)
return state return state
@ -135,6 +145,77 @@ class TestCancel:
assert "3f9a1c2b" in body and "too_expensive" in body and "1/5" in body assert "3f9a1c2b" in body and "too_expensive" in body and "1/5" in body
def _offer():
return asyncio.run(cancellation.retention_offer(request=None))
def _accept(**body):
body.setdefault("reason", "too_expensive")
return asyncio.run(cancellation.accept_retention_offer(
cancellation.CancelRequest(**body), request=None))
class TestRetentionOffer:
def test_a_live_monthly_plan_gets_the_offer(self, env):
assert _offer() == {"eligible": True, "percent_off": 50, "months": 3}
@pytest.mark.parametrize("field,value", [
("interval", "year"), # would halve a whole year
("status", "trialing"),
("status", "past_due"), # a discount does not fix a failed card
])
def test_no_offer_outside_a_live_monthly_plan(self, env, field, value):
setattr(env.sub, field, value)
assert _offer() == {"eligible": False}
def test_no_second_offer_or_stacked_discount(self, env):
env.offer_blocked = True
assert _offer() == {"eligible": False}
with pytest.raises(HTTPException) as e:
_accept()
assert e.value.status_code == 409
assert env.applied == []
def test_a_stripe_hiccup_means_no_offer_not_a_broken_flow(self, env, monkeypatch):
def boom(_sid):
raise RuntimeError("stripe down")
monkeypatch.setattr(cancellation, "_stripe_offer_blocked", boom)
assert _offer() == {"eligible": False}
def test_taking_it_applies_the_coupon_and_keeps_the_feedback(self, env):
out = _accept(reason="not_using_it", details="busy month", rating=3)
assert out["ok"] and out["percent_off"] == 50
assert env.applied == [("sub_123", cancellation.RETENTION_COUPON)]
assert env.stripe_calls == [] # nothing was cancelled
assert env.sub.cancel_at_period_end is False
(row,) = env.added
assert row.outcome == "retained" and row.reason == "not_using_it"
(subject, body), = env.alerts
assert "busy month" not in body and "50% off" in body
def test_no_coupon_configured_no_offer(self, env, monkeypatch):
monkeypatch.setattr(cancellation, "RETENTION_COUPON", "")
assert _offer() == {"eligible": False}
def test_a_cancel_row_says_so(self, env):
_cancel()
assert env.added[0].outcome == "canceled"
class TestResume:
def test_undoes_a_scheduled_cancel(self, env):
env.sub.cancel_at_period_end = True
assert asyncio.run(cancellation.resume_subscription(request=None))["ok"]
assert env.resumed == ["sub_123"]
assert env.sub.cancel_at_period_end is False
def test_nothing_to_undo(self, env):
with pytest.raises(HTTPException) as e:
asyncio.run(cancellation.resume_subscription(request=None))
assert e.value.status_code == 409
assert env.resumed == []
class TestReasons: class TestReasons:
def test_every_reason_maps_to_a_stripe_feedback_value(self): def test_every_reason_maps_to_a_stripe_feedback_value(self):
stripe_enum = {"customer_service", "low_quality", "missing_features", "other", stripe_enum = {"customer_service", "low_quality", "missing_features", "other",