feat(funnel): first free video clipped whole, auto-partial instead of the wall, lifecycle emails
- Free source past the balance: first video (<= 60 min) clipped whole for the balance, any other clipped to the first N minutes. No 402 wall for free accounts with >= PARTIAL_MIN_MINUTES left. - cloud/lifecycle.py: welcome, first-clip nudge, win-back (optional WINBACK_PROMO_CODE from env) and abandoned-checkout recovery via after_expiration.recovery + checkout.session.expired. - Commercial emails go through send_commercial_email: opt-out honoured, unsubscribe footer and List-Unsubscribe headers (out-of-minutes too).
This commit is contained in:
parent
89f0309343
commit
725aebf1a3
16 changed files with 773 additions and 27 deletions
|
|
@ -122,3 +122,12 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
|
||||||
# BACKUP_DEST=s3://openshorts-backups/pg
|
# BACKUP_DEST=s3://openshorts-backups/pg
|
||||||
# BACKUP_S3_ENDPOINT=https://<accountid>.r2.cloudflarestorage.com
|
# BACKUP_S3_ENDPOINT=https://<accountid>.r2.cloudflarestorage.com
|
||||||
# RETENTION_DAYS=30
|
# RETENTION_DAYS=30
|
||||||
|
|
||||||
|
# Lifecycle emails (cloud/lifecycle.py, cloud mode only): welcome, a nudge a
|
||||||
|
# day after sign-up with nothing clipped, a win-back 2 days after the first
|
||||||
|
# free video, and the abandoned-checkout recovery link. The win-back carries
|
||||||
|
# a Stripe promotion code when one is set here (never commit the real code:
|
||||||
|
# this repository is public). LIFECYCLE_EMAILS_DISABLED=1 turns all four off.
|
||||||
|
# WINBACK_PROMO_CODE=
|
||||||
|
# WINBACK_PROMO_LABEL=50% off your first month
|
||||||
|
# LIFECYCLE_EMAILS_DISABLED=0
|
||||||
|
|
|
||||||
32
CLAUDE.md
32
CLAUDE.md
|
|
@ -183,6 +183,38 @@ otherwise process 45 minutes on a 20-minute reservation. `/api/status` and
|
||||||
the process response carry `partial`, and the results view says which part
|
the process response carry `partial`, and the results view says which part
|
||||||
of the video the clips came from, with the upsell for the rest.
|
of the video the clips came from, with the upsell for the rest.
|
||||||
|
|
||||||
|
### Free sources past the balance never meet the wall (`app.free_overflow`)
|
||||||
|
|
||||||
|
Since 28-sep-2026 the wall above only shows to paid plans and to free
|
||||||
|
accounts with less than `PARTIAL_MIN_MINUTES` left. For a free account whose
|
||||||
|
source is longer than its balance, `reserve_process_minutes` decides on its
|
||||||
|
own (the client sends no `max_minutes`):
|
||||||
|
|
||||||
|
- **First video, up to `FIRST_VIDEO_MAX_MINUTES` (60):** clipped whole. Only
|
||||||
|
the floored balance is reserved (it lands at zero) and the download's safety
|
||||||
|
cap (`SOURCE_CAP_MINUTES`) is the probed length, not the reservation. Once
|
||||||
|
per account: `metering.has_processed_before` (any reserved/committed
|
||||||
|
`process` row; a released one keeps the grant for the retry). The response
|
||||||
|
carries `first_video: true`; the dashboard says so and tracks
|
||||||
|
`FirstVideoGrant`.
|
||||||
|
- **Anything else:** `max_minutes` becomes the balance, so the job clips the
|
||||||
|
first N minutes exactly as if the user had taken the wall's offer. Tracked
|
||||||
|
client-side as `AutoPartial`.
|
||||||
|
|
||||||
|
### Lifecycle emails (`cloud/lifecycle.py`)
|
||||||
|
|
||||||
|
Welcome (minutes after sign-up), first-clip nudge (24-72 h, nothing
|
||||||
|
processed), win-back (2-7 days after the first committed video, no plan; with
|
||||||
|
`WINBACK_PROMO_CODE` when set) and checkout recovery (`checkout.session.expired`
|
||||||
|
with the `after_expiration.recovery` URL that `create_checkout` now enables).
|
||||||
|
Each at most once per account: a `lifecycle_emails` row is claimed before the
|
||||||
|
send (unique `user_id, kind`). The loop sends at most `BATCH` per 10-minute
|
||||||
|
tick. All four are commercial: `emails.send_commercial_email` skips
|
||||||
|
`marketing_opt_out` accounts and adds the unsubscribe footer and
|
||||||
|
`List-Unsubscribe` headers (the out-of-minutes upsell goes through it too).
|
||||||
|
The Stripe webhook endpoint must have `checkout.session.expired` enabled.
|
||||||
|
Promotion codes and coupon ids live in the env / Stripe, never in this repo.
|
||||||
|
|
||||||
### How many clips a job returns (`clip_selection.py`)
|
### How many clips a job returns (`clip_selection.py`)
|
||||||
|
|
||||||
The count is not a setting, it is derived, and every stage of the derivation
|
The count is not a setting, it is derived, and every stage of the derivation
|
||||||
|
|
|
||||||
49
app.py
49
app.py
|
|
@ -264,7 +264,7 @@ def _maybe_send_quota_email(user):
|
||||||
_last_quota_email[str(user.id)] = now
|
_last_quota_email[str(user.id)] = now
|
||||||
from cloud.emails import send_out_of_minutes_email
|
from cloud.emails import send_out_of_minutes_email
|
||||||
upgrade_url = f"{_cloud_config.settings.frontend_url}/#/pricing"
|
upgrade_url = f"{_cloud_config.settings.frontend_url}/#/pricing"
|
||||||
asyncio.create_task(send_out_of_minutes_email(user.email, upgrade_url))
|
asyncio.create_task(send_out_of_minutes_email(user.email, upgrade_url, user.id))
|
||||||
|
|
||||||
|
|
||||||
def _check_probe_rate(user_id):
|
def _check_probe_rate(user_id):
|
||||||
|
|
@ -314,6 +314,30 @@ def plan_partial_minutes(minutes_required: int, minutes_remaining: float, max_mi
|
||||||
return cap, {"processed_minutes": cap, "total_minutes": minutes_required}
|
return cap, {"processed_minutes": cap, "total_minutes": minutes_required}
|
||||||
|
|
||||||
|
|
||||||
|
def free_overflow(plan, minutes_required, minutes_remaining, max_minutes, processed_before):
|
||||||
|
"""What a free account gets for a source longer than its balance.
|
||||||
|
|
||||||
|
Returns ``(grant, max_minutes)``:
|
||||||
|
|
||||||
|
* ``grant`` is the whole (floored) balance when this is the account's first
|
||||||
|
video and it fits ``FIRST_VIDEO_MAX_MINUTES``: the video is clipped whole
|
||||||
|
and only the balance is charged, so it lands at zero.
|
||||||
|
* otherwise ``max_minutes`` becomes the balance, so the job clips the first
|
||||||
|
N minutes (``plan_partial_minutes``) instead of answering with the wall.
|
||||||
|
|
||||||
|
Anything else (a paid plan, a source that fits, a client that already named
|
||||||
|
its own cut) passes through untouched.
|
||||||
|
"""
|
||||||
|
from cloud import config as _cfg
|
||||||
|
remaining = max(0.0, float(minutes_remaining or 0))
|
||||||
|
if plan != "free" or max_minutes is not None or minutes_required <= remaining:
|
||||||
|
return None, max_minutes
|
||||||
|
if (not processed_before and remaining >= 1
|
||||||
|
and minutes_required <= _cfg.FIRST_VIDEO_MAX_MINUTES):
|
||||||
|
return int(math.floor(remaining)), None
|
||||||
|
return None, remaining
|
||||||
|
|
||||||
|
|
||||||
async def reserve_process_minutes(request, url, input_path, job_id, max_minutes=None):
|
async def reserve_process_minutes(request, url, input_path, job_id, max_minutes=None):
|
||||||
"""Meter a managed /api/process request.
|
"""Meter a managed /api/process request.
|
||||||
|
|
||||||
|
|
@ -404,15 +428,29 @@ async def reserve_process_minutes(request, url, input_path, job_id, max_minutes=
|
||||||
pass
|
pass
|
||||||
minutes = max(1, math.ceil(minutes))
|
minutes = max(1, math.ceil(minutes))
|
||||||
|
|
||||||
|
# Free account past its balance: the first video (up to
|
||||||
|
# FIRST_VIDEO_MAX_MINUTES) is clipped whole for the balance; any other is
|
||||||
|
# clipped to the first N minutes. Neither sees the wall.
|
||||||
|
grant = None
|
||||||
|
if balance.get("plan") == "free" and minutes > balance["remaining"] and max_minutes is None:
|
||||||
|
processed_before = await _metering.has_processed_before(user.id)
|
||||||
|
grant, max_minutes = free_overflow("free", minutes, balance["remaining"],
|
||||||
|
max_minutes, processed_before)
|
||||||
|
|
||||||
# A source longer than the balance can be clipped in part instead of
|
# A source longer than the balance can be clipped in part instead of
|
||||||
# refused: the wall offers "the first N minutes" (``partial_minutes`` in
|
# refused: the wall offers "the first N minutes" (``partial_minutes`` in
|
||||||
# the 402 below) and the client resubmits with ``max_minutes``.
|
# the 402 below) and the client resubmits with ``max_minutes``.
|
||||||
|
if grant is not None:
|
||||||
|
reserve, partial = grant, None
|
||||||
|
else:
|
||||||
reserve, partial = plan_partial_minutes(minutes, balance["remaining"], max_minutes)
|
reserve, partial = plan_partial_minutes(minutes, balance["remaining"], max_minutes)
|
||||||
try:
|
try:
|
||||||
reservation_id = await _metering.reserve_minutes(user.id, reserve, job_id)
|
reservation_id = await _metering.reserve_minutes(user.id, reserve, job_id)
|
||||||
# Read by process_endpoint for the download's safety cut
|
# Read by process_endpoint for the download's safety cut
|
||||||
# (SOURCE_CAP_MINUTES); kept off the return tuple on purpose.
|
# (SOURCE_CAP_MINUTES); kept off the return tuple on purpose. A granted
|
||||||
request.state.reserved_minutes = reserve
|
# first video is processed whole, so its cap is the probed length.
|
||||||
|
request.state.reserved_minutes = minutes if grant is not None else reserve
|
||||||
|
request.state.first_video = grant is not None
|
||||||
except _metering.QuotaExceeded as e:
|
except _metering.QuotaExceeded as e:
|
||||||
_maybe_send_quota_email(user)
|
_maybe_send_quota_email(user)
|
||||||
raise HTTPException(status_code=402, detail={
|
raise HTTPException(status_code=402, detail={
|
||||||
|
|
@ -2126,6 +2164,8 @@ async def lifespan(app: FastAPI):
|
||||||
# Autopilot: watch connected YouTube channels for new videos. Paused
|
# Autopilot: watch connected YouTube channels for new videos. Paused
|
||||||
# while this instance drains so only the new container submits jobs.
|
# while this instance drains so only the new container submits jobs.
|
||||||
cloud.autopilot.start(app, is_active=lambda: not _draining)
|
cloud.autopilot.start(app, is_active=lambda: not _draining)
|
||||||
|
# Welcome / first-clip / win-back emails (cloud/lifecycle.py).
|
||||||
|
cloud.lifecycle.start(is_active=lambda: not _draining)
|
||||||
# Nag on Telegram while the residential proxy is down/out of credits —
|
# Nag on Telegram while the residential proxy is down/out of credits —
|
||||||
# a single job-failure alert is easy to miss and ingest stays broken
|
# a single job-failure alert is easy to miss and ingest stays broken
|
||||||
# until someone tops the balance up.
|
# until someone tops the balance up.
|
||||||
|
|
@ -3119,7 +3159,8 @@ async def process_endpoint(
|
||||||
|
|
||||||
_enqueue_job(job_id, priority)
|
_enqueue_job(job_id, priority)
|
||||||
|
|
||||||
return {"job_id": job_id, "status": "queued", "partial": partial}
|
return {"job_id": job_id, "status": "queued", "partial": partial,
|
||||||
|
"first_video": bool(getattr(request.state, "first_video", False))}
|
||||||
|
|
||||||
def _job_view_from_disk(job_id):
|
def _job_view_from_disk(job_id):
|
||||||
"""What the disk says about a job this instance does not hold in memory.
|
"""What the disk says about a job this instance does not hold in memory.
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@ def setup_sync(app):
|
||||||
app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret)
|
app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret)
|
||||||
|
|
||||||
from . import (auth, oauth, billing, social_profiles, videos, api_keys,
|
from . import (auth, oauth, billing, social_profiles, videos, api_keys,
|
||||||
account, mcp_oauth, marketing, autopilot)
|
account, mcp_oauth, marketing, autopilot, lifecycle) # noqa: F401
|
||||||
oauth.register()
|
oauth.register()
|
||||||
billing._init_stripe()
|
billing._init_stripe()
|
||||||
app.include_router(auth.router)
|
app.include_router(auth.router)
|
||||||
|
|
@ -40,7 +40,8 @@ def setup_sync(app):
|
||||||
app.include_router(account.router)
|
app.include_router(account.router)
|
||||||
# Autopilot: clip new videos from the user's connected YouTube channel.
|
# Autopilot: clip new videos from the user's connected YouTube channel.
|
||||||
app.include_router(autopilot.router)
|
app.include_router(autopilot.router)
|
||||||
# Unsubscribe from the one commercial email (LSSI art. 21.2).
|
# Unsubscribe from commercial email (LSSI art. 21.2): the out-of-minutes
|
||||||
|
# upsell and the lifecycle emails (cloud/lifecycle.py).
|
||||||
app.include_router(marketing.router)
|
app.include_router(marketing.router)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -42,6 +42,7 @@ from .models import (
|
||||||
User, Subscription, CreditTopup, UsageLedger, MagicLinkToken,
|
User, Subscription, CreditTopup, UsageLedger, MagicLinkToken,
|
||||||
SignupAttribution, ApiKey, UploadPostProfile, UserVideo, ClipExpiryWarning,
|
SignupAttribution, ApiKey, UploadPostProfile, UserVideo, ClipExpiryWarning,
|
||||||
Project, AccountDeletion, OAuthCode, AutopilotRun, AutopilotSettings,
|
Project, AccountDeletion, OAuthCode, AutopilotRun, AutopilotSettings,
|
||||||
|
LifecycleEmail,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Every table that holds rows belonging to a user, child-first (clip_expiry_
|
# Every table that holds rows belonging to a user, child-first (clip_expiry_
|
||||||
|
|
@ -56,7 +57,7 @@ from .models import (
|
||||||
USER_OWNED_TABLES = (
|
USER_OWNED_TABLES = (
|
||||||
ClipExpiryWarning, UserVideo, Project, UsageLedger, CreditTopup,
|
ClipExpiryWarning, UserVideo, Project, UsageLedger, CreditTopup,
|
||||||
Subscription, ApiKey, SignupAttribution, UploadPostProfile, OAuthCode,
|
Subscription, ApiKey, SignupAttribution, UploadPostProfile, OAuthCode,
|
||||||
AutopilotRun, AutopilotSettings,
|
AutopilotRun, AutopilotSettings, LifecycleEmail,
|
||||||
)
|
)
|
||||||
|
|
||||||
# The optional "why are you leaving" answer, as a closed list. It was a free
|
# The optional "why are you leaving" answer, as a closed list. It was a free
|
||||||
|
|
|
||||||
|
|
@ -197,6 +197,11 @@ async def create_checkout(body: CheckoutRequest, request: Request):
|
||||||
# that already converts at ~1%.
|
# that already converts at ~1%.
|
||||||
tax_id_collection={"enabled": True},
|
tax_id_collection={"enabled": True},
|
||||||
customer_update={"name": "auto", "address": "auto"},
|
customer_update={"name": "auto", "address": "auto"},
|
||||||
|
# An unpaid session expires after 24 h; recovery makes Stripe hand the
|
||||||
|
# checkout.session.expired webhook a URL that reopens the same cart,
|
||||||
|
# which cloud/lifecycle.py mails once (1,011 of 1,126 sessions to
|
||||||
|
# 27-sep-2026 expired unpaid, none followed up).
|
||||||
|
after_expiration={"recovery": {"enabled": True, "allow_promotion_codes": True}},
|
||||||
metadata={
|
metadata={
|
||||||
"user_id": str(user.id),
|
"user_id": str(user.id),
|
||||||
"kind": entry["kind"],
|
"kind": entry["kind"],
|
||||||
|
|
@ -398,6 +403,12 @@ async def handle_event(event: dict):
|
||||||
await _track_invoice_revenue(obj)
|
await _track_invoice_revenue(obj)
|
||||||
elif etype == "charge.refunded":
|
elif etype == "charge.refunded":
|
||||||
await _track_refund(obj)
|
await _track_refund(obj)
|
||||||
|
elif etype == "checkout.session.expired":
|
||||||
|
from . import lifecycle
|
||||||
|
try:
|
||||||
|
await lifecycle.on_checkout_expired(obj)
|
||||||
|
except Exception as e: # an email must never make Stripe retry the event
|
||||||
|
print(f"⚠️ Checkout recovery email failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
async def _user_id_for_customer(session, customer_id):
|
async def _user_id_for_customer(session, customer_id):
|
||||||
|
|
|
||||||
|
|
@ -89,6 +89,16 @@ def new_subscriber_label(status: str):
|
||||||
# clips, so the wall stays as it was.
|
# clips, so the wall stays as it was.
|
||||||
PARTIAL_MIN_MINUTES = 5
|
PARTIAL_MIN_MINUTES = 5
|
||||||
|
|
||||||
|
# A free account's FIRST video is clipped whole when it runs up to this many
|
||||||
|
# minutes, even past the 20-minute balance: the balance goes to zero and the
|
||||||
|
# user sees every clip of the video they came with. Once per account (any
|
||||||
|
# reserved/committed process job disqualifies it), and the free plan itself is
|
||||||
|
# already gated (Google or permanent email, re-registration blocked 90 days).
|
||||||
|
# Longer first videos, and every later one past the balance, are clipped to
|
||||||
|
# the first N minutes automatically instead of hitting the wall.
|
||||||
|
# 0 disables the grant.
|
||||||
|
FIRST_VIDEO_MAX_MINUTES = 60
|
||||||
|
|
||||||
# Minute cap DURING the trial (across all plans). Kept for grandfathered
|
# Minute cap DURING the trial (across all plans). Kept for grandfathered
|
||||||
# 'trialing' subscriptions; removable once no subscription has status
|
# 'trialing' subscriptions; removable once no subscription has status
|
||||||
# 'trialing'.
|
# 'trialing'.
|
||||||
|
|
|
||||||
133
cloud/emails.py
133
cloud/emails.py
|
|
@ -11,11 +11,13 @@ from email.message import EmailMessage
|
||||||
from .config import settings
|
from .config import settings
|
||||||
|
|
||||||
|
|
||||||
def _send_sync(to: str, subject: str, html: str):
|
def _send_sync(to: str, subject: str, html: str, headers: dict | None = None):
|
||||||
msg = EmailMessage()
|
msg = EmailMessage()
|
||||||
msg["From"] = settings.email_from
|
msg["From"] = settings.email_from
|
||||||
msg["To"] = to
|
msg["To"] = to
|
||||||
msg["Subject"] = subject
|
msg["Subject"] = subject
|
||||||
|
for name, value in (headers or {}).items():
|
||||||
|
msg[name] = value
|
||||||
msg.set_content("This message requires an HTML-capable email client.")
|
msg.set_content("This message requires an HTML-capable email client.")
|
||||||
msg.add_alternative(html, subtype="html")
|
msg.add_alternative(html, subtype="html")
|
||||||
|
|
||||||
|
|
@ -31,17 +33,41 @@ def _send_sync(to: str, subject: str, html: str):
|
||||||
s.send_message(msg)
|
s.send_message(msg)
|
||||||
|
|
||||||
|
|
||||||
async def send_email(to: str, subject: str, html: str):
|
async def send_email(to: str, subject: str, html: str, headers: dict | None = None):
|
||||||
"""Send an email (async wrapper). Logs instead of sending if SMTP is unset."""
|
"""Send an email (async wrapper). Logs instead of sending if SMTP is unset."""
|
||||||
if not settings.smtp_configured:
|
if not settings.smtp_configured:
|
||||||
print(f"✉️ [DEV email → {to}] {subject}")
|
print(f"✉️ [DEV email → {to}] {subject}")
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
await asyncio.to_thread(_send_sync, to, subject, html)
|
await asyncio.to_thread(_send_sync, to, subject, html, headers)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"⚠️ Failed to send email to {to}: {e}")
|
print(f"⚠️ Failed to send email to {to}: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
async def send_commercial_email(user_id, to: str, subject: str, html: str) -> bool:
|
||||||
|
"""Send a commercial communication (LSSI art. 21): never to an account that
|
||||||
|
unsubscribed, and always with a one-click way out (footer link plus the
|
||||||
|
``List-Unsubscribe`` header, see cloud/marketing.py). Returns False when
|
||||||
|
the account had opted out and nothing was sent.
|
||||||
|
"""
|
||||||
|
from . import marketing
|
||||||
|
if user_id is not None and await marketing.is_opted_out(user_id):
|
||||||
|
return False
|
||||||
|
unsub = marketing.unsubscribe_url(user_id) if user_id is not None else ""
|
||||||
|
headers = {}
|
||||||
|
if unsub:
|
||||||
|
footer = (f'<a href="{unsub}" style="color:#666">Unsubscribe</a> from '
|
||||||
|
"upgrade and tips emails.")
|
||||||
|
headers = {"List-Unsubscribe": f"<{unsub}>",
|
||||||
|
"List-Unsubscribe-Post": "List-Unsubscribe=One-Click"}
|
||||||
|
else:
|
||||||
|
footer = "Reply to this email if you'd rather not get upgrade and tips emails."
|
||||||
|
html = (f'{html}<p style="font-family:system-ui,sans-serif;max-width:480px;'
|
||||||
|
f'margin:24px auto 0;color:#666;font-size:12px">{footer}</p>')
|
||||||
|
await send_email(to, subject, html, headers)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
async def send_magic_link_email(email: str, link: str):
|
async def send_magic_link_email(email: str, link: str):
|
||||||
if not settings.smtp_configured:
|
if not settings.smtp_configured:
|
||||||
print(f"✉️ [DEV magic link] {email} -> {link}")
|
print(f"✉️ [DEV magic link] {email} -> {link}")
|
||||||
|
|
@ -144,7 +170,7 @@ async def send_clips_expiring_email(email: str, clip_count: int):
|
||||||
await send_email(email, f"Your {clips} will be deleted tomorrow", html)
|
await send_email(email, f"Your {clips} will be deleted tomorrow", html)
|
||||||
|
|
||||||
|
|
||||||
async def send_out_of_minutes_email(email: str, upgrade_url: str):
|
async def send_out_of_minutes_email(email: str, upgrade_url: str, user_id=None):
|
||||||
"""Free user hit their monthly quota — the natural upgrade moment.
|
"""Free user hit their monthly quota — the natural upgrade moment.
|
||||||
|
|
||||||
Mirrors the in-app upgrade modal: lead with what they lose by staying free
|
Mirrors the in-app upgrade modal: lead with what they lose by staying free
|
||||||
|
|
@ -168,8 +194,9 @@ async def send_out_of_minutes_email(email: str, upgrade_url: str):
|
||||||
reset on the 1st of every month.</p>
|
reset on the 1st of every month.</p>
|
||||||
</div>
|
</div>
|
||||||
"""
|
"""
|
||||||
|
if await send_commercial_email(user_id, email,
|
||||||
|
"Your video is waiting — you're out of free minutes", html):
|
||||||
print(f"✉️ Out-of-minutes upsell email → {email}")
|
print(f"✉️ Out-of-minutes upsell email → {email}")
|
||||||
await send_email(email, "Your video is waiting — you're out of free minutes", html)
|
|
||||||
|
|
||||||
|
|
||||||
async def send_account_deleted_email(email: str):
|
async def send_account_deleted_email(email: str):
|
||||||
|
|
@ -200,3 +227,99 @@ async def send_account_deleted_email(email: str):
|
||||||
"""
|
"""
|
||||||
print(f"✉️ Account-deleted confirmation → {email}")
|
print(f"✉️ Account-deleted confirmation → {email}")
|
||||||
await send_email(email, "Your OpenShorts account has been deleted", html)
|
await send_email(email, "Your OpenShorts account has been deleted", html)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
# Lifecycle emails (cloud/lifecycle.py decides who gets which, and when).
|
||||||
|
# All of them are commercial communications: send_commercial_email skips
|
||||||
|
# accounts that unsubscribed and adds the unsubscribe footer and header.
|
||||||
|
# --------------------------------------------------------------------------- #
|
||||||
|
def _cta(url: str, label: str) -> str:
|
||||||
|
return (f'<p><a href="{url}" style="display:inline-block;background:#111;color:#fff;'
|
||||||
|
f'padding:12px 20px;border-radius:8px;text-decoration:none">{label}</a></p>')
|
||||||
|
|
||||||
|
|
||||||
|
def _first_video_line(first_video_minutes: int) -> str:
|
||||||
|
if first_video_minutes > 0:
|
||||||
|
return (f"<p><strong>Your first video is on us:</strong> anything up to "
|
||||||
|
f"{first_video_minutes} minutes is clipped whole, free.</p>")
|
||||||
|
return "<p>You get 20 free minutes every month.</p>"
|
||||||
|
|
||||||
|
|
||||||
|
async def send_welcome_email(user_id, email: str, first_video_minutes: int) -> bool:
|
||||||
|
"""Right after sign-up: one concrete next step, not a feature tour."""
|
||||||
|
app_url = f"{settings.frontend_url}/#app"
|
||||||
|
html = f"""
|
||||||
|
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
|
||||||
|
<h2>Welcome to OpenShorts 👋</h2>
|
||||||
|
<p>Paste a YouTube link (or upload a video) and you get vertical clips
|
||||||
|
with captions, ready for TikTok, Reels and Shorts, in a few minutes.</p>
|
||||||
|
{_first_video_line(first_video_minutes)}
|
||||||
|
{_cta(app_url, "Clip my first video")}
|
||||||
|
<p style="color:#666;font-size:13px">Works best with people talking:
|
||||||
|
podcasts, interviews, streams, tutorials.</p>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
return await send_commercial_email(user_id, email, "Your first video is on us", html)
|
||||||
|
|
||||||
|
|
||||||
|
async def send_first_clip_email(user_id, email: str, first_video_minutes: int) -> bool:
|
||||||
|
"""A day after sign-up with no video processed yet."""
|
||||||
|
app_url = f"{settings.frontend_url}/#app"
|
||||||
|
html = f"""
|
||||||
|
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
|
||||||
|
<h2>Your clips are one link away</h2>
|
||||||
|
<p>You signed up yesterday but haven't clipped anything yet. It takes
|
||||||
|
one step: paste the link of a video you already published.</p>
|
||||||
|
{_first_video_line(first_video_minutes)}
|
||||||
|
{_cta(app_url, "Paste a link")}
|
||||||
|
<p style="color:#666;font-size:13px">Stuck on something? Just reply to
|
||||||
|
this email.</p>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
return await send_commercial_email(user_id, email, "Your first video is still free", html)
|
||||||
|
|
||||||
|
|
||||||
|
async def send_winback_email(user_id, email: str, promo_code: str = "",
|
||||||
|
promo_label: str = "") -> bool:
|
||||||
|
"""Two days after the first free video, still no plan."""
|
||||||
|
pricing = f"{settings.frontend_url}/#/pricing"
|
||||||
|
if promo_code:
|
||||||
|
offer = (f"<p>Here's <strong>{promo_label or 'a discount'}</strong>: use code "
|
||||||
|
f"<strong style=\"font-family:monospace;font-size:16px\">{promo_code}</strong> "
|
||||||
|
f"at checkout.</p>")
|
||||||
|
subject = f"{promo_label or 'A discount'} on OpenShorts, for you"
|
||||||
|
else:
|
||||||
|
offer = ""
|
||||||
|
subject = "Keep your clips, lose the watermark"
|
||||||
|
html = f"""
|
||||||
|
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
|
||||||
|
<h2>Liked your clips?</h2>
|
||||||
|
<p>Free clips carry a watermark and are deleted after 7 days. Starter
|
||||||
|
($12/mo) gives you 100 minutes a month, no watermark, and clips
|
||||||
|
stored forever.</p>
|
||||||
|
{offer}
|
||||||
|
{_cta(pricing, "See plans")}
|
||||||
|
<p style="color:#666;font-size:13px">Cancel anytime.</p>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
return await send_commercial_email(user_id, email, subject, html)
|
||||||
|
|
||||||
|
|
||||||
|
async def send_checkout_recovery_email(user_id, email: str, recovery_url: str,
|
||||||
|
amount_label: str = "") -> bool:
|
||||||
|
"""A Stripe Checkout expired unpaid. ``recovery_url`` reopens the same cart
|
||||||
|
(valid 30 days, Stripe's ``after_expiration.recovery``)."""
|
||||||
|
what = f"your OpenShorts plan ({amount_label})" if amount_label else "your OpenShorts plan"
|
||||||
|
html = f"""
|
||||||
|
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
|
||||||
|
<h2>You didn't finish checking out</h2>
|
||||||
|
<p>You started upgrading to {what} but the payment wasn't completed.
|
||||||
|
Your cart is saved: one click takes you back to it.</p>
|
||||||
|
{_cta(recovery_url, "Finish checkout")}
|
||||||
|
<p style="color:#666;font-size:13px">Card declined? PayPal and other
|
||||||
|
methods are on the same page. Reply to this email if something
|
||||||
|
didn't work.</p>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
return await send_commercial_email(user_id, email, "Your OpenShorts checkout is saved", html)
|
||||||
|
|
|
||||||
232
cloud/lifecycle.py
Normal file
232
cloud/lifecycle.py
Normal file
|
|
@ -0,0 +1,232 @@
|
||||||
|
"""Lifecycle emails: the follow-ups a free sign-up gets on the way to a plan.
|
||||||
|
|
||||||
|
Measured on the 30 days to 27-sep-2026: 8.5k sign-ups, ~4.3k with clips, ~400
|
||||||
|
checkouts started, ~90 paid, and until now not one email in between: no
|
||||||
|
welcome, no nudge for the half that never clipped anything, nothing after an
|
||||||
|
abandoned Stripe Checkout (1,011 expired sessions since launch). Four emails,
|
||||||
|
each at most once per account:
|
||||||
|
|
||||||
|
* ``welcome`` — minutes after sign-up.
|
||||||
|
* ``first_clip`` — 24-72 h after sign-up, nothing processed yet.
|
||||||
|
* ``winback`` — 2-7 days after the first processed video, no plan.
|
||||||
|
Carries ``WINBACK_PROMO_CODE`` when it is set (a
|
||||||
|
Stripe promotion code; lives in the env, not here,
|
||||||
|
because this repository is public).
|
||||||
|
* ``checkout_recovery`` — on ``checkout.session.expired`` (billing webhook),
|
||||||
|
with Stripe's recovery URL for the same cart.
|
||||||
|
|
||||||
|
The first three come from a loop (``TICK_SECONDS``) that sends at most
|
||||||
|
``BATCH`` per tick, so the backlog on the first deploy drains slowly instead
|
||||||
|
of hammering the SMTP relay. A ``LifecycleEmail`` row is inserted before each
|
||||||
|
send; its (user_id, kind) unique constraint is what stops a second container
|
||||||
|
(during a rolling deploy) or a second tick from sending the same email.
|
||||||
|
|
||||||
|
All four are commercial communications: they go through
|
||||||
|
``emails.send_commercial_email`` (skips unsubscribed accounts, adds the
|
||||||
|
unsubscribe footer and header). ``LIFECYCLE_EMAILS_DISABLED=1`` turns the loop
|
||||||
|
and the recovery email off.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from sqlalchemy import and_, exists, func, select
|
||||||
|
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||||
|
|
||||||
|
from . import config, database, emails, metering
|
||||||
|
from .models import LifecycleEmail, Subscription, UsageLedger, User
|
||||||
|
|
||||||
|
TICK_SECONDS = 10 * 60
|
||||||
|
BATCH = 30 # emails per tick, all kinds together (~180/h at most)
|
||||||
|
|
||||||
|
WELCOME_AFTER = timedelta(minutes=5)
|
||||||
|
WELCOME_UNTIL = timedelta(hours=24)
|
||||||
|
FIRST_CLIP_AFTER = timedelta(hours=24)
|
||||||
|
FIRST_CLIP_UNTIL = timedelta(hours=72)
|
||||||
|
WINBACK_AFTER = timedelta(hours=48)
|
||||||
|
WINBACK_UNTIL = timedelta(days=7)
|
||||||
|
|
||||||
|
# Subscription states that mean "already a customer": no upsell, no nudges.
|
||||||
|
# ``incomplete`` is left out on purpose: that is a Checkout whose first
|
||||||
|
# payment failed, exactly who the recovery email is for.
|
||||||
|
_CUSTOMER_STATES = ("active", "trialing", "past_due", "unpaid")
|
||||||
|
|
||||||
|
_is_active = None
|
||||||
|
_task = None
|
||||||
|
|
||||||
|
|
||||||
|
def disabled() -> bool:
|
||||||
|
return os.environ.get("LIFECYCLE_EMAILS_DISABLED", "").lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
|
|
||||||
|
def _now():
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def promo() -> tuple[str, str]:
|
||||||
|
"""(code, label) of the win-back discount, or ("", "") when unset."""
|
||||||
|
code = os.environ.get("WINBACK_PROMO_CODE", "").strip()
|
||||||
|
label = os.environ.get("WINBACK_PROMO_LABEL", "").strip()
|
||||||
|
return code, (label if code else "")
|
||||||
|
|
||||||
|
|
||||||
|
def amount_label(session_obj: dict) -> str:
|
||||||
|
""""$12.00" style label for a Checkout Session, or ""."""
|
||||||
|
amount = session_obj.get("amount_total")
|
||||||
|
currency = (session_obj.get("currency") or "").upper()
|
||||||
|
if not amount or not currency:
|
||||||
|
return ""
|
||||||
|
value = f"{amount / 100:.2f}"
|
||||||
|
return f"${value}" if currency == "USD" else f"{value} {currency}"
|
||||||
|
|
||||||
|
|
||||||
|
async def claim(user_id, kind: str) -> bool:
|
||||||
|
"""Reserve the right to send ``kind`` to this account. True exactly once."""
|
||||||
|
async with database.session() as s:
|
||||||
|
async with s.begin():
|
||||||
|
row = (await s.execute(
|
||||||
|
pg_insert(LifecycleEmail).values(user_id=user_id, kind=kind)
|
||||||
|
.on_conflict_do_nothing(constraint="uq_lifecycle_user_kind")
|
||||||
|
.returning(LifecycleEmail.id)
|
||||||
|
)).first()
|
||||||
|
return row is not None
|
||||||
|
|
||||||
|
|
||||||
|
def _not_sent(kind):
|
||||||
|
return ~exists().where(and_(LifecycleEmail.user_id == User.id,
|
||||||
|
LifecycleEmail.kind == kind))
|
||||||
|
|
||||||
|
|
||||||
|
def _not_customer():
|
||||||
|
return ~exists().where(and_(Subscription.user_id == User.id,
|
||||||
|
Subscription.status.in_(_CUSTOMER_STATES)))
|
||||||
|
|
||||||
|
|
||||||
|
def _processed():
|
||||||
|
return exists().where(and_(UsageLedger.user_id == User.id,
|
||||||
|
UsageLedger.job_type == "process",
|
||||||
|
UsageLedger.status.in_(("reserved", "committed"))))
|
||||||
|
|
||||||
|
|
||||||
|
async def _candidates(kind: str, limit: int, now=None):
|
||||||
|
"""User rows due for ``kind`` right now (oldest first)."""
|
||||||
|
now = now or _now()
|
||||||
|
q = select(User).where(_not_sent(kind), _not_customer(),
|
||||||
|
User.marketing_opt_out.is_(False))
|
||||||
|
if kind == "welcome":
|
||||||
|
q = q.where(User.created_at <= now - WELCOME_AFTER,
|
||||||
|
User.created_at >= now - WELCOME_UNTIL)
|
||||||
|
elif kind == "first_clip":
|
||||||
|
q = q.where(User.created_at <= now - FIRST_CLIP_AFTER,
|
||||||
|
User.created_at >= now - FIRST_CLIP_UNTIL,
|
||||||
|
~_processed())
|
||||||
|
elif kind == "winback":
|
||||||
|
first_job = (select(func.min(UsageLedger.created_at))
|
||||||
|
.where(and_(UsageLedger.user_id == User.id,
|
||||||
|
UsageLedger.job_type == "process",
|
||||||
|
UsageLedger.status == "committed"))
|
||||||
|
.scalar_subquery())
|
||||||
|
q = q.where(first_job <= now - WINBACK_AFTER, first_job >= now - WINBACK_UNTIL)
|
||||||
|
else:
|
||||||
|
raise ValueError(kind)
|
||||||
|
async with database.session() as s:
|
||||||
|
return list((await s.execute(q.order_by(User.created_at.asc()).limit(limit))).scalars())
|
||||||
|
|
||||||
|
|
||||||
|
async def _send(kind: str, user) -> bool:
|
||||||
|
# The welcome and first-clip emails promise free minutes: only to accounts
|
||||||
|
# that actually have them (not temp-mail, not re-registered after erasure).
|
||||||
|
# Claimed first even when skipped, so an ineligible account is not picked
|
||||||
|
# up (and does not eat the batch) again on every tick.
|
||||||
|
if not await claim(user.id, kind):
|
||||||
|
return False
|
||||||
|
first_video = config.FIRST_VIDEO_MAX_MINUTES
|
||||||
|
if kind in ("welcome", "first_clip"):
|
||||||
|
if not metering.free_plan_eligible(user):
|
||||||
|
return False
|
||||||
|
# A first video already processed (welcome sent late) has no grant left.
|
||||||
|
if await metering.has_processed_before(user.id):
|
||||||
|
first_video = 0
|
||||||
|
if kind == "welcome":
|
||||||
|
return await emails.send_welcome_email(user.id, user.email, first_video)
|
||||||
|
if kind == "first_clip":
|
||||||
|
return await emails.send_first_clip_email(user.id, user.email, first_video)
|
||||||
|
code, label = promo()
|
||||||
|
return await emails.send_winback_email(user.id, user.email, code, label)
|
||||||
|
|
||||||
|
|
||||||
|
async def run_once(now=None) -> int:
|
||||||
|
"""One tick: send up to ``BATCH`` due emails. Returns how many went out."""
|
||||||
|
budget = BATCH
|
||||||
|
sent = 0
|
||||||
|
for kind in ("welcome", "first_clip", "winback"):
|
||||||
|
if budget <= 0:
|
||||||
|
break
|
||||||
|
for user in await _candidates(kind, budget, now):
|
||||||
|
if _is_active is not None and not _is_active():
|
||||||
|
return sent # draining for a deploy: the new instance takes over
|
||||||
|
try:
|
||||||
|
if await _send(kind, user):
|
||||||
|
sent += 1
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ Lifecycle {kind} email failed for {user.id}: {e}")
|
||||||
|
budget -= 1
|
||||||
|
await asyncio.sleep(1) # be gentle with the SMTP relay
|
||||||
|
if sent:
|
||||||
|
print(f"✉️ Lifecycle emails sent this tick: {sent}")
|
||||||
|
return sent
|
||||||
|
|
||||||
|
|
||||||
|
async def _recovery_target(user_id):
|
||||||
|
"""The account behind an expired checkout, unless it is gone or already
|
||||||
|
paying (it may have paid in another session meanwhile)."""
|
||||||
|
async with database.session() as s:
|
||||||
|
user = await s.get(User, user_id)
|
||||||
|
if user is None:
|
||||||
|
return None
|
||||||
|
customer = (await s.execute(select(Subscription.id).where(and_(
|
||||||
|
Subscription.user_id == user.id,
|
||||||
|
Subscription.status.in_(_CUSTOMER_STATES))))).first()
|
||||||
|
return None if customer is not None else user
|
||||||
|
|
||||||
|
|
||||||
|
async def on_checkout_expired(session_obj: dict) -> bool:
|
||||||
|
"""``checkout.session.expired``: mail the recovery link, once per account."""
|
||||||
|
if disabled():
|
||||||
|
return False
|
||||||
|
recovery = ((session_obj.get("after_expiration") or {}).get("recovery") or {})
|
||||||
|
url = recovery.get("url")
|
||||||
|
user_id = (session_obj.get("client_reference_id")
|
||||||
|
or (session_obj.get("metadata") or {}).get("user_id"))
|
||||||
|
if not url or not user_id:
|
||||||
|
return False
|
||||||
|
user = await _recovery_target(user_id)
|
||||||
|
if user is None:
|
||||||
|
return False
|
||||||
|
if not await claim(user.id, "checkout_recovery"):
|
||||||
|
return False
|
||||||
|
return await emails.send_checkout_recovery_email(
|
||||||
|
user.id, user.email, url, amount_label(session_obj))
|
||||||
|
|
||||||
|
|
||||||
|
async def _loop():
|
||||||
|
await asyncio.sleep(90) # let the instance finish booting and resuming jobs
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
if _is_active is None or _is_active():
|
||||||
|
await run_once()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
return
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ Lifecycle loop error: {e}")
|
||||||
|
await asyncio.sleep(TICK_SECONDS)
|
||||||
|
|
||||||
|
|
||||||
|
def start(is_active=None):
|
||||||
|
"""Start the loop. ``is_active`` returns False while the instance drains."""
|
||||||
|
global _is_active, _task
|
||||||
|
_is_active = is_active
|
||||||
|
if disabled():
|
||||||
|
print("✉️ Lifecycle emails disabled (LIFECYCLE_EMAILS_DISABLED).")
|
||||||
|
return
|
||||||
|
_task = asyncio.create_task(_loop())
|
||||||
|
|
@ -1,12 +1,13 @@
|
||||||
"""Opting out of the one email we send that is a commercial communication.
|
"""Opting out of the emails we send that are commercial communications.
|
||||||
|
|
||||||
Every other message OpenShorts sends is a service notice: a sign-in link, "your
|
Most messages OpenShorts sends are service notices: a sign-in link, "your
|
||||||
clips are ready", "your free clips are deleted tomorrow", "your account has been
|
clips are ready", "your free clips are deleted tomorrow", "your account has been
|
||||||
deleted". ``send_out_of_minutes_email`` is not — it leads with a price and a
|
deleted". ``send_out_of_minutes_email`` and the lifecycle emails
|
||||||
Buy button, which makes it a comunicación comercial under LSSI art. 21. Art.
|
(cloud/lifecycle.py) are not — they sell a plan, which makes them a
|
||||||
21.2 permits it to an existing customer for a similar product, but only if
|
comunicación comercial under LSSI art. 21. Art. 21.2 permits them to an
|
||||||
*every single message* offers a simple, free way to refuse — and until now it
|
existing customer for a similar product, but only if *every single message*
|
||||||
offered none: no footer link and no ``List-Unsubscribe`` header.
|
offers a simple, free way to refuse: ``emails.send_commercial_email`` adds the
|
||||||
|
footer link and the ``List-Unsubscribe`` header, and skips opted-out accounts.
|
||||||
|
|
||||||
The link has to work with no session (the reader is in their mail client, not
|
The link has to work with no session (the reader is in their mail client, not
|
||||||
the app) and must never expire, so it carries an HMAC of the user id keyed on
|
the app) and must never expire, so it carries an HMAC of the user id keyed on
|
||||||
|
|
|
||||||
|
|
@ -439,6 +439,23 @@ async def _plan_used_this_period(session, user_id, period_end) -> Decimal:
|
||||||
return _D(total)
|
return _D(total)
|
||||||
|
|
||||||
|
|
||||||
|
async def has_processed_before(user_id) -> bool:
|
||||||
|
"""True once the account has any live (reserved/committed) process job.
|
||||||
|
|
||||||
|
Released reservations (a job that failed or never started) don't count, so
|
||||||
|
a first video that errors out keeps the first-video grant for the retry.
|
||||||
|
"""
|
||||||
|
async with database.session() as session:
|
||||||
|
row = (await session.execute(
|
||||||
|
select(UsageLedger.id).where(and_(
|
||||||
|
UsageLedger.user_id == user_id,
|
||||||
|
UsageLedger.job_type == "process",
|
||||||
|
UsageLedger.status.in_(("reserved", "committed")),
|
||||||
|
)).limit(1)
|
||||||
|
)).first()
|
||||||
|
return row is not None
|
||||||
|
|
||||||
|
|
||||||
async def _topups_fifo(session, user_id):
|
async def _topups_fifo(session, user_id):
|
||||||
return list((await session.execute(
|
return list((await session.execute(
|
||||||
select(CreditTopup).where(CreditTopup.user_id == user_id)
|
select(CreditTopup).where(CreditTopup.user_id == user_id)
|
||||||
|
|
|
||||||
|
|
@ -25,11 +25,12 @@ class User(Base):
|
||||||
stripe_customer_id = Column(Text, unique=True, nullable=True)
|
stripe_customer_id = Column(Text, unique=True, nullable=True)
|
||||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
last_login_at = Column(DateTime(timezone=True), nullable=True)
|
last_login_at = Column(DateTime(timezone=True), nullable=True)
|
||||||
# Set by the unsubscribe link in the only email we send that is a
|
# Set by the unsubscribe link in the emails that are commercial
|
||||||
# commercial communication rather than a service notice (the out-of-minutes
|
# communications rather than service notices (the out-of-minutes upsell and
|
||||||
# upsell). LSSI art. 21.2 lets us mail our own customers about a similar
|
# the lifecycle emails). LSSI art. 21.2 lets us mail our own customers about
|
||||||
# product, but only if every message carries a way out — so this column is
|
# a similar product, but only if every message carries a way out — so this
|
||||||
# what that link writes, and cloud/emails.py refuses to send when it is set.
|
# column is what that link writes, and emails.send_commercial_email refuses
|
||||||
|
# to send when it is set.
|
||||||
# Schema bootstrap is create_all, which never ALTERs: see
|
# Schema bootstrap is create_all, which never ALTERs: see
|
||||||
# cloud/database.init_engine for the additive statement that adds it to an
|
# cloud/database.init_engine for the additive statement that adds it to an
|
||||||
# existing database.
|
# existing database.
|
||||||
|
|
@ -390,3 +391,22 @@ class AutopilotRun(Base):
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint("user_id", "video_id", name="uq_autopilot_user_video"),
|
UniqueConstraint("user_id", "video_id", name="uq_autopilot_user_video"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class LifecycleEmail(Base):
|
||||||
|
"""One lifecycle email sent to one account (cloud/lifecycle.py).
|
||||||
|
|
||||||
|
The (user_id, kind) unique constraint is the dedupe and the claim: the row
|
||||||
|
is inserted BEFORE the email goes out, so two API containers running the
|
||||||
|
loop during a deploy never both send it, and an account never gets the
|
||||||
|
same kind twice.
|
||||||
|
"""
|
||||||
|
__tablename__ = "lifecycle_emails"
|
||||||
|
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)
|
||||||
|
kind = Column(String(32), nullable=False) # welcome | first_clip | winback | checkout_recovery
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("user_id", "kind", name="uq_lifecycle_user_kind"),
|
||||||
|
)
|
||||||
|
|
|
||||||
|
|
@ -276,6 +276,8 @@ function App() {
|
||||||
// {processed_minutes, total_minutes} when the running/finished job clips
|
// {processed_minutes, total_minutes} when the running/finished job clips
|
||||||
// only the first part of the source (the quota wall's free offer).
|
// only the first part of the source (the quota wall's free offer).
|
||||||
const [partialJob, setPartialJob] = useState(null);
|
const [partialJob, setPartialJob] = useState(null);
|
||||||
|
// The free plan's first video, clipped whole past the 20-minute balance.
|
||||||
|
const [firstVideoJob, setFirstVideoJob] = useState(false);
|
||||||
// {position, ahead, eta_seconds} while the job waits in line, else null.
|
// {position, ahead, eta_seconds} while the job waits in line, else null.
|
||||||
const [queueInfo, setQueueInfo] = useState(null);
|
const [queueInfo, setQueueInfo] = useState(null);
|
||||||
// Why the last job could not start or failed, in plain words (or '').
|
// Why the last job could not start or failed, in plain words (or '').
|
||||||
|
|
@ -968,6 +970,7 @@ function App() {
|
||||||
setProjectState(null);
|
setProjectState(null);
|
||||||
setNoSource(false);
|
setNoSource(false);
|
||||||
setPartialJob(null);
|
setPartialJob(null);
|
||||||
|
setFirstVideoJob(false);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let body;
|
let body;
|
||||||
|
|
@ -1037,6 +1040,13 @@ function App() {
|
||||||
|
|
||||||
setJobId(resData.job_id);
|
setJobId(resData.job_id);
|
||||||
setPartialJob(resData.partial || null);
|
setPartialJob(resData.partial || null);
|
||||||
|
setFirstVideoJob(!!resData.first_video);
|
||||||
|
// The server clipped past the balance on its own (no wall): the first
|
||||||
|
// video whole, or the first N minutes of a later one.
|
||||||
|
if (resData.first_video) track('FirstVideoGrant');
|
||||||
|
else if (resData.partial && data.maxMinutes == null) {
|
||||||
|
track('AutoPartial', { props: { processed: resData.partial.processed_minutes, total: resData.partial.total_minutes } });
|
||||||
|
}
|
||||||
if (data.type === 'thumbnail_session') {
|
if (data.type === 'thumbnail_session') {
|
||||||
setProcessingMedia({ type: 'server', payload: `/api/source/${resData.job_id}` });
|
setProcessingMedia({ type: 'server', payload: `/api/source/${resData.job_id}` });
|
||||||
}
|
}
|
||||||
|
|
@ -1112,6 +1122,7 @@ function App() {
|
||||||
setProjectState(null);
|
setProjectState(null);
|
||||||
setNoSource(false);
|
setNoSource(false);
|
||||||
setPartialJob(null);
|
setPartialJob(null);
|
||||||
|
setFirstVideoJob(false);
|
||||||
setQueueInfo(null);
|
setQueueInfo(null);
|
||||||
setJobError('');
|
setJobError('');
|
||||||
localStorage.removeItem(SESSION_KEY);
|
localStorage.removeItem(SESSION_KEY);
|
||||||
|
|
@ -2111,7 +2122,17 @@ function App() {
|
||||||
)}
|
)}
|
||||||
{/* Peak-moment upsell: they just SAW their clips — sell while
|
{/* Peak-moment upsell: they just SAW their clips — sell while
|
||||||
they're proud of the result, before asking for stars. */}
|
they're proud of the result, before asking for stars. */}
|
||||||
{plan === 'free' && !partialJob && (
|
{firstVideoJob && !partialJob && (
|
||||||
|
<button
|
||||||
|
onClick={() => { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); }}
|
||||||
|
className="w-full text-left px-3 py-2.5 rounded-input bg-paper3 border border-brass/40 hover:border-brass text-sm transition-colors"
|
||||||
|
>
|
||||||
|
<span className="text-ink">Your first video is on us: we clipped all of it.</span>{' '}
|
||||||
|
<span className="text-muted">That used this month's free minutes.</span>{' '}
|
||||||
|
<span className="text-brass font-medium">Keep clipping →</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{plan === 'free' && !partialJob && !firstVideoJob && (
|
||||||
<button
|
<button
|
||||||
onClick={() => { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); }}
|
onClick={() => { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); }}
|
||||||
className="w-full text-left px-3 py-2.5 rounded-input bg-paper3 border border-brass/40 hover:border-brass text-sm transition-colors"
|
className="w-full text-left px-3 py-2.5 rounded-input bg-paper3 border border-brass/40 hover:border-brass text-sm transition-colors"
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,10 @@ import { firstTouchProps } from './attribution';
|
||||||
// - CheckoutFailed — /api/billing/checkout errored, `reason` says why
|
// - CheckoutFailed — /api/billing/checkout errored, `reason` says why
|
||||||
// - PartialClipChosen — the wall's "clip the first N min" taken instead of a
|
// - PartialClipChosen — the wall's "clip the first N min" taken instead of a
|
||||||
// plan (`required` / `partial` minutes)
|
// plan (`required` / `partial` minutes)
|
||||||
|
// - FirstVideoGrant — free account's first video (<= 60 min) clipped whole
|
||||||
|
// past its balance, no wall shown
|
||||||
|
// - AutoPartial — free source past the balance clipped to the first N
|
||||||
|
// minutes by the server, no wall shown
|
||||||
// - Subscribed — plan activated after checkout
|
// - Subscribed — plan activated after checkout
|
||||||
// - SocialNudgeSeen — post-generation "connect socials" banner rendered
|
// - SocialNudgeSeen — post-generation "connect socials" banner rendered
|
||||||
// - SocialNudgeConnect — its connect button clicked (opens hosted connect page)
|
// - SocialNudgeConnect — its connect button clicked (opens hosted connect page)
|
||||||
|
|
|
||||||
187
tests/test_lifecycle_emails.py
Normal file
187
tests/test_lifecycle_emails.py
Normal file
|
|
@ -0,0 +1,187 @@
|
||||||
|
"""Lifecycle emails (cloud/lifecycle.py) and the commercial-email guard.
|
||||||
|
|
||||||
|
Until 28-sep-2026 a free sign-up got no email between the magic link and the
|
||||||
|
out-of-minutes upsell, and an abandoned Stripe Checkout (1,011 of 1,126
|
||||||
|
sessions) was never followed up.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cloud import emails, lifecycle, marketing, metering
|
||||||
|
|
||||||
|
|
||||||
|
def run(coro):
|
||||||
|
return asyncio.run(coro)
|
||||||
|
|
||||||
|
|
||||||
|
class TestAmountLabel:
|
||||||
|
def test_usd(self):
|
||||||
|
assert lifecycle.amount_label({"amount_total": 1200, "currency": "usd"}) == "$12.00"
|
||||||
|
|
||||||
|
def test_other_currency(self):
|
||||||
|
assert lifecycle.amount_label({"amount_total": 990, "currency": "eur"}) == "9.90 EUR"
|
||||||
|
|
||||||
|
def test_missing(self):
|
||||||
|
assert lifecycle.amount_label({}) == ""
|
||||||
|
assert lifecycle.amount_label({"amount_total": 0, "currency": "usd"}) == ""
|
||||||
|
|
||||||
|
|
||||||
|
class TestPromo:
|
||||||
|
def test_unset(self, monkeypatch):
|
||||||
|
monkeypatch.delenv("WINBACK_PROMO_CODE", raising=False)
|
||||||
|
monkeypatch.setenv("WINBACK_PROMO_LABEL", "50% off")
|
||||||
|
assert lifecycle.promo() == ("", "")
|
||||||
|
|
||||||
|
def test_set(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("WINBACK_PROMO_CODE", " CODE ")
|
||||||
|
monkeypatch.setenv("WINBACK_PROMO_LABEL", "50% off your first month")
|
||||||
|
assert lifecycle.promo() == ("CODE", "50% off your first month")
|
||||||
|
|
||||||
|
|
||||||
|
def _expired(url="https://checkout.stripe.com/r/x", user_id="u1", amount=1200):
|
||||||
|
return {"after_expiration": {"recovery": {"url": url} if url else None},
|
||||||
|
"client_reference_id": user_id, "amount_total": amount, "currency": "usd"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def recovery(monkeypatch):
|
||||||
|
monkeypatch.delenv("LIFECYCLE_EMAILS_DISABLED", raising=False)
|
||||||
|
state = {"claims": set(), "sent": [], "target": SimpleNamespace(id="u1", email="a@b.co")}
|
||||||
|
|
||||||
|
async def _target(user_id):
|
||||||
|
return state["target"]
|
||||||
|
|
||||||
|
async def _claim(user_id, kind):
|
||||||
|
if (user_id, kind) in state["claims"]:
|
||||||
|
return False
|
||||||
|
state["claims"].add((user_id, kind))
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def _send(user_id, email, url, amount_label=""):
|
||||||
|
state["sent"].append((email, url, amount_label))
|
||||||
|
return True
|
||||||
|
|
||||||
|
monkeypatch.setattr(lifecycle, "_recovery_target", _target)
|
||||||
|
monkeypatch.setattr(lifecycle, "claim", _claim)
|
||||||
|
monkeypatch.setattr(emails, "send_checkout_recovery_email", _send)
|
||||||
|
return state
|
||||||
|
|
||||||
|
|
||||||
|
class TestCheckoutRecovery:
|
||||||
|
def test_sends_the_recovery_url_once(self, recovery):
|
||||||
|
assert run(lifecycle.on_checkout_expired(_expired())) is True
|
||||||
|
assert recovery["sent"] == [("a@b.co", "https://checkout.stripe.com/r/x", "$12.00")]
|
||||||
|
# A second abandoned session does not mail again.
|
||||||
|
assert run(lifecycle.on_checkout_expired(_expired())) is False
|
||||||
|
assert len(recovery["sent"]) == 1
|
||||||
|
|
||||||
|
def test_no_recovery_url_no_email(self, recovery):
|
||||||
|
assert run(lifecycle.on_checkout_expired(_expired(url=None))) is False
|
||||||
|
assert recovery["sent"] == []
|
||||||
|
|
||||||
|
def test_no_user_no_email(self, recovery):
|
||||||
|
assert run(lifecycle.on_checkout_expired(_expired(user_id=None))) is False
|
||||||
|
recovery["target"] = None # gone, or already paying
|
||||||
|
assert run(lifecycle.on_checkout_expired(_expired())) is False
|
||||||
|
assert recovery["sent"] == []
|
||||||
|
|
||||||
|
def test_kill_switch(self, recovery, monkeypatch):
|
||||||
|
monkeypatch.setenv("LIFECYCLE_EMAILS_DISABLED", "1")
|
||||||
|
assert run(lifecycle.on_checkout_expired(_expired())) is False
|
||||||
|
assert recovery["sent"] == []
|
||||||
|
|
||||||
|
def test_webhook_dispatches_and_swallows_errors(self, monkeypatch):
|
||||||
|
billing = pytest.importorskip("cloud.billing") # needs the stripe SDK
|
||||||
|
seen = []
|
||||||
|
|
||||||
|
async def _boom(obj):
|
||||||
|
seen.append(obj)
|
||||||
|
raise RuntimeError("smtp down")
|
||||||
|
monkeypatch.setattr(lifecycle, "on_checkout_expired", _boom)
|
||||||
|
event = {"type": "checkout.session.expired", "created": 1790000000,
|
||||||
|
"data": {"object": {"id": "cs_1"}}}
|
||||||
|
run(billing.handle_event(event)) # must not raise: Stripe would retry
|
||||||
|
assert seen == [{"id": "cs_1"}]
|
||||||
|
|
||||||
|
|
||||||
|
class TestLoopSend:
|
||||||
|
@pytest.fixture()
|
||||||
|
def loop_state(self, monkeypatch):
|
||||||
|
state = {"claims": [], "sent": []}
|
||||||
|
|
||||||
|
async def _claim(user_id, kind):
|
||||||
|
state["claims"].append(kind)
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def _processed(user_id):
|
||||||
|
return state.get("processed", False)
|
||||||
|
|
||||||
|
def _mk(kind):
|
||||||
|
async def _send(user_id, email, *args):
|
||||||
|
state["sent"].append((kind, args))
|
||||||
|
return True
|
||||||
|
return _send
|
||||||
|
|
||||||
|
monkeypatch.setattr(lifecycle, "claim", _claim)
|
||||||
|
monkeypatch.setattr(metering, "has_processed_before", _processed)
|
||||||
|
monkeypatch.setattr(metering, "free_plan_eligible", lambda u: u.eligible)
|
||||||
|
monkeypatch.setattr(emails, "send_welcome_email", _mk("welcome"))
|
||||||
|
monkeypatch.setattr(emails, "send_first_clip_email", _mk("first_clip"))
|
||||||
|
monkeypatch.setattr(emails, "send_winback_email", _mk("winback"))
|
||||||
|
monkeypatch.setattr(lifecycle.config, "FIRST_VIDEO_MAX_MINUTES", 60)
|
||||||
|
return state
|
||||||
|
|
||||||
|
def test_welcome_promises_the_first_video(self, loop_state):
|
||||||
|
user = SimpleNamespace(id="u", email="e", eligible=True)
|
||||||
|
assert run(lifecycle._send("welcome", user)) is True
|
||||||
|
assert loop_state["sent"] == [("welcome", (60,))]
|
||||||
|
|
||||||
|
def test_no_free_promise_after_a_processed_video(self, loop_state):
|
||||||
|
loop_state["processed"] = True
|
||||||
|
user = SimpleNamespace(id="u", email="e", eligible=True)
|
||||||
|
run(lifecycle._send("welcome", user))
|
||||||
|
assert loop_state["sent"] == [("welcome", (0,))]
|
||||||
|
|
||||||
|
def test_ineligible_account_is_claimed_but_not_mailed(self, loop_state):
|
||||||
|
user = SimpleNamespace(id="u", email="e", eligible=False)
|
||||||
|
assert run(lifecycle._send("first_clip", user)) is False
|
||||||
|
assert loop_state["claims"] == ["first_clip"] # not picked up again
|
||||||
|
assert loop_state["sent"] == []
|
||||||
|
|
||||||
|
def test_winback_carries_the_promo_code(self, loop_state, monkeypatch):
|
||||||
|
monkeypatch.setenv("WINBACK_PROMO_CODE", "CODE")
|
||||||
|
monkeypatch.setenv("WINBACK_PROMO_LABEL", "50% off")
|
||||||
|
user = SimpleNamespace(id="u", email="e", eligible=False)
|
||||||
|
assert run(lifecycle._send("winback", user)) is True
|
||||||
|
assert loop_state["sent"] == [("winback", ("CODE", "50% off"))]
|
||||||
|
|
||||||
|
|
||||||
|
class TestCommercialEmail:
|
||||||
|
@pytest.fixture()
|
||||||
|
def outbox(self, monkeypatch):
|
||||||
|
sent = []
|
||||||
|
|
||||||
|
async def _send(to, subject, html, headers=None):
|
||||||
|
sent.append((to, subject, html, headers))
|
||||||
|
monkeypatch.setattr(emails, "send_email", _send)
|
||||||
|
monkeypatch.setattr(marketing, "unsubscribe_url", lambda uid: f"https://api/unsub?u={uid}")
|
||||||
|
return sent
|
||||||
|
|
||||||
|
def test_opted_out_account_gets_nothing(self, outbox, monkeypatch):
|
||||||
|
async def _out(uid):
|
||||||
|
return True
|
||||||
|
monkeypatch.setattr(marketing, "is_opted_out", _out)
|
||||||
|
assert run(emails.send_commercial_email("u1", "a@b.co", "s", "<p>x</p>")) is False
|
||||||
|
assert outbox == []
|
||||||
|
|
||||||
|
def test_footer_and_list_unsubscribe(self, outbox, monkeypatch):
|
||||||
|
async def _in(uid):
|
||||||
|
return False
|
||||||
|
monkeypatch.setattr(marketing, "is_opted_out", _in)
|
||||||
|
assert run(emails.send_commercial_email("u1", "a@b.co", "s", "<p>x</p>")) is True
|
||||||
|
(to, _, html, headers), = outbox
|
||||||
|
assert "https://api/unsub?u=u1" in html
|
||||||
|
assert headers["List-Unsubscribe"] == "<https://api/unsub?u=u1>"
|
||||||
|
assert headers["List-Unsubscribe-Post"] == "List-Unsubscribe=One-Click"
|
||||||
|
|
@ -66,6 +66,42 @@ class TestPlanPartialMinutes:
|
||||||
assert app_module.plan_partial_minutes(45, 20.0, "lots") == (45, None)
|
assert app_module.plan_partial_minutes(45, 20.0, "lots") == (45, None)
|
||||||
|
|
||||||
|
|
||||||
|
class TestFreeOverflow:
|
||||||
|
"""A free source past the balance never meets the wall: the first video
|
||||||
|
(<= FIRST_VIDEO_MAX_MINUTES) is clipped whole for the balance, any other
|
||||||
|
is clipped to the first N minutes."""
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _cap(self, monkeypatch):
|
||||||
|
monkeypatch.setattr(config, "FIRST_VIDEO_MAX_MINUTES", 60)
|
||||||
|
|
||||||
|
def test_first_video_up_to_the_cap_is_granted_whole(self):
|
||||||
|
assert app_module.free_overflow("free", 50, 20.0, None, False) == (20, None)
|
||||||
|
assert app_module.free_overflow("free", 60, 20.0, None, False) == (20, None)
|
||||||
|
# The grant charges the floored balance, which lands at zero.
|
||||||
|
assert app_module.free_overflow("free", 45, 17.6, None, False) == (17, None)
|
||||||
|
|
||||||
|
def test_first_video_past_the_cap_is_clipped_to_the_balance(self):
|
||||||
|
assert app_module.free_overflow("free", 61, 20.0, None, False) == (None, 20.0)
|
||||||
|
|
||||||
|
def test_later_videos_are_clipped_to_the_balance(self):
|
||||||
|
grant, max_minutes = app_module.free_overflow("free", 50, 20.0, None, True)
|
||||||
|
assert grant is None and max_minutes == 20.0
|
||||||
|
# ...which plan_partial_minutes turns into the usual first-N cut.
|
||||||
|
assert app_module.plan_partial_minutes(50, 20.0, max_minutes) == (
|
||||||
|
20, {"processed_minutes": 20, "total_minutes": 50})
|
||||||
|
|
||||||
|
def test_untouched_cases(self):
|
||||||
|
# Fits the balance, a paid plan, or the client already named a cut.
|
||||||
|
assert app_module.free_overflow("free", 15, 20.0, None, False) == (None, None)
|
||||||
|
assert app_module.free_overflow("starter", 50, 20.0, None, False) == (None, None)
|
||||||
|
assert app_module.free_overflow("free", 50, 20.0, 10, False) == (None, 10)
|
||||||
|
|
||||||
|
def test_grant_can_be_disabled(self, monkeypatch):
|
||||||
|
monkeypatch.setattr(config, "FIRST_VIDEO_MAX_MINUTES", 0)
|
||||||
|
assert app_module.free_overflow("free", 50, 20.0, None, False) == (None, 20.0)
|
||||||
|
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
# Endpoint: max_minutes reaches the reservation, the cut reaches the job
|
# Endpoint: max_minutes reaches the reservation, the cut reaches the job
|
||||||
# --------------------------------------------------------------------------- #
|
# --------------------------------------------------------------------------- #
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue