referrals: close D.3 — both parties get 45 days credit on conversion

The referral feature was half-built: codes captured, banner shown,
counts displayed — but no money flowed when a referred user paid.
The Settings page hard-coded "— (D.3)" for Active credits and the
marketing copy promised "50% off for 3 months" with nothing behind it.

Closing the loop:

- New `convert_referral(session, user)` in referral_service.py looks
  up the user's Referral row, stamps `converted_at` + `credited_at`,
  and extends `credit_until` by 45 days on BOTH the buyer and the
  referrer. Idempotent — replayed webhooks and renewals are no-ops.
  Stacks correctly when the user already has a credit window running
  (anchors at max(now, current_credit_until) like cli.grant_credit).

- Stripe webhook wires this into `_grant_paid`. A captured
  `first_paid_transition = user.tier != "paid"` gate avoids the DB
  lookup on every renewal event; convert_referral's own idempotency
  is the second line of defence.

- `_grant_paid` now takes `session` as its first positional arg so
  the conversion runs inside the same transaction as the tier flip
  and audit-row write. A mid-flight failure rolls everything back
  together — no partial state.

- Settings page replaces the "— (D.3)" placeholder with the live
  count of conversions still inside their 45-day credit window, plus
  a "+N days on your account" hint when the user has any credit of
  their own (referrer bonus, admin grant, or future refund-as-credit).

- Marketing copy on pricing.html + settings.html switches from "50%
  off for 3 months" to "45 days of paid access" — same economic value,
  honest about the actual mechanism (full free access rather than
  discounted billing).

Credit-amount rationale: 50% × 3 months ≈ 1.5 months of free
service ≈ 45 days. Pure-credit delivery is processor-agnostic, needs
no Stripe coupon plumbing, and stacks cleanly across referrals.

7 new tests in test_referral_conversion.py cover the happy path,
idempotency, no-referral no-op, credit stacking, deleted-referrer
survival, end-to-end webhook → credit landing, and the renewal-event
no-double-credit guarantee.

Also bundled: the Restore-button class fix from earlier
(portfolio.js — the cloud-restore "Restore" submit was unstyled and
picked up browser defaults; now uses .settings-btn like the rest of
the action-button family).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Giorgio Gilestro 2026-05-26 23:05:29 +02:00
parent 00211fec02
commit ce36ce36fd
7 changed files with 556 additions and 15 deletions

View file

@ -132,8 +132,9 @@ async def settings_page(
# Lazily assign a referral code on first visit.
user = await assign_code_if_missing(session, user)
# Stats: how many people have signed up with their code so far, and
# how many of those converted (paid). D.3 will fill `converted_at`.
# Stats: how many people have signed up with their code so far, how
# many converted (paid), and how many of those credit grants are
# still live (referrer-side bonus runway not yet expired).
pending_count = (await session.execute(
select(func.count(Referral.id))
.where(Referral.referrer_user_id == user.id)
@ -144,6 +145,32 @@ async def settings_page(
.where(Referral.referrer_user_id == user.id)
.where(Referral.converted_at.is_not(None))
)).scalar() or 0
# An "active credit" is a conversion whose credit window hasn't yet
# expired for the REFERRED user. We approximate by counting
# conversions in the last REFERRAL_CREDIT_DAYS days — simpler than
# joining against the referred user's credit_until, and matches the
# marketing copy ("45 days of paid access each").
from datetime import timedelta
from app.services.referral_service import REFERRAL_CREDIT_DAYS
credit_horizon = datetime.now(timezone.utc) - timedelta(days=REFERRAL_CREDIT_DAYS)
active_credit_count = (await session.execute(
select(func.count(Referral.id))
.where(Referral.referrer_user_id == user.id)
.where(Referral.credited_at.is_not(None))
.where(Referral.credited_at >= credit_horizon)
)).scalar() or 0
# Days of credit the user themselves has on their own account (from
# any source: referrer bonus, admin grant, refund-as-credit). None
# if no credit or it has already expired.
own_credit_days: int | None = None
if user.credit_until is not None:
cu = user.credit_until
if cu.tzinfo is None:
cu = cu.replace(tzinfo=timezone.utc)
delta = cu - datetime.now(timezone.utc)
if delta.total_seconds() > 0:
own_credit_days = max(1, -(-int(delta.total_seconds()) // 86400))
invite_url = str(request.url_for("login_page")) + f"?ref={user.referral_code}"
@ -176,6 +203,8 @@ async def settings_page(
"invite_url": invite_url,
"pending_count": int(pending_count),
"converted_count": int(converted_count),
"active_credit_count": int(active_credit_count),
"own_credit_days": own_credit_days,
"paid": paid_status(user),
"last_email_send": last_email_send,
"trial_days_remaining": trial_days_remaining,

View file

@ -232,6 +232,7 @@ async def _find_user(
async def _grant_paid(
session: AsyncSession,
user: User,
*,
customer_id: str | None,
@ -239,6 +240,11 @@ async def _grant_paid(
trial_end: int | None = None,
status: str | None = None,
) -> None:
# Capture "first paid transition" before mutating — drives the
# referral-conversion call below. Skipping the convert lookup on
# every renewal event saves a DB roundtrip per webhook.
first_paid_transition = user.tier != "paid"
user.tier = "paid"
if customer_id and user.stripe_customer_id != customer_id:
user.stripe_customer_id = customer_id
@ -253,6 +259,13 @@ async def _grant_paid(
elif status == "active":
user.stripe_trial_end_at = None
# Apply referral credit on the FIRST paid transition only.
# convert_referral is itself idempotent (no-op on missing or
# already-converted rows), so this guard is purely a perf hint.
if first_paid_transition:
from app.services.referral_service import convert_referral
await convert_referral(session, user)
async def _revoke_paid(user: User) -> None:
user.tier = "free"
@ -277,6 +290,7 @@ async def _handle_checkout_completed(
# after will carry it. We grant paid here without trial info and
# let the subscription event fill in trial_end_at moments later.
await _grant_paid(
session,
user,
customer_id=obj.get("customer"),
subscription_id=obj.get("subscription"),
@ -301,6 +315,7 @@ async def _handle_subscription_event(
# subscription.deleted (which fires after the final state lands).
if status in ("trialing", "active"):
await _grant_paid(
session,
user,
customer_id=obj.get("customer"),
subscription_id=obj.get("id"),