src/analytics.js
// Funnel, attribution, weekly cohort retention and campaign comparison over normalised events.
// Every number is a count or ratio of rows the user supplied. Denominators of 0 give null, not 0.
import { ToolError } from "./errors.js";
const DAY = 86400000;
const Z95 = 1.959963984540054;
const r4 = (x) => (x === null || !Number.isFinite(x) ? null : Math.round(x * 10000) / 10000);
export const ratio = (a, b) => (b > 0 ? r4(a / b) : null);
/** 95% Wilson score interval for x successes in n trials. */
export function wilson(x, n) {
if (!(n > 0)) return null;
const p = x / n;
const z2 = Z95 * Z95;
const denom = 1 + z2 / n;
const center = (p + z2 / (2 * n)) / denom;
const half = (Z95 * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / denom;
return [r4(Math.max(0, center - half)), r4(Math.min(1, center + half))];
}
// Abramowitz & Stegun 7.1.26 (absolute error < 1.5e-7).
function erf(x) {
const s = Math.sign(x);
const a = Math.abs(x);
const t = 1 / (1 + 0.3275911 * a);
const y = 1 - ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-a * a);
return s * y;
}
const normCdf = (z) => 0.5 * (1 + erf(z / Math.SQRT2));
/** Two-sided two-proportion z-test. Returns { p, reliable } or null when undefined (zero variance). */
export function twoProportion(x1, n1, x2, n2) {
if (!(n1 > 0 && n2 > 0)) return null;
const p = (x1 + x2) / (n1 + n2);
const se = Math.sqrt(p * (1 - p) * (1 / n1 + 1 / n2));
if (!(se > 0)) return null;
const z = (x1 / n1 - x2 / n2) / se;
return { p: r4(2 * (1 - normCdf(Math.abs(z)))), reliable: Math.min(x1, x2, n1 - x1, n2 - x2) >= 5 };
}
function byUser(events) {
const m = new Map();
for (const ev of events) {
let u = m.get(ev.u);
if (!u) m.set(ev.u, (u = []));
u.push(ev);
}
return m;
}
/** First index in sorted `arr` with value >= x. */
function lowerBound(arr, x) {
let lo = 0;
let hi = arr.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (arr[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
function eventTimes(evs) {
const m = new Map();
for (const ev of evs) {
let a = m.get(ev.e);
if (!a) m.set(ev.e, (a = []));
a.push(ev.t);
}
return m;
}
// ------------------------------------------------------------------------------------------------
export function funnel(events, steps, windowDays) {
if (new Set(steps).size !== steps.length) throw new ToolError("invalid_input", "steps must not repeat an event name.");
const windowMs = windowDays ? windowDays * DAY : Infinity;
const counts = steps.map(() => 0);
for (const evs of byUser(events).values()) {
const times = eventTimes(evs);
let prev = -Infinity;
let t0 = null;
for (const [k, step] of steps.entries()) {
const arr = times.get(step);
if (!arr) break;
const i = lowerBound(arr, prev);
if (i >= arr.length) break;
const t = arr[i];
if (k === 0) t0 = t;
else if (t - t0 > windowMs) break;
counts[k]++;
prev = t;
}
}
const out = steps.map((event, k) => ({
step: k + 1,
event,
users: counts[k],
conversion_from_previous: k === 0 ? null : ratio(counts[k], counts[k - 1]),
conversion_from_first: k === 0 ? (counts[0] > 0 ? 1 : null) : ratio(counts[k], counts[0]),
drop_off_from_previous: k === 0 ? null : counts[k - 1] - counts[k],
ci95_from_first: k === 0 ? null : wilson(counts[k], counts[0]),
}));
const last = counts[counts.length - 1];
const notes = [];
if (counts[0] === 0) notes.push(`No user has the first step event "${steps[0]}"; conversion is undefined (n/a), not 0%.`);
else if (counts[0] < 30) notes.push(`Only ${counts[0]} users entered the funnel; rates are indicative only.`);
return {
steps: out,
overall: { entered: counts[0], completed: last, conversion: ratio(last, counts[0]), ci95: wilson(last, counts[0]) },
definition: `Distinct users. Step 1 is each user's first "${steps[0]}" event; each later step is the user's first matching event at or after the previous step${windowDays ? `, within ${windowDays} days of step 1` : ""}.`,
notes,
};
}
// ------------------------------------------------------------------------------------------------
const GROUP_PARTS = { source: ["src"], source_medium: ["src", "med"], campaign: ["camp"], source_medium_campaign: ["src", "med", "camp"] };
const PART_NAME = { src: "source", med: "medium", camp: "campaign" };
function groupKey(ev, groupBy) {
const parts = GROUP_PARTS[groupBy];
const label = parts.map((p) => ev[p] || "(none)").join(" / ");
const fields = Object.fromEntries(parts.map((p) => [PART_NAME[p], ev[p] || "(none)"]));
return { label, fields };
}
export function attribution(events, { conversionEvents, lookbackDays = 30, groupBy = "source_medium_campaign", count = "first_per_user" }) {
const lookMs = lookbackDays * DAY;
const convSet = new Set(conversionEvents);
const rows = new Map();
const row = (k) => {
if (!rows.has(k.label)) rows.set(k.label, { channel: k.label, ...k.fields, first_touch: 0, last_touch: 0, by_event: Object.fromEntries(conversionEvents.map((e) => [e, { first_touch: 0, last_touch: 0 }])) });
return rows.get(k.label);
};
let conversions = 0;
let unattributed = 0;
const unattributedBy = Object.fromEntries(conversionEvents.map((e) => [e, 0]));
for (const evs of byUser(events).values()) {
const touches = evs.filter((e) => e.touch);
const seen = new Set();
for (const c of evs) {
if (!convSet.has(c.e)) continue;
if (count === "first_per_user") {
if (seen.has(c.e)) continue;
seen.add(c.e);
}
conversions++;
const window = touches.filter((t) => t.t <= c.t && t.t >= c.t - lookMs && !(t.t === c.t && t.order > c.order));
if (!window.length) {
unattributed++;
unattributedBy[c.e]++;
continue;
}
const f = row(groupKey(window[0], groupBy));
const l = row(groupKey(window[window.length - 1], groupBy));
f.first_touch++;
f.by_event[c.e].first_touch++;
l.last_touch++;
l.by_event[c.e].last_touch++;
}
}
const attributed = conversions - unattributed;
const list = [...rows.values()]
.map((r) => ({ ...r, first_touch_share: ratio(r.first_touch, attributed), last_touch_share: ratio(r.last_touch, attributed) }))
.sort((a, b) => b.last_touch - a.last_touch || b.first_touch - a.first_touch || a.channel.localeCompare(b.channel));
const notes = [];
if (conversions === 0) notes.push(`No ${conversionEvents.join("/")} events were found, so there is nothing to attribute.`);
if (unattributed) notes.push(`${unattributed} of ${conversions} conversions had no UTM-tagged touch in the ${lookbackDays} days before them; they are reported as unattributed (${Object.entries(unattributedBy).filter(([, n]) => n).map(([e, n]) => `${e} ${n}`).join(", ")}), not assigned to any channel.`);
if (attributed > 0 && attributed < 30) notes.push(`Only ${attributed} attributed conversions; channel shares are unstable.`);
return {
rows: list,
conversions,
attributed,
unattributed,
unattributed_by_event: unattributedBy,
lookback_days: lookbackDays,
definition: `Each ${count === "all" ? "conversion event" : "user's first conversion of each event"} is credited to the earliest (first touch) and latest (last touch) UTM-tagged row of the same user within ${lookbackDays} days before it. Direct traffic ((direct)/(none)) is not a touch. Shares are of attributed conversions.`,
notes,
};
}
// ------------------------------------------------------------------------------------------------
export const mondayOf = (ms) => {
const day = Math.floor(ms / DAY);
const wd = (((day + 4) % 7) + 7) % 7; // 0 = Sunday
return (day - ((wd + 6) % 7)) * DAY;
};
export function isoWeekLabel(mondayMs) {
const thu = new Date(mondayMs + 3 * DAY);
const y = thu.getUTCFullYear();
const jan1 = Date.UTC(y, 0, 1);
const week = Math.floor((thu.getTime() - jan1) / DAY / 7) + 1;
return `${y}-W${String(week).padStart(2, "0")}`;
}
export function cohortRetention(events, { cohortEvent, activityEvents, weeks = 8, smallCohort = 20 }) {
const activity = activityEvents ? new Set(activityEvents) : null;
const notes = [];
if (!events.length) return { cohorts: [], weeks, data_end: null, definition: "", notes: ["No usable rows."] };
const dataEnd = events[events.length - 1].t;
const lastWeek = mondayOf(dataEnd);
const cohorts = new Map();
let noCohortEvent = 0;
for (const evs of byUser(events).values()) {
const start = cohortEvent ? evs.find((e) => e.e === cohortEvent) : evs[0];
if (!start) {
noCohortEvent++;
continue;
}
const cw = mondayOf(start.t);
let c = cohorts.get(cw);
if (!c) cohorts.set(cw, (c = { size: 0, active: Array(weeks + 1).fill(0) }));
c.size++;
const activeWeeks = new Set();
for (const e of evs) {
if (e.t < start.t || (activity && !activity.has(e.e))) continue;
const k = Math.round((mondayOf(e.t) - cw) / (7 * DAY));
if (k <= weeks) activeWeeks.add(k);
}
for (const k of activeWeeks) c.active[k]++;
}
const list = [...cohorts.entries()]
.sort((a, b) => a[0] - b[0])
.map(([cw, c]) => ({
cohort_week: isoWeekLabel(cw),
week_start_date: new Date(cw).toISOString().slice(0, 10),
size: c.size,
retention: c.active.map((n, k) => {
const ws = cw + k * 7 * DAY;
if (ws > lastWeek) return { week: k, active: null, rate: null, observed: false };
const cell = { week: k, active: n, rate: ratio(n, c.size), observed: true };
if (ws === lastWeek && dataEnd < ws + 7 * DAY - 1000) cell.partial = true;
return cell;
}),
}));
const small = list.filter((c) => c.size < smallCohort);
if (small.length) notes.push(`${small.length} cohort(s) have fewer than ${smallCohort} users (${small.map((c) => `${c.cohort_week}: ${c.size}`).join(", ")}); their rates swing a lot.`);
if (noCohortEvent) notes.push(`${noCohortEvent} user(s) never had "${cohortEvent}" and are in no cohort.`);
notes.push(`Your data ends ${new Date(dataEnd).toISOString()}: later weeks are "not observed" (null), and the last week is partial.`);
return {
cohorts: list,
weeks,
data_end: new Date(dataEnd).toISOString(),
definition: `Cohort = ISO week (Monday 00:00 UTC) of each user's ${cohortEvent ? `first "${cohortEvent}"` : "first event"}. Week k retention = users with at least one ${activity ? [...activity].join("/") : "event"} in week k after joining, divided by cohort size.`,
notes,
};
}
// ------------------------------------------------------------------------------------------------
export function campaignComparison(events, { conversionEvents, groupBy = "campaign", lookbackDays = 30, minSample = 30, hasSessions }) {
const lookMs = lookbackDays * DAY;
const groups = new Map();
const users = byUser(events);
for (const ev of events) {
if (!ev.touch) continue;
const k = groupKey(ev, groupBy);
let g = groups.get(k.label);
if (!g) groups.set(k.label, (g = { label: k.label, fields: k.fields, first: new Map(), sessions: new Set(), touchRows: 0 }));
if (!g.first.has(ev.u)) g.first.set(ev.u, ev.t);
g.touchRows++;
g.sessions.add(ev.sid ? JSON.stringify([ev.u, ev.sid]) : `row:${ev.order}`);
}
const times = new Map([...users.entries()].map(([u, evs]) => [u, eventTimes(evs)]));
const rows = [...groups.values()].map((g) => {
const visitors = g.first.size;
const conversions = {};
const confidence_notes = [];
for (const e of conversionEvents) {
let n = 0;
for (const [u, ft] of g.first) {
const arr = times.get(u).get(e);
if (!arr) continue;
const i = lowerBound(arr, ft);
if (i < arr.length && arr[i] <= ft + lookMs) n++;
}
conversions[e] = { users: n, rate: ratio(n, visitors), ci95: wilson(n, visitors) };
if (n < 5) confidence_notes.push(`${e}: ${n} conversion(s); the interval is wide.`);
}
if (visitors < minSample) confidence_notes.unshift(`Small sample: ${visitors} visitor(s) (< ${minSample}); treat rates as indicative only.`);
return {
group: g.label,
...g.fields,
visitors,
sessions: hasSessions ? g.sessions.size : g.touchRows,
conversions,
confidence: visitors < minSample ? "low" : "ok",
confidence_notes,
};
});
rows.sort((a, b) => b.visitors - a.visitors || a.group.localeCompare(b.group));
const comparisons = conversionEvents.map((e) => {
const ranked = rows.filter((r) => r.visitors > 0).sort((a, b) => b.conversions[e].rate - a.conversions[e].rate || b.visitors - a.visitors);
if (ranked.length < 2) return { event: e, note: `Fewer than two groups have visitors; nothing to compare for ${e}.` };
const [a, b] = ranked;
const ca = a.conversions[e];
const cb = b.conversions[e];
const t = twoProportion(ca.users, a.visitors, cb.users, b.visitors);
const base = { event: e, best: a.group, runner_up: b.group };
if (!t) return { ...base, p_value: null, significant: null, note: `${a.group} and ${b.group} have identical ${e} rates (no variance to test).` };
if (!t.reliable) return { ...base, p_value: t.p, significant: null, note: `Too few conversions or non-conversions (< 5 in a group) for a reliable z-test between ${a.group} and ${b.group}; approximate p = ${t.p}.` };
const sig = t.p < 0.05;
return { ...base, p_value: t.p, significant: sig, note: sig ? `${a.group} converts better than ${b.group} for ${e} (two-proportion z-test p = ${t.p} < 0.05).` : `The difference between ${a.group} and ${b.group} for ${e} is not statistically significant at the 95% level (p = ${t.p}).` };
});
const notes = ["A user who touched several groups counts as a visitor of each, so visitors and conversions overlap across rows; use attribution for credit that sums to the total."];
if (!hasSessions) notes.push("No session_id column was found, so sessions = number of UTM-tagged rows.");
return {
rows,
comparisons,
group_by: groupBy,
definition: `Visitors = distinct users with a UTM-tagged row in the group. A visitor converts when the event happens at or after their first touch in that group and within ${lookbackDays} days. Intervals are 95% Wilson intervals.`,
notes,
};
}