Merge origin/main: analytics + billing cross-sub guard

Conflicto resuelto en AuthContext (se mantienen el track('Signup') y el
enrutado del plan free). Además, fix de la interacción entre ambos cambios:
AccountPage daba el checkout por activado en cuanto /api/me devolvía un
plan, pero 'free' ahora existe desde el primer instante — se exige un plan
de pago antes de parar el polling, disparar el goal Subscribed y llevar al
usuario a conectar sus redes.
This commit is contained in:
juancarlos.cavero 2026-07-20 15:22:52 +02:00
commit a42297f120
6 changed files with 93 additions and 8 deletions

View file

@ -332,6 +332,18 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime):
# Order guard: ignore events older than what we've already applied. # Order guard: ignore events older than what we've already applied.
if row and row.last_event_at and event_created < row.last_event_at: if row and row.last_event_at and event_created < row.last_event_at:
return return
# Cross-subscription guard: the table keeps one row per user, so an
# event for a *different* subscription of the same user must not clobber
# the row that represents their live plan. This is exactly what happens
# when a user has a dangling sub (e.g. a past_due annual that gets
# canceled) alongside a live one (a trialing monthly): the canceled
# sub's update would otherwise overwrite the good row. Only let another
# subscription take over when the stored one is no longer live.
if row and row.stripe_subscription_id != sub_obj["id"]:
stored_live = row.status in ("active", "trialing", "past_due", "unpaid")
incoming_live = sub_obj.get("status") in ("active", "trialing", "past_due")
if stored_live and not incoming_live:
return
start, end = _sub_period(sub_obj) start, end = _sub_period(sub_obj)
now_canceling = bool(sub_obj.get("cancel_at_period_end")) now_canceling = bool(sub_obj.get("cancel_at_period_end"))
# Detect the moment the user hits "cancel" (False -> True). # Detect the moment the user hits "cancel" (False -> True).

View file

@ -191,7 +191,20 @@
<!-- Analytics --> <!-- Analytics -->
<script defer data-domain="openshorts.app" src="https://analytics.fotoexamen.com/js/script.js"></script> <script defer data-domain="openshorts.app" src="https://analytics.fotoexamen.com/js/script.js"></script>
</head> <script>window.plausible = window.plausible || function () { (window.plausible.q = window.plausible.q || []).push(arguments) }</script>
<!-- OpenPanel analytics (self-hosted) -->
<script>
window.op = window.op || function () { var n = []; return new Proxy(function () { arguments.length && n.push([].slice.call(arguments)); }, { get: function (t, r) { return "q" === r ? n : function () { n.push([r].concat([].slice.call(arguments))); }; }, has: function (t, r) { return "q" === r; } }); }();
window.op("init", {
apiUrl: "https://api.openpanel.fotoexamen.com",
clientId: "9b7ab939-bdef-4097-87c4-bb4a2dbe034d",
trackScreenViews: true,
trackOutgoingLinks: true,
trackAttributes: true,
});
</script>
<script src="https://openpanel.dev/op1.js" defer async></script>
</head>
<body> <body>
<div id="root"></div> <div id="root"></div>

View file

@ -2,6 +2,7 @@ import React, { useState, useEffect, useCallback } from 'react';
import { Loader2, CreditCard, LogOut, Plus } from 'lucide-react'; import { Loader2, CreditCard, LogOut, Plus } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api'; import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
const fmt1 = (n) => Math.round((n || 0) * 10) / 10; const fmt1 = (n) => Math.round((n || 0) * 10) / 10;
@ -21,12 +22,36 @@ export default function AccountPage() {
const t = setInterval(async () => { const t = setInterval(async () => {
tries += 1; tries += 1;
const data = await refreshMe(); const data = await refreshMe();
if ((data && data.plan) || tries > 15) { // 'free' is the default plan for any signed-in account, so it does NOT
// mean the checkout landed — keep polling until the webhook writes the
// paid subscription.
const paidPlan = data?.plan && data.plan !== 'free';
if (paidPlan || tries > 15) {
clearInterval(t); clearInterval(t);
setActivating(false); setActivating(false);
// Fire the Subscribed conversion goal. A pending-checkout stash (set in
// PricingSection) carries the plan price, so we can attach real revenue;
// top-ups don't set it, so they never count as a subscription.
if (paidPlan) {
let pending = null;
try { pending = JSON.parse(localStorage.getItem('os_pending_checkout') || 'null'); } catch (_) { /* ignore */ }
if (pending) {
// This Plausible is Community Edition, which has no revenue goals —
// so the price rides along as plain props (value_usd / plan) that CE
// can break the goal down by. The exact MRR still lives in Stripe.
track('Subscribed', {
props: {
plan: pending.plan,
interval: pending.interval,
value_usd: Math.round((pending.amount || 0) / 100),
},
});
try { localStorage.removeItem('os_pending_checkout'); } catch (_) { /* ignore */ }
}
}
// First time a plan activates, take the user straight to connect their // First time a plan activates, take the user straight to connect their
// socials. Guard with a flag so top-up checkouts don't re-trigger it. // socials. Guard with a flag so top-up checkouts don't re-trigger it.
if (data && data.plan && !localStorage.getItem('os_socials_prompted')) { if (paidPlan && !localStorage.getItem('os_socials_prompted')) {
localStorage.setItem('os_socials_prompted', '1'); localStorage.setItem('os_socials_prompted', '1');
try { try {
const { access_url } = await apiJson('/api/social/connect', { method: 'POST' }); const { access_url } = await apiJson('/api/social/connect', { method: 'POST' });

View file

@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';
import { Check, Loader2, Zap, Github, Server } from 'lucide-react'; import { Check, Loader2, Zap, Github, Server } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext'; import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api'; import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import SegmentedControl from './ui/SegmentedControl'; import SegmentedControl from './ui/SegmentedControl';
const PLAN_ORDER = ['starter', 'creator', 'pro']; const PLAN_ORDER = ['starter', 'creator', 'pro'];
@ -31,14 +32,22 @@ export default function PricingSection({ onRequireLogin }) {
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}, []); }, []);
const checkout = async (price_id) => { const checkout = async (entry) => {
if (!isSignedIn) { onRequireLogin?.(price_id); return; } if (!isSignedIn) { onRequireLogin?.(entry.price_id); return; }
setBusyPrice(price_id); setBusyPrice(entry.price_id);
track('CheckoutStarted', { props: { plan: entry.plan, interval: entry.interval } });
// Stash the price so we can attach real revenue to the Subscribed goal when
// the user returns from Stripe (see AccountPage's checkout=success handler).
try {
localStorage.setItem('os_pending_checkout', JSON.stringify({
plan: entry.plan, interval: entry.interval, amount: entry.amount, currency: entry.currency,
}));
} catch (_) { /* ignore storage errors */ }
try { try {
const { url } = await apiJson('/api/billing/checkout', { const { url } = await apiJson('/api/billing/checkout', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ price_id }), body: JSON.stringify({ price_id: entry.price_id }),
}); });
window.location.href = url; window.location.href = url;
} catch (e) { } catch (e) {
@ -118,7 +127,7 @@ export default function PricingSection({ onRequireLogin }) {
{plan === 'pro' && <li className="flex items-start gap-2"><Zap size={16} className="text-brass shrink-0 mt-0.5" /> <span>Priority processing queue</span></li>} {plan === 'pro' && <li className="flex items-start gap-2"><Zap size={16} className="text-brass shrink-0 mt-0.5" /> <span>Priority processing queue</span></li>}
</ul> </ul>
<button <button
onClick={() => checkout(entry.price_id)} onClick={() => checkout(entry)}
disabled={busyPrice === entry.price_id} disabled={busyPrice === entry.price_id}
className={`w-full ${highlight ? 'btn-primary' : 'btn-ghost'}`} className={`w-full ${highlight ? 'btn-primary' : 'btn-ghost'}`}
> >

View file

@ -7,6 +7,7 @@
import { createContext, useContext, useState, useEffect, useCallback } from 'react'; import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { getApiUrl } from '../config'; import { getApiUrl } from '../config';
import { apiFetch, apiJson, getToken, setToken, clearToken } from '../lib/api'; import { apiFetch, apiJson, getToken, setToken, clearToken } from '../lib/api';
import { track } from '../lib/analytics';
const AuthContext = createContext(null); const AuthContext = createContext(null);
export const useAuth = () => useContext(AuthContext); export const useAuth = () => useContext(AuthContext);
@ -65,6 +66,9 @@ export function AuthProvider({ children }) {
} }
} }
const signedInMe = await refreshMe(); const signedInMe = await refreshMe();
// This handler only runs on the auth redirect, so a resolved user here is
// a fresh sign-in / sign-up — the top of the conversion funnel.
if (signedInMe?.user) track('Signup', { props: { method: kind === 'verify' ? 'magic_link' : 'google' } });
// Google sign-ins are entitled (free plan) and land in the app; only // Google sign-ins are entitled (free plan) and land in the app; only
// magic-link-only accounts (no entitlement) are routed to pricing, where // magic-link-only accounts (no entitlement) are routed to pricing, where
// the free card tells them to use Google. // the free card tells them to use Google.

View file

@ -0,0 +1,22 @@
// Lightweight Plausible custom-event helper.
//
// The hosted openshorts.app build loads the Plausible script (see index.html),
// which exposes `window.plausible`. Self-hosted builds, ad-blockers or offline
// dev simply won't have it — every call here is a safe no-op in that case, so
// analytics can never break the app or leak into the open-source experience.
//
// This targets a Plausible Community Edition instance, which has NO revenue
// goals (that's a Cloud-only feature) — so prices ride along as ordinary props
// (e.g. value_usd) that CE can break a goal down by. Goals to create (by name):
// - Signup (custom event) — account created / signed in
// - CheckoutStarted (custom event) — redirected to Stripe Checkout
// - Subscribed (custom event) — plan activated after checkout
export function track(event, options) {
try {
if (typeof window !== 'undefined' && typeof window.plausible === 'function') {
window.plausible(event, options);
}
} catch (_) {
/* analytics must never throw into the app */
}
}