feat(alerts): avisar del dinero de Stripe (con importe) y de activación de clips
Stripe — dos huecos que faltaban:
- invoice.paid no disparaba nada: las renovaciones mensuales entraban en
silencio. Ahora 💵 'Payment received: $X' en cada cobro real (primera compra
Y renovación), con el importe y el motivo (new subscription / renewal).
- El aviso de top-up ahora incluye el importe cobrado.
- Helper _money() para formatear cents+currency ('$59.00 USD').
Clips (opción 1, alta señal para no ahogar el canal cuando crezca el free):
- _notify_clip_activity avisa por Telegram SOLO en el primer clip de un
usuario (activación) o en clips de usuarios de pago. Nada de un ping por
cada clip free. Incluye email, plan, título y nº de clips.
Verificado enviando los formatos reales al Telegram del admin.
This commit is contained in:
parent
26135fb485
commit
2efbeb2828
2 changed files with 87 additions and 1 deletions
46
app.py
46
app.py
|
|
@ -721,6 +721,8 @@ async def run_job_wrapper(job_id):
|
|||
await _track_proxy_usage(job_id)
|
||||
# Tell the owner their clips are ready (managed jobs, once per job).
|
||||
await _notify_clips_ready(job_id)
|
||||
# Telegram pulse for high-signal activity (first clip / paid user).
|
||||
await _notify_clip_activity(job_id)
|
||||
# Always release semaphore and mark queue task done
|
||||
concurrency_semaphore.release()
|
||||
job_queue.task_done()
|
||||
|
|
@ -790,6 +792,50 @@ async def _notify_clips_ready(job_id):
|
|||
print(f"⚠️ Clips-ready email error for {job_id}: {e}")
|
||||
|
||||
|
||||
async def _notify_clip_activity(job_id):
|
||||
"""High-signal Telegram pulse when clips are created — NOT every clip (that
|
||||
would drown the ops channel as free usage grows). Only:
|
||||
* a user's very first clips (activation), and
|
||||
* any paid user's clips.
|
||||
Telegram-only (best effort, no email)."""
|
||||
if not BILLING_ENABLED:
|
||||
return
|
||||
job = jobs.get(job_id) or {}
|
||||
if not job.get('user_id') or job.get('status') != 'completed':
|
||||
return
|
||||
clips = (job.get('result') or {}).get('clips') or []
|
||||
if not clips:
|
||||
return
|
||||
try:
|
||||
from sqlalchemy import select, func, and_
|
||||
from cloud.database import session as cloud_session
|
||||
from cloud.models import User, UserVideo
|
||||
from cloud import metering
|
||||
async with cloud_session() as s:
|
||||
user = await s.get(User, job['user_id'])
|
||||
if not user:
|
||||
return
|
||||
sub = await metering._active_subscription(s, user.id)
|
||||
# Clips from OTHER jobs (this job's are already archived by now).
|
||||
prior = (await s.execute(
|
||||
select(func.count(UserVideo.id)).where(and_(
|
||||
UserVideo.user_id == user.id, UserVideo.job_id != job_id,
|
||||
))
|
||||
)).scalar_one()
|
||||
plan = sub.plan if sub else "free"
|
||||
is_paid = sub is not None
|
||||
first_clip = prior == 0
|
||||
if not (first_clip or is_paid):
|
||||
return
|
||||
title = clips[0].get('video_title_for_youtube_short') or clips[0].get('title') or "video"
|
||||
n = len(clips)
|
||||
tag = "🎬 First clips!" if first_clip else "🎬 Clips created"
|
||||
await _alerts.send_telegram(
|
||||
f"{tag}\n{user.email} ({plan}) — “{title}” ({n} clip{'s' if n != 1 else ''})")
|
||||
except Exception as e:
|
||||
print(f"⚠️ Clip-activity notify error for {job_id}: {e}")
|
||||
|
||||
|
||||
async def _record_job_alert(job_id):
|
||||
if not BILLING_ENABLED:
|
||||
return
|
||||
|
|
|
|||
|
|
@ -33,6 +33,12 @@ def _ts(unix) -> datetime:
|
|||
return datetime.fromtimestamp(unix, tz=timezone.utc)
|
||||
|
||||
|
||||
def _money(cents, currency="usd") -> str:
|
||||
"""'$59.00' from Stripe's integer-cents + currency."""
|
||||
sym = {"usd": "$", "eur": "€", "gbp": "£"}.get((currency or "usd").lower(), "")
|
||||
return f"{sym}{(cents or 0) / 100:,.2f} {(currency or 'usd').upper()}"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Catalog (resolved once by lookup_key)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
|
@ -241,6 +247,7 @@ async def handle_event(event: dict):
|
|||
await _set_subscription_status_by_invoice(obj, "past_due", created)
|
||||
elif etype == "invoice.paid":
|
||||
await _set_subscription_status_by_invoice(obj, "active", created)
|
||||
await _notify_invoice_paid(obj)
|
||||
|
||||
|
||||
async def _user_id_for_customer(session, customer_id):
|
||||
|
|
@ -276,9 +283,13 @@ async def _apply_topup(session_obj: dict):
|
|||
select(User.email).where(User.id == user_id)
|
||||
)).scalar_one_or_none()
|
||||
|
||||
amount_txt = ""
|
||||
total = session_obj.get("amount_total")
|
||||
if total:
|
||||
amount_txt = f" ({_money(total, session_obj.get('currency'))})"
|
||||
from .alerts import send_admin_alert
|
||||
await send_admin_alert(
|
||||
"💰 Top-up purchased",
|
||||
f"💰 Top-up purchased{amount_txt}",
|
||||
f"{buyer_email or 'A user'} bought +{minutes} minutes.",
|
||||
)
|
||||
|
||||
|
|
@ -422,3 +433,32 @@ async def _set_subscription_status_by_invoice(invoice_obj: dict, status: str, ev
|
|||
if not sub_id:
|
||||
return
|
||||
await _set_subscription_status({"id": sub_id}, status, event_created)
|
||||
|
||||
|
||||
async def _notify_invoice_paid(invoice_obj: dict):
|
||||
"""Real money-in alert: every paid invoice — first charge AND every monthly
|
||||
renewal (renewals were previously silent). Includes the amount."""
|
||||
amount = invoice_obj.get("amount_paid", 0)
|
||||
if amount <= 0: # $0 invoices (e.g. legacy trial start)
|
||||
return
|
||||
money = _money(amount, invoice_obj.get("currency"))
|
||||
reason = invoice_obj.get("billing_reason") or ""
|
||||
kind = {
|
||||
"subscription_create": "new subscription",
|
||||
"subscription_cycle": "renewal",
|
||||
"subscription_update": "plan change",
|
||||
}.get(reason, reason or "payment")
|
||||
|
||||
email = None
|
||||
async with database.session() as s:
|
||||
cust = invoice_obj.get("customer")
|
||||
if cust:
|
||||
email = (await s.execute(
|
||||
select(User.email).where(User.stripe_customer_id == cust)
|
||||
)).scalar_one_or_none()
|
||||
|
||||
from .alerts import send_admin_alert
|
||||
await send_admin_alert(
|
||||
f"💵 Payment received: {money}",
|
||||
f"{email or 'A customer'} — {kind}.",
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in a new issue