From 725aebf1a35a3eb453deab1763304e97e9c985c4 Mon Sep 17 00:00:00 2001
From: victorcavero14
Date: Mon, 28 Sep 2026 13:05:43 +0200
Subject: [PATCH] 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).
---
.env.example | 9 ++
CLAUDE.md | 32 +++++
app.py | 51 ++++++-
cloud/__init__.py | 5 +-
cloud/account.py | 3 +-
cloud/billing.py | 11 ++
cloud/config.py | 10 ++
cloud/emails.py | 135 +++++++++++++++++-
cloud/lifecycle.py | 232 +++++++++++++++++++++++++++++++
cloud/marketing.py | 15 +-
cloud/metering.py | 17 +++
cloud/models.py | 30 +++-
dashboard/src/App.jsx | 23 ++-
dashboard/src/lib/analytics.js | 4 +
tests/test_lifecycle_emails.py | 187 +++++++++++++++++++++++++
tests/test_partial_processing.py | 36 +++++
16 files changed, 773 insertions(+), 27 deletions(-)
create mode 100644 cloud/lifecycle.py
create mode 100644 tests/test_lifecycle_emails.py
diff --git a/.env.example b/.env.example
index 944af09..e285759 100644
--- a/.env.example
+++ b/.env.example
@@ -122,3 +122,12 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
# BACKUP_DEST=s3://openshorts-backups/pg
# BACKUP_S3_ENDPOINT=https://.r2.cloudflarestorage.com
# 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
diff --git a/CLAUDE.md b/CLAUDE.md
index 347cf12..9f46b2b 100644
--- a/CLAUDE.md
+++ b/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
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`)
The count is not a setting, it is derived, and every stage of the derivation
diff --git a/app.py b/app.py
index e60da86..1a70ea9 100644
--- a/app.py
+++ b/app.py
@@ -264,7 +264,7 @@ def _maybe_send_quota_email(user):
_last_quota_email[str(user.id)] = now
from cloud.emails import send_out_of_minutes_email
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):
@@ -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}
+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):
"""Meter a managed /api/process request.
@@ -404,15 +428,29 @@ async def reserve_process_minutes(request, url, input_path, job_id, max_minutes=
pass
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
# refused: the wall offers "the first N minutes" (``partial_minutes`` in
# the 402 below) and the client resubmits with ``max_minutes``.
- reserve, partial = plan_partial_minutes(minutes, balance["remaining"], max_minutes)
+ if grant is not None:
+ reserve, partial = grant, None
+ else:
+ reserve, partial = plan_partial_minutes(minutes, balance["remaining"], max_minutes)
try:
reservation_id = await _metering.reserve_minutes(user.id, reserve, job_id)
# Read by process_endpoint for the download's safety cut
- # (SOURCE_CAP_MINUTES); kept off the return tuple on purpose.
- request.state.reserved_minutes = reserve
+ # (SOURCE_CAP_MINUTES); kept off the return tuple on purpose. A granted
+ # 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:
_maybe_send_quota_email(user)
raise HTTPException(status_code=402, detail={
@@ -2126,6 +2164,8 @@ async def lifespan(app: FastAPI):
# Autopilot: watch connected YouTube channels for new videos. Paused
# while this instance drains so only the new container submits jobs.
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 —
# a single job-failure alert is easy to miss and ingest stays broken
# until someone tops the balance up.
@@ -3119,7 +3159,8 @@ async def process_endpoint(
_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):
"""What the disk says about a job this instance does not hold in memory.
diff --git a/cloud/__init__.py b/cloud/__init__.py
index 842a0e4..221106c 100644
--- a/cloud/__init__.py
+++ b/cloud/__init__.py
@@ -27,7 +27,7 @@ def setup_sync(app):
app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret)
from . import (auth, oauth, billing, social_profiles, videos, api_keys,
- account, mcp_oauth, marketing, autopilot)
+ account, mcp_oauth, marketing, autopilot, lifecycle) # noqa: F401
oauth.register()
billing._init_stripe()
app.include_router(auth.router)
@@ -40,7 +40,8 @@ def setup_sync(app):
app.include_router(account.router)
# Autopilot: clip new videos from the user's connected YouTube channel.
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)
diff --git a/cloud/account.py b/cloud/account.py
index 8b17da5..1727677 100644
--- a/cloud/account.py
+++ b/cloud/account.py
@@ -42,6 +42,7 @@ from .models import (
User, Subscription, CreditTopup, UsageLedger, MagicLinkToken,
SignupAttribution, ApiKey, UploadPostProfile, UserVideo, ClipExpiryWarning,
Project, AccountDeletion, OAuthCode, AutopilotRun, AutopilotSettings,
+ LifecycleEmail,
)
# Every table that holds rows belonging to a user, child-first (clip_expiry_
@@ -56,7 +57,7 @@ from .models import (
USER_OWNED_TABLES = (
ClipExpiryWarning, UserVideo, Project, UsageLedger, CreditTopup,
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
diff --git a/cloud/billing.py b/cloud/billing.py
index 1af2d07..3ccf44d 100644
--- a/cloud/billing.py
+++ b/cloud/billing.py
@@ -197,6 +197,11 @@ async def create_checkout(body: CheckoutRequest, request: Request):
# that already converts at ~1%.
tax_id_collection={"enabled": True},
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={
"user_id": str(user.id),
"kind": entry["kind"],
@@ -398,6 +403,12 @@ async def handle_event(event: dict):
await _track_invoice_revenue(obj)
elif etype == "charge.refunded":
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):
diff --git a/cloud/config.py b/cloud/config.py
index 5c66b85..e49b9b5 100644
--- a/cloud/config.py
+++ b/cloud/config.py
@@ -89,6 +89,16 @@ def new_subscriber_label(status: str):
# clips, so the wall stays as it was.
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
# 'trialing' subscriptions; removable once no subscription has status
# 'trialing'.
diff --git a/cloud/emails.py b/cloud/emails.py
index b2fa9fe..bae04cc 100644
--- a/cloud/emails.py
+++ b/cloud/emails.py
@@ -11,11 +11,13 @@ from email.message import EmailMessage
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["From"] = settings.email_from
msg["To"] = to
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.add_alternative(html, subtype="html")
@@ -31,17 +33,41 @@ def _send_sync(to: str, subject: str, html: str):
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."""
if not settings.smtp_configured:
print(f"✉️ [DEV email → {to}] {subject}")
return
try:
- await asyncio.to_thread(_send_sync, to, subject, html)
+ await asyncio.to_thread(_send_sync, to, subject, html, headers)
except Exception as 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'Unsubscribe 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}
{footer}
')
+ await send_email(to, subject, html, headers)
+ return True
+
+
async def send_magic_link_email(email: str, link: str):
if not settings.smtp_configured:
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)
-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.
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.
"""
- print(f"✉️ Out-of-minutes upsell email → {email}")
- await send_email(email, "Your video is waiting — you're out of free minutes", html)
+ 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}")
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}")
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'
Your first video is on us: anything up to "
+ f"{first_video_minutes} minutes is clipped whole, free.
")
+ return "
You get 20 free minutes every month.
"
+
+
+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"""
+
+
Welcome to OpenShorts 👋
+
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.
+ {_first_video_line(first_video_minutes)}
+ {_cta(app_url, "Clip my first video")}
+
Works best with people talking:
+ podcasts, interviews, streams, tutorials.
+
+ """
+ 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"""
+
+
Your clips are one link away
+
You signed up yesterday but haven't clipped anything yet. It takes
+ one step: paste the link of a video you already published.
+ {_first_video_line(first_video_minutes)}
+ {_cta(app_url, "Paste a link")}
+
Stuck on something? Just reply to
+ this email.
+
+ """
+ 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"
Here's {promo_label or 'a discount'}: use code "
+ f"{promo_code} "
+ f"at checkout.
")
+ subject = f"{promo_label or 'A discount'} on OpenShorts, for you"
+ else:
+ offer = ""
+ subject = "Keep your clips, lose the watermark"
+ html = f"""
+
+
Liked your clips?
+
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.
+ {offer}
+ {_cta(pricing, "See plans")}
+
Cancel anytime.
+
+ """
+ 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"""
+
+
You didn't finish checking out
+
You started upgrading to {what} but the payment wasn't completed.
+ Your cart is saved: one click takes you back to it.
+ {_cta(recovery_url, "Finish checkout")}
+
Card declined? PayPal and other
+ methods are on the same page. Reply to this email if something
+ didn't work.
+
+ """
+ return await send_commercial_email(user_id, email, "Your OpenShorts checkout is saved", html)
diff --git a/cloud/lifecycle.py b/cloud/lifecycle.py
new file mode 100644
index 0000000..5256888
--- /dev/null
+++ b/cloud/lifecycle.py
@@ -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())
diff --git a/cloud/marketing.py b/cloud/marketing.py
index f74822b..8c023d1 100644
--- a/cloud/marketing.py
+++ b/cloud/marketing.py
@@ -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
-deleted". ``send_out_of_minutes_email`` is not — it leads with a price and a
-Buy button, which makes it a comunicación comercial under LSSI art. 21. Art.
-21.2 permits it to an existing customer for a similar product, but only if
-*every single message* offers a simple, free way to refuse — and until now it
-offered none: no footer link and no ``List-Unsubscribe`` header.
+deleted". ``send_out_of_minutes_email`` and the lifecycle emails
+(cloud/lifecycle.py) are not — they sell a plan, which makes them a
+comunicación comercial under LSSI art. 21. Art. 21.2 permits them to an
+existing customer for a similar product, but only if *every single message*
+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 app) and must never expire, so it carries an HMAC of the user id keyed on
diff --git a/cloud/metering.py b/cloud/metering.py
index 6374718..c543335 100644
--- a/cloud/metering.py
+++ b/cloud/metering.py
@@ -439,6 +439,23 @@ async def _plan_used_this_period(session, user_id, period_end) -> Decimal:
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):
return list((await session.execute(
select(CreditTopup).where(CreditTopup.user_id == user_id)
diff --git a/cloud/models.py b/cloud/models.py
index 0256387..e91f16d 100644
--- a/cloud/models.py
+++ b/cloud/models.py
@@ -25,11 +25,12 @@ class User(Base):
stripe_customer_id = Column(Text, unique=True, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
last_login_at = Column(DateTime(timezone=True), nullable=True)
- # Set by the unsubscribe link in the only email we send that is a
- # commercial communication rather than a service notice (the out-of-minutes
- # upsell). LSSI art. 21.2 lets us mail our own customers about a similar
- # product, but only if every message carries a way out — so this column is
- # what that link writes, and cloud/emails.py refuses to send when it is set.
+ # Set by the unsubscribe link in the emails that are commercial
+ # communications rather than service notices (the out-of-minutes upsell and
+ # the lifecycle emails). LSSI art. 21.2 lets us mail our own customers about
+ # a similar product, but only if every message carries a way out — so this
+ # 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
# cloud/database.init_engine for the additive statement that adds it to an
# existing database.
@@ -390,3 +391,22 @@ class AutopilotRun(Base):
__table_args__ = (
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"),
+ )
diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx
index f6d2feb..f207516 100644
--- a/dashboard/src/App.jsx
+++ b/dashboard/src/App.jsx
@@ -276,6 +276,8 @@ function App() {
// {processed_minutes, total_minutes} when the running/finished job clips
// only the first part of the source (the quota wall's free offer).
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.
const [queueInfo, setQueueInfo] = useState(null);
// Why the last job could not start or failed, in plain words (or '').
@@ -968,6 +970,7 @@ function App() {
setProjectState(null);
setNoSource(false);
setPartialJob(null);
+ setFirstVideoJob(false);
try {
let body;
@@ -1037,6 +1040,13 @@ function App() {
setJobId(resData.job_id);
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') {
setProcessingMedia({ type: 'server', payload: `/api/source/${resData.job_id}` });
}
@@ -1112,6 +1122,7 @@ function App() {
setProjectState(null);
setNoSource(false);
setPartialJob(null);
+ setFirstVideoJob(false);
setQueueInfo(null);
setJobError('');
localStorage.removeItem(SESSION_KEY);
@@ -2111,7 +2122,17 @@ function App() {
)}
{/* Peak-moment upsell: they just SAW their clips — sell while
they're proud of the result, before asking for stars. */}
- {plan === 'free' && !partialJob && (
+ {firstVideoJob && !partialJob && (
+
+ )}
+ {plan === 'free' && !partialJob && !firstVideoJob && (