From 3e6d5c3beeb61b905e0e115dca9289e3b5682e0c Mon Sep 17 00:00:00 2001 From: "victormanuel.caverogracia" <> Date: Thu, 3 Sep 2026 14:15:23 +0200 Subject: [PATCH] feat(billing): mirror paid invoices, top-ups and refunds into OpenPanel as revenue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The browser's `Subscribed` event is an intent signal: it misses renewals, is eaten by ad-blockers and never sees a refund. The Stripe webhook is the only place money is known for certain, so every invoice.paid (new / renewal / upgrade), one-off top-up and charge.refunded (negative) is now mirrored as OpenPanel's native `revenue` event, keyed by the user uuid the browser and the job events already use. Each event carries the acquisition channel read back from signup_attribution (utm_source > referrer host > direct) plus plan, interval, billing_reason and the Stripe id — so revenue is sliceable by where the buyer came from. Fire-and-forget: never touches the webhook path. The dashboard now `identify`s the signed-in user on every boot (OpenPanel keeps the profile in memory only) and clears it on sign-out, so pageviews and the server-side events share one profile. Also fixes GET /api/billing/invoices, which called the non-existent `database.SessionLocal` and 500'd for every user with a Stripe customer. Claude-Session: https://claude.ai/code/session_01GPZmS33ubmHxHEc84X7sQy --- cloud/analytics.py | 46 ++++++++++ cloud/billing.py | 112 ++++++++++++++++++++++++- dashboard/src/contexts/AuthContext.jsx | 5 +- dashboard/src/lib/analytics.js | 29 +++++++ tests/test_openpanel_revenue.py | 76 +++++++++++++++++ 5 files changed, 264 insertions(+), 4 deletions(-) create mode 100644 tests/test_openpanel_revenue.py diff --git a/cloud/analytics.py b/cloud/analytics.py index 3a77d23..66fcd38 100644 --- a/cloud/analytics.py +++ b/cloud/analytics.py @@ -75,3 +75,49 @@ def track(name: str, user_id=None, **props): asyncio.get_running_loop().create_task(_post(payload)) except RuntimeError: pass # no loop (CLI/self-host path) — nothing to report to anyway + + +def track_revenue(user_id, amount_cents, currency="usd", **props): + """Queue a ``revenue`` event in OpenPanel's native shape. Never raises. + + ``amount_cents`` is Stripe's integer minor-unit amount, negative for a + refund. OpenPanel stores ``__revenue`` in minor units and divides by 100 in + its own views (Overview card, revenue trend), so a $59 sale is sent as 5900; + ``amount`` (major units) rides along because custom reports read raw + properties without that formatting. Same contract as every other product + on this OpenPanel instance, so revenue is comparable across them. + """ + try: + cents = int(amount_cents or 0) + except (TypeError, ValueError): + return + if cents == 0: + return + props["__revenue"] = cents + props["amount"] = round(cents / 100, 2) + props["currency"] = (currency or "usd").upper() + track("revenue", user_id=user_id, **props) + + +def acquisition_properties(attribution): + """Flatten a ``SignupAttribution`` row (or any object with the same + attributes, or None) into the props a revenue event carries. + + A Stripe webhook has no browser session, so the only way to know where a + paying user came from is the first-touch snapshot recorded at sign-up. + ``channel`` collapses it to one label: utm_source > referring host > direct. + """ + if attribution is None: + return {"channel": "direct"} + get = lambda k: (getattr(attribution, k, None) or "").strip() or None # noqa: E731 + created = getattr(attribution, "created_at", None) + props = { + "channel": get("utm_source") or get("referrer_host") or "direct", + "utm_source": get("utm_source"), + "utm_medium": get("utm_medium"), + "utm_campaign": get("utm_campaign"), + "referrer": get("referrer_host"), + "landing_path": get("landing_path"), + "signup_date": created.isoformat() if hasattr(created, "isoformat") else None, + } + return {k: v for k, v in props.items() if v} diff --git a/cloud/billing.py b/cloud/billing.py index 4d6ec10..46fed76 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -17,8 +17,8 @@ from pydantic import BaseModel from sqlalchemy import select from .config import settings, PLAN_MINUTES, TRIAL_DAYS, SUBSCRIPTION_LOOKUP_KEYS, TOPUP_LOOKUP_KEYS -from . import config, database -from .models import User, Subscription, CreditTopup, StripeEvent +from . import analytics, config, database +from .models import User, Subscription, CreditTopup, StripeEvent, SignupAttribution from .auth import get_current_user_required router = APIRouter() @@ -311,7 +311,7 @@ async def list_invoices(request: Request): user = await get_current_user_required(request) if not settings.agentledger_api_key: raise HTTPException(status_code=503, detail="Billing backend not configured") - async with database.SessionLocal() as session: + async with database.session() as session: u = await session.get(User, user.id) customer_id = u.stripe_customer_id if u else None if not customer_id: @@ -380,6 +380,9 @@ async def handle_event(event: dict): elif etype == "invoice.paid": await _set_subscription_status_by_invoice(obj, "active", created) await _notify_invoice_paid(obj) + await _track_invoice_revenue(obj) + elif etype == "charge.refunded": + await _track_refund(obj) async def _user_id_for_customer(session, customer_id): @@ -395,6 +398,7 @@ async def _apply_topup(session_obj: dict): if minutes <= 0: return buyer_email = None + acquisition = {} async with database.session() as s: async with s.begin(): existing = (await s.execute( @@ -427,6 +431,7 @@ async def _apply_topup(session_obj: dict): buyer_email = (await s.execute( select(User.email).where(User.id == user_id) )).scalar_one_or_none() + acquisition = await _acquisition_properties(s, user_id) amount_txt = "" total = session_obj.get("amount_total") @@ -437,6 +442,12 @@ async def _apply_topup(session_obj: dict): f"💰 Top-up purchased{amount_txt}", f"{buyer_email or 'A user'} bought +{minutes} minutes.", ) + # Mirror the sale into OpenPanel, on the same profile the browser identifies. + analytics.track_revenue( + user_id, total, session_obj.get("currency"), + type="topup", source="openshorts", minutes=minutes, + stripe_session_id=session_id, email=buyer_email, **acquisition, + ) def _sub_item(sub_obj: dict): @@ -607,3 +618,98 @@ async def _notify_invoice_paid(invoice_obj: dict): f"💵 Payment received: {money}", f"{email or 'A customer'} — {kind}.", ) + + +# --------------------------------------------------------------------------- # +# OpenPanel revenue mirror +# --------------------------------------------------------------------------- # +# The browser fires ``Subscribed`` with the list price when the user comes back +# from Stripe, but that is an intent signal: it misses renewals entirely, is +# eaten by ad-blockers and can never see a refund. The webhook is the only +# place money is known for certain, so every paid invoice, top-up and refund is +# mirrored here as OpenPanel's native ``revenue`` event. ``profileId`` is the +# user's uuid — the same id the browser and the job events already use — so +# the sale lands on the profile that carries their pageviews and ``Signup``. + +_INVOICE_REVENUE_TYPE = { + "subscription_create": "new", + "subscription_cycle": "renewal", + "subscription_update": "upgrade", + "subscription_threshold": "renewal", +} + + +async def _acquisition_properties(session, user_id) -> dict: + """Never raises: a missing row simply reads as ``channel=direct``.""" + try: + row = await session.get(SignupAttribution, user_id) + except Exception: + row = None + return analytics.acquisition_properties(row) + + +async def _track_invoice_revenue(invoice_obj: dict): + try: + amount = int(invoice_obj.get("amount_paid") or 0) + except (TypeError, ValueError): + return + if amount <= 0: + return + cust = invoice_obj.get("customer") + if not cust: + return + async with database.session() as s: + user = (await s.execute( + select(User.id, User.email).where(User.stripe_customer_id == cust) + )).first() + if user is None: + return + user_id, email = user + plan = interval = None + sub_id = invoice_obj.get("subscription") + if sub_id: + sub = (await s.execute( + select(Subscription.plan, Subscription.interval).where( + Subscription.stripe_subscription_id == sub_id + ) + )).first() + if sub is not None: + plan, interval = sub + acquisition = await _acquisition_properties(s, user_id) + reason = invoice_obj.get("billing_reason") or "" + analytics.track_revenue( + user_id, amount, invoice_obj.get("currency"), + type=_INVOICE_REVENUE_TYPE.get(reason, "other"), source="openshorts", + plan=plan, interval=interval, billing_reason=reason or None, + stripe_invoice_id=invoice_obj.get("id"), email=email, **acquisition, + ) + + +async def _track_refund(charge_obj: dict): + """Negative revenue. ``amount_refunded`` is cumulative across partial + refunds, so prefer the newest entry of ``refunds.data`` when Stripe + includes it (it is not expanded by default on recent API versions).""" + refunds = ((charge_obj.get("refunds") or {}).get("data") or []) + raw = refunds[0].get("amount") if refunds else charge_obj.get("amount_refunded") + try: + amount = int(raw or 0) + except (TypeError, ValueError): + return + if amount <= 0: + return + cust = charge_obj.get("customer") + if not cust: + return + async with database.session() as s: + user = (await s.execute( + select(User.id, User.email).where(User.stripe_customer_id == cust) + )).first() + if user is None: + return + user_id, email = user + acquisition = await _acquisition_properties(s, user_id) + analytics.track_revenue( + user_id, -amount, charge_obj.get("currency"), + type="refund", source="openshorts", + stripe_charge_id=charge_obj.get("id"), email=email, **acquisition, + ) diff --git a/dashboard/src/contexts/AuthContext.jsx b/dashboard/src/contexts/AuthContext.jsx index 2a67a22..0788e46 100644 --- a/dashboard/src/contexts/AuthContext.jsx +++ b/dashboard/src/contexts/AuthContext.jsx @@ -7,7 +7,7 @@ import { createContext, useContext, useState, useEffect, useCallback } from 'react'; import { getApiUrl } from '../config'; import { apiFetch, apiJson, getToken, setToken, clearToken } from '../lib/api'; -import { track } from '../lib/analytics'; +import { track, identify, reset as resetAnalytics } from '../lib/analytics'; import { report as reportAttribution } from '../lib/attribution'; const AuthContext = createContext(null); @@ -25,6 +25,8 @@ export function AuthProvider({ children }) { try { const data = await apiJson('/api/me'); setMe(data); + // Same profileId (user uuid) the server-side events use. + identify(data?.user, { plan: data?.plan || 'free' }); return data; } catch (e) { // Stale/invalid token: drop it and fall back to anonymous BYOK. @@ -131,6 +133,7 @@ export function AuthProvider({ children }) { const logout = useCallback(() => { clearToken(); setMe(null); + resetAnalytics(); }, []); const value = { diff --git a/dashboard/src/lib/analytics.js b/dashboard/src/lib/analytics.js index 155d4ff..969b377 100644 --- a/dashboard/src/lib/analytics.js +++ b/dashboard/src/lib/analytics.js @@ -35,3 +35,32 @@ export function track(event, options) { /* analytics must never throw into the app */ } } + +/** + * Bind this browser to the signed-in account. `profileId` is the user's uuid — + * the same id the backend uses for its server-side events (ClipsDelivered, + * JobFailed and the `revenue` mirror of the Stripe webhook) — so a sale lands + * on the profile that carries the first visit's referrer and campaign. + * OpenPanel keeps the profile in memory only, so this runs on every boot. + */ +export function identify(user, props) { + try { + if (!user || !user.id) return; + if (typeof window !== 'undefined' && typeof window.op === 'function') { + window.op('identify', { profileId: String(user.id), email: user.email, ...(props || {}) }); + } + } catch (_) { + /* analytics must never throw into the app */ + } +} + +/** Forget the current profile (sign-out). */ +export function reset() { + try { + if (typeof window !== 'undefined' && typeof window.op === 'function') { + window.op('clear'); + } + } catch (_) { + /* ignore */ + } +} diff --git a/tests/test_openpanel_revenue.py b/tests/test_openpanel_revenue.py new file mode 100644 index 0000000..0daae27 --- /dev/null +++ b/tests/test_openpanel_revenue.py @@ -0,0 +1,76 @@ +"""OpenPanel revenue mirror: event shape, sign for refunds, acquisition props +from the SignupAttribution row, and silence when OpenPanel is unconfigured. + +Pure logic — the HTTP send is stubbed, no DB. +""" +from datetime import datetime, timezone +from types import SimpleNamespace + +import pytest + +from cloud import analytics + + +@pytest.fixture +def sent(monkeypatch): + """Capture payloads instead of POSTing; pretend OpenPanel is configured.""" + box = [] + monkeypatch.setenv("OPENPANEL_CLIENT_ID", "cid") + monkeypatch.setenv("OPENPANEL_CLIENT_SECRET", "sec") + + class _Loop: + def create_task(self, coro): + box.append(coro.cr_frame.f_locals["payload"]) + coro.close() + + monkeypatch.setattr(analytics.asyncio, "get_running_loop", lambda: _Loop()) + return box + + +def test_revenue_event_shape(sent): + analytics.track_revenue("11111111-1111-1111-1111-111111111111", 5900, "usd", + type="new", plan="creator", interval="monthly", channel="github.com", + email=None) + assert len(sent) == 1 + p = sent[0] + assert p["type"] == "track" + assert p["payload"]["name"] == "revenue" + assert p["payload"]["profileId"] == "11111111-1111-1111-1111-111111111111" + props = p["payload"]["properties"] + assert props["__revenue"] == 5900 # minor units, what OpenPanel's views read + assert props["amount"] == 59.0 # major units for custom reports + assert props["currency"] == "USD" + assert props["plan"] == "creator" and props["channel"] == "github.com" + assert "email" not in props # None props are dropped + + +def test_refund_is_negative_and_zero_is_skipped(sent): + analytics.track_revenue("u", -1500, "eur", type="refund") + analytics.track_revenue("u", 0, "usd") + analytics.track_revenue("u", "not-a-number", "usd") + assert [e["payload"]["properties"]["__revenue"] for e in sent] == [-1500] + assert sent[0]["payload"]["properties"]["currency"] == "EUR" + + +def test_silent_when_unconfigured(sent, monkeypatch): + monkeypatch.delenv("OPENPANEL_CLIENT_ID") + analytics.track_revenue("u", 5900, "usd") + assert sent == [] + + +def test_acquisition_properties(): + assert analytics.acquisition_properties(None) == {"channel": "direct"} + row = SimpleNamespace( + referrer="https://github.com/mutonby/openshorts", referrer_host="github.com", + landing_path="/?utm_source=github", utm_source="", utm_medium=None, utm_campaign="readme", + created_at=datetime(2026, 9, 1, tzinfo=timezone.utc), + ) + assert analytics.acquisition_properties(row) == { + "channel": "github.com", + "utm_campaign": "readme", + "referrer": "github.com", + "landing_path": "/?utm_source=github", + "signup_date": "2026-09-01T00:00:00+00:00", + } + row.utm_source = "producthunt" + assert analytics.acquisition_properties(row)["channel"] == "producthunt"