Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(referrals): clamp the funnel lookback to the same window rewards use
nirholas637e7b185903
diff --git a/api/_lib/referrals.js b/api/_lib/referrals.jsindex 438eb1c95..ac1ddec11 100644--- a/api/_lib/referrals.js+++ b/api/_lib/referrals.js@@ -423,6 +423,87 @@ export async function getReferredUsers(userId, opts = {}) {return { items, total: Number(total || 0), limit, offset, referral_commission_bps: bps };}+// Funnel lookback bounds. 30 days matches the activation-reward cap window in+// api/_lib/referral-rewards.js, so "this month" means the same thing on both+// sides of the referral system.+const FUNNEL_DAYS_DEFAULT = 30;+const FUNNEL_DAYS_MAX = 365;++function clampFunnelDays(days) {+ const n = Number.parseInt(days, 10);+ if (!Number.isFinite(n) || n <= 0) return FUNNEL_DAYS_DEFAULT;+ return Math.min(n, FUNNEL_DAYS_MAX);+}++function pct(numerator, denominator) {+ if (!denominator) return null;+ return Math.round((numerator / denominator) * 1000) / 10;+}++/**+ * The referrer's viral funnel over a trailing window: link visits, signups, and+ * activations, plus the two conversion rates between them.+ *+ * Each stage is counted from the event that actually happened, in its own time:+ * • visits — rows POST /api/referral/visit wrote into referral_visits,+ * already deduped to one per (code, visitor, UTC day).+ * • signups — accounts attributed to this referrer that were created in+ * the window.+ * • activations — referred users who reached their first win in the window,+ * counted from the referred-side activation grant in+ * credit_ledger. Counting the referred side (not the+ * referrer's own grant) keeps the number honest when the+ * referrer has hit the 30-day reward cap and stopped being+ * credited, and avoids miscounting the referrer's own welcome+ * credit as one of their referrals.+ *+ * Conversion rates are null rather than 0 when the prior stage is empty, so the+ * UI can say "no data yet" instead of showing a fake 0%.+ *+ * @param {string|number} userId the referrer+ * @param {{ days?: number|string }} [opts]+ * @returns {Promise<{ days: number, visits: number, signups: number, activations: number, visit_to_signup_pct: number|null, signup_to_activation_pct: number|null }>}+ */+export async function getReferralFunnel(userId, opts = {}) {+ const days = clampFunnelDays(opts.days);+ const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);++ const [visitRow] = await sql`+ SELECT COUNT(*)::int AS count FROM referral_visits+ WHERE referrer_user_id = ${userId} AND created_at >= ${since}+ `;+ const [signupRow] = await sql`+ SELECT COUNT(*)::int AS count FROM users+ WHERE referred_by_id = ${userId} AND deleted_at IS NULL AND created_at >= ${since}+ `;+ const [activationRow] = await sql`+ SELECT COUNT(*)::int AS count+ FROM users ru+ WHERE ru.referred_by_id = ${userId}+ AND ru.deleted_at IS NULL+ AND EXISTS (+ SELECT 1 FROM credit_ledger cl+ WHERE cl.user_id = ru.id+ AND cl.ref_type = 'referral_activation'+ AND cl.kind = 'grant'+ AND cl.created_at >= ${since}+ )+ `;++ const visits = Number(visitRow?.count || 0);+ const signups = Number(signupRow?.count || 0);+ const activations = Number(activationRow?.count || 0);++ return {+ days,+ visits,+ signups,+ activations,+ visit_to_signup_pct: pct(signups, visits),+ signup_to_activation_pct: pct(activations, signups),+ };+}+/*** Assemble the full membership-card payload for a user: signup position,* referral code + count, lifetime referral earnings, and a derived score.diff --git a/api/users/referrals.js b/api/users/referrals.jsindex aa79f696d..58859ee1d 100644--- a/api/users/referrals.js+++ b/api/users/referrals.js@@ -1,7 +1,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { getMembershipCard, getReferredUsers } from '../_lib/referrals.js';+import { getMembershipCard, getReferredUsers, getReferralFunnel } from '../_lib/referrals.js';// GET /api/users/referrals — the signed-in user's membership card payload:// referral code (lazily minted if absent), referral count + lifetime earnings,@@ -11,7 +11,9 @@ import { getMembershipCard, getReferredUsers } from '../_lib/referrals.js';// actionable referral table — not just a counter. Powers /dashboard/referrals.//// Query params (optional): ?limit (1–100, default 20) & ?offset (>=0) page the-// referred-user list, sorted by revenue generated (desc).+// referred-user list, sorted by revenue generated (desc). ?funnel_days (1–365,+// default 30) sets the lookback for the `funnel` block, which reports the+// visit → signup → activation conversion recorded by POST /api/referral/visit.export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;@@ -28,10 +30,13 @@ export default wrap(async (req, res) => {if (!card) return error(res, 404, 'not_found', 'user not found');const url = new URL(req.url, 'http://localhost');- const referredUsers = await getReferredUsers(userId, {- limit: url.searchParams.get('limit'),- offset: url.searchParams.get('offset'),- });+ const [referredUsers, funnel] = await Promise.all([+ getReferredUsers(userId, {+ limit: url.searchParams.get('limit'),+ offset: url.searchParams.get('offset'),+ }),+ getReferralFunnel(userId, { days: url.searchParams.get('funnel_days') }),+ ]);- return json(res, 200, { ...card, referred_users: referredUsers });+ return json(res, 200, { ...card, referred_users: referredUsers, funnel });});diff --git a/src/dashboard-next/pages/referrals.js b/src/dashboard-next/pages/referrals.jsindex f189c2f66..9911932dd 100644--- a/src/dashboard-next/pages/referrals.js+++ b/src/dashboard-next/pages/referrals.js@@ -55,6 +55,58 @@ function fmtUsd(n) {return Number(n || 0).toLocaleString('en-US', { style: 'currency', currency: 'USD' });}+/** A conversion rate the API left null (empty prior stage) reads as a dash, never a fake 0%. */+function fmtPct(n) {+ return n == null ? '—' : `${Number(n).toLocaleString('en-US', { maximumFractionDigits: 1 })}%`;+}++/**+ * The share funnel: link visits (POST /api/referral/visit), signups attributed+ * to those links, and referrals who reached their first creation. Rendered only+ * once at least one visit exists, so a member who has never shared sees the+ * "How referrals work" steps instead of an all-zero table.+ */+function funnelPanel(funnel) {+ if (!funnel || !Number(funnel.visits)) return '';+ const visits = Number(funnel.visits) || 0;+ const rows = [+ { label: 'Link visits', count: visits, rate: '', hint: 'People who opened your link' },+ {+ label: 'Signups',+ count: Number(funnel.signups) || 0,+ rate: fmtPct(funnel.visit_to_signup_pct),+ hint: 'Visits that became accounts',+ },+ {+ label: 'Activated',+ count: Number(funnel.activations) || 0,+ rate: fmtPct(funnel.signup_to_activation_pct),+ hint: 'Signups that made a first creation',+ },+ ];+ return `+ <section class="dn-panel" style="margin-top:20px" aria-label="Your share funnel">+ <div class="dn-panel-title" style="margin-bottom:4px">Share funnel</div>+ <p class="ref-funnel-note">Last ${fmtInt(funnel.days)} days. Visits are counted once per person per day.</p>+ <div class="ref-funnel">+ ${rows+ .map(+ (r) => `+ <div class="ref-funnel-row">+ <div class="ref-funnel-head">+ <span class="ref-funnel-label">${r.label}</span>+ <span class="ref-funnel-value">${fmtInt(r.count)}${r.rate ? `<small>${r.rate}</small>` : ''}</span>+ </div>+ <div class="ref-funnel-bar"><i style="width:${Math.max(2, Math.round((r.count / visits) * 100))}%"></i></div>+ <div class="ref-funnel-hint">${r.hint}</div>+ </div>`,+ )+ .join('')}+ </div>+ </section>+ `;+}+/** "06/27" — two years out, the card's notional validity. */function expLabel(memberSince) {const base = memberSince ? new Date(memberSince) : new Date();@@ -201,6 +253,18 @@ function injectStyles() {.ref-tile-k{font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:.05em;margin-bottom:6px}.ref-tile-v{font-size:24px;font-weight:700;letter-spacing:-0.01em;font-family:${MONO}}.ref-tile-v small{font-size:13px;color:var(--nxt-ink-fade);font-weight:500;font-family:inherit}++ .ref-funnel-note{margin:0 0 14px;font-size:12.5px;color:var(--nxt-ink-fade)}+ .ref-funnel{display:flex;flex-direction:column;gap:14px}+ .ref-funnel-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px}+ .ref-funnel-label{font-size:12.5px;letter-spacing:.05em;text-transform:uppercase;color:var(--nxt-ink-fade)}+ .ref-funnel-value{font-size:19px;font-weight:700;font-family:${MONO};line-height:1}+ .ref-funnel-value small{margin-left:8px;font-size:12px;font-weight:600;color:#c4b5fd;font-family:inherit}+ .ref-funnel-bar{margin-top:7px;height:7px;border-radius:999px;background:rgba(255,255,255,.05);overflow:hidden}+ .ref-funnel-bar i{display:block;height:100%;border-radius:999px;+ background:linear-gradient(90deg,#a78bfa,#c4b5fd);transition:width .5s cubic-bezier(.22,1,.36,1)}+ .ref-funnel-hint{margin-top:6px;font-size:12px;color:var(--nxt-ink-fade)}+ @media (prefers-reduced-motion:reduce){.ref-funnel-bar i{transition:none}}.ref-steps{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px}.ref-step{display:flex;gap:12px;align-items:flex-start}.ref-step-n{flex:0 0 auto;width:26px;height:26px;border-radius:50%;display:grid;place-items:center;@@ -523,6 +587,8 @@ function renderCard(host, card) {<div class="ref-tile"><div class="ref-tile-k">Score</div><div class="ref-tile-v">${fmtInt(card.score)}</div></div></div>+ ${funnelPanel(card.funnel)}+<section class="dn-panel" style="margin-top:20px" data-slot="tier-panel" aria-label="Your membership tier"></section><section class="dn-panel" style="margin-top:20px" data-slot="referrals-list" aria-label="Your referrals"></section>