Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
199 lines
7.1 KiB
Python
199 lines
7.1 KiB
Python
"""Weekly Growth Digest email — the mailed half of ``/insights/digest``.
|
|
|
|
A beat tick (``app/services/loops/growth_digest_tasks.py``) calls
|
|
:func:`run_weekly` once a week. For every account with a live personal plan
|
|
(the same gate as the dashboard page, ``digest.has_growth_digest_access``)
|
|
it composes the real digest from that account's own logged hook/template
|
|
performance and sends it, once per ISO week:
|
|
|
|
* **Real data only.** Every number comes from
|
|
:func:`app.services.hook_performance.winning_hooks` /
|
|
:func:`app.services.hook_performance.winning_templates` /
|
|
:func:`app.services.insights.user_insights` — the same strictly per-user
|
|
aggregates the dashboard page reads. No fabricated or placeholder figures.
|
|
* **Skip, not fabricate, when there is nothing logged yet.** An account with
|
|
no logged reel performance gets no email this week rather than an email
|
|
built on empty data.
|
|
* **Once per ISO week.** An append-only audit row
|
|
(``growth_digest_mail.sent``, target ``growth_digest:<ISO week>``) makes a
|
|
replayed tick a no-op; a second tick in the same week sends nothing more.
|
|
* **Unsubscribe respected.** The same one-click opt-out as the other
|
|
lifecycle mail (``app.services.billing.lifecycle_mail``); an opted-out or
|
|
internal (smoke test / Megaphone) account gets nothing.
|
|
* **Draft only, same as the web feature.** The email only links back to the
|
|
dashboard; it never sends anything to a creator, posts anything, or spends
|
|
money on its own.
|
|
|
|
Send path and template reuse the existing branded mailer
|
|
(``app.services.billing.lifecycle_mail._send`` -> Rally Send, then SMTP).
|
|
Nothing here raises into the beat tick.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timezone
|
|
from typing import Any
|
|
|
|
from loguru import logger
|
|
|
|
ACTION_SENT = "growth_digest_mail.sent"
|
|
TARGET_PREFIX = "growth_digest:"
|
|
DIGEST_PATH = "/insights/digest"
|
|
#: How many logged hooks/templates to pull before splitting into winning/dying.
|
|
_HOOKS_PULLED = 25
|
|
|
|
|
|
def _iso_week(moment: datetime) -> str:
|
|
year, week, _ = moment.isocalendar()
|
|
return f"{year}-W{week:02d}"
|
|
|
|
|
|
def _already_sent(session: Any, user_id: str, week: str) -> bool:
|
|
from sqlalchemy import select
|
|
|
|
from app.models.db.models import AuditLog
|
|
|
|
return (
|
|
session.execute(
|
|
select(AuditLog.id)
|
|
.where(
|
|
AuditLog.actor_user_id == str(user_id),
|
|
AuditLog.action == ACTION_SENT,
|
|
AuditLog.target_type == f"{TARGET_PREFIX}{week}",
|
|
)
|
|
.limit(1)
|
|
).first()
|
|
is not None
|
|
)
|
|
|
|
|
|
def _record_sent(session: Any, user_id: str, week: str) -> None:
|
|
from app.services import audit
|
|
|
|
audit.record(
|
|
session,
|
|
actor_user_id=str(user_id),
|
|
action=ACTION_SENT,
|
|
target_type=f"{TARGET_PREFIX}{week}",
|
|
target_id=str(user_id),
|
|
)
|
|
|
|
|
|
def _address(session: Any, user_id: str) -> str:
|
|
from app.models.db.models import User
|
|
from app.services.funnel.internal import is_internal_email
|
|
|
|
user = session.get(User, user_id)
|
|
email = str(getattr(user, "email", "") or "").strip()
|
|
return email if "@" in email and not is_internal_email(email) else ""
|
|
|
|
|
|
def _eligible_user_ids(session: Any) -> list[str]:
|
|
"""Accounts with a live personal plan (same gate as the dashboard page)."""
|
|
from sqlalchemy import select
|
|
|
|
from app.models.db.creator_subscription import CreatorSubscription
|
|
from app.services.billing.creator_subscriptions import LIVE_STATUSES
|
|
|
|
rows = (
|
|
session.execute(
|
|
select(CreatorSubscription.user_id).where(
|
|
CreatorSubscription.status.in_(LIVE_STATUSES)
|
|
)
|
|
)
|
|
.scalars()
|
|
.all()
|
|
)
|
|
return [str(r) for r in rows]
|
|
|
|
|
|
def send_weekly_digest(user_id: str, now: datetime | None = None) -> bool:
|
|
"""Compose and send one account's weekly growth digest. Returns whether an
|
|
email was actually sent (``False`` on: nothing logged, opted out, already
|
|
sent this week, or mail unavailable). Never raises.
|
|
"""
|
|
moment = now or datetime.now(timezone.utc)
|
|
week = _iso_week(moment)
|
|
try:
|
|
from app.models.db.base import get_session
|
|
from app.services import hook_performance
|
|
from app.services import insights as insights_service
|
|
from app.services.billing import lifecycle_mail
|
|
from app.services.email_templates import growth_digest_email
|
|
from app.services.growth_digest import digest
|
|
|
|
with get_session() as session:
|
|
if _already_sent(session, user_id, week):
|
|
return False
|
|
to = _address(session, user_id)
|
|
if not to:
|
|
return False
|
|
if lifecycle_mail.opted_out(session, user_id):
|
|
return False
|
|
|
|
hooks = hook_performance.winning_hooks(
|
|
session, user_id, limit=_HOOKS_PULLED
|
|
)
|
|
if not hooks:
|
|
return False # nothing logged yet; no digest worth sending
|
|
templates = hook_performance.winning_templates(
|
|
session, user_id, limit=digest.ROTATION_LIMIT
|
|
)
|
|
rotation = digest.hook_rotation(hooks)
|
|
brief = digest.draft_creator_brief(hooks, templates)
|
|
snapshot = digest.daily_digest_line(
|
|
insights_service.user_insights(session, user_id)
|
|
)
|
|
|
|
unsub = lifecycle_mail.unsubscribe_url(user_id)
|
|
rendered = growth_digest_email(
|
|
snapshot=snapshot,
|
|
winning=rotation["winning"],
|
|
dying=rotation["dying"],
|
|
brief=brief,
|
|
url=f"{lifecycle_mail.web_base_url()}{DIGEST_PATH}",
|
|
unsubscribe_url=unsub,
|
|
)
|
|
if not lifecycle_mail._send(to, rendered):
|
|
return False
|
|
_record_sent(session, user_id, week)
|
|
return True
|
|
except Exception as exc: # noqa: BLE001 - a beat tick must never crash the worker
|
|
logger.warning(
|
|
f"growth digest mail for {user_id} failed: {type(exc).__name__}: {exc}"
|
|
)
|
|
return False
|
|
|
|
|
|
def run_weekly(now: datetime | None = None) -> dict[str, int]:
|
|
"""One weekly tick over every account with a live personal plan."""
|
|
import os
|
|
|
|
if (os.environ.get("MENIVOR_GROWTH_DIGEST_MAIL") or "1").strip().lower() in {
|
|
"0",
|
|
"false",
|
|
"off",
|
|
"no",
|
|
}:
|
|
return {}
|
|
counts = {"sent": 0, "skipped": 0}
|
|
try:
|
|
from app.models.db.base import get_session
|
|
|
|
with get_session() as session:
|
|
user_ids = _eligible_user_ids(session)
|
|
except Exception as exc: # noqa: BLE001 - a beat tick must never crash the worker
|
|
logger.error(f"growth digest weekly scan failed: {exc}")
|
|
return counts
|
|
for user_id in user_ids:
|
|
try:
|
|
sent = send_weekly_digest(user_id, now)
|
|
except Exception as exc: # noqa: BLE001 - one account never stops the rest
|
|
logger.error(f"growth digest for {user_id} failed: {exc}")
|
|
sent = False
|
|
counts["sent" if sent else "skipped"] += 1
|
|
return counts
|
|
|
|
|
|
__all__ = ["ACTION_SENT", "run_weekly", "send_weekly_digest"]
|