Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Marketing Analytics v0.2.1 · claude-code

Archive SHA-256 ee6fb9f311128ee4857c2908161f8fbedc5f80dff026158ba4f335c50a58671d · 50.6 KB · built Nov 27, 2026

src/spend.js

// Spend efficiency from aggregated ad-platform / channel exports (one row per day, week or campaign with
// spend, impressions, clicks, conversions, revenue). Every figure is a sum or ratio of the user's cells.
// Currency symbols, thousands separators and decimal commas are parsed; mixed currencies are refused
// rather than summed; "Total" rows are skipped so they are not double counted; a zero denominator
// gives null ("n/a"), never Infinity or 0.
import { ToolError } from "./errors.js";
import { parseCsv } from "./csv.js";
import { parseTimestamp } from "./data.js";
import { mondayOf, isoWeekLabel, wilson } from "./analytics.js";
import { cell } from "./report.js";

export const METRICS = ["spend", "impressions", "clicks", "conversions", "revenue"];
const DIMENSIONS = ["date", "channel", "campaign"];

/** Header normalisation: lower case, currency in parentheses removed, punctuation collapsed to "_". */
const norm = (h) => String(h).toLowerCase().replace(/\((?:[a-z]{3}|[$€£¥₹])\)/g, "").replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");

const ALIASES = {
  date: ["date", "day", "week", "month", "reporting_starts", "date_start", "start_date", "period", "timestamp"],
  channel: ["channel", "source", "platform", "network", "utm_source", "publisher_platform", "channel_group", "default_channel_group", "source_medium", "session_source_medium"],
  campaign: ["campaign", "campaign_name", "utm_campaign", "ad_set_name", "ad_group"],
  spend: ["spend", "cost", "amount_spent", "ad_spend", "media_cost", "spent"],
  impressions: ["impressions", "impr", "imps"],
  clicks: ["clicks", "link_clicks", "clicks_all"],
  conversions: ["conversions", "conv", "results", "purchases", "signups", "sign_ups", "leads", "all_conv"],
  revenue: ["revenue", "conversion_value", "conv_value", "purchase_value", "purchases_conversion_value", "total_conversion_value", "all_conv_value", "value"],
};

const CODE_OF = { "€": "EUR", "£": "GBP", "¥": "JPY", "₹": "INR", "US$": "USD", "CA$": "CAD", "C$": "CAD", "A$": "AUD", "NZ$": "NZD", "$": "$" };
const DOLLAR_CODES = new Set(["USD", "CAD", "AUD", "NZD", "HKD", "SGD", "MXN"]);
const CURRENCY_RE = /^(US\$|CA\$|C\$|A\$|NZ\$|[$€£¥₹]|[A-Z]{3}(?=[\s\d.,(-]))|(US\$|CA\$|C\$|A\$|NZ\$|[$€£¥₹]|(?<=[\d\s.,)])[A-Z]{3})$/;
const BLANK = new Set(["", "-", "--", "—", "–", "n/a", "na", "(blank)"]);
const TOTAL = /^\s*(grand\s+)?totals?\b/i;
const r2 = (x) => (x === null ? null : Math.round(x * 100) / 100);
const r4 = (x) => (x === null || !Number.isFinite(x) ? null : Math.round(x * 10000) / 10000);
const div = (a, b) => (a === null || b === null || !(b > 0) ? null : r4(a / b));

/**
 * Splits a numeric cell into { sign, digits, currency } or { blank: true }, or null when it is not a number.
 * `digits` still contains the original separators; the decimal convention is decided per file.
 */
export function lexNumber(raw) {
  let s = String(raw ?? "").replace(/[\u00A0\u202F ]/g, " ").trim();
  if (BLANK.has(s.toLowerCase())) return { blank: true };
  let sign = 1;
  if (/^\(.*\)$/.test(s)) { sign = -1; s = s.slice(1, -1).trim(); }
  if (/^[-−]/.test(s)) { sign = -sign; s = s.slice(1).trim(); }
  let currency = null;
  for (let k = 0; k < 2; k++) {
    const m = CURRENCY_RE.exec(s);
    if (!m) break;
    const tok = m[1] ?? m[2];
    currency = CODE_OF[tok] ?? tok;
    s = (m[1] ? s.slice(tok.length) : s.slice(0, s.length - tok.length)).trim();
  }
  if (/^[-−]/.test(s)) { sign = -sign; s = s.slice(1).trim(); }
  s = s.replace(/[ ']/g, "");
  if (!/^\d[\d.,]*$/.test(s) || /[.,]{2}/.test(s) || /[.,]$/.test(s)) return null;
  return { sign, digits: s, currency };
}

/** Chooses "1,234.56" or "1.234,56" from the digit strings of one file. */
export function inferNumberFormat(digitStrings) {
  let dot = 0;
  let comma = 0;
  for (const d of digitStrings) {
    const lastDot = d.lastIndexOf(".");
    const lastComma = d.lastIndexOf(",");
    const commas = (d.match(/,/g) ?? []).length;
    const dots = (d.match(/\./g) ?? []).length;
    // Evidence for decimal commas ("1.234,56", "12,5", "0,75", "1.234.567") or decimal points
    // ("1,234.56", "12.5", "0.75", "1,234,567"). "1,234" or "1.234" alone is ambiguous: no evidence.
    if (lastDot >= 0 && lastComma >= 0) {
      if (lastComma > lastDot) comma++;
      else dot++;
    } else if (lastComma >= 0) {
      if (commas > 1) dot++;
      else if (/,\d{1,2}$/.test(d) || /,\d{4,}$/.test(d) || /^0,/.test(d)) comma++;
    } else if (lastDot >= 0) {
      if (dots > 1) comma++;
      else if (/\.\d{1,2}$/.test(d) || /\.\d{4,}$/.test(d) || /^0\./.test(d)) dot++;
    }
  }
  if (dot && comma) return { format: null, evidence: { dot, comma } };
  return { format: comma ? "1.234,56" : "1,234.56", inferred: !dot && !comma };
}

export function toNumber(lex, format) {
  const [thousands, decimal] = format === "1.234,56" ? [".", ","] : [",", "."];
  const d = lex.digits;
  const parts = d.split(decimal);
  if (parts.length > 2) return null;
  const [int, frac = ""] = parts;
  if (frac.includes(thousands)) return null;
  if (int.includes(thousands) && !new RegExp(`^\\d{1,3}(\\${thousands}\\d{3})+$`).test(int)) return null;
  const n = Number(`${int.split(thousands).join("")}${frac ? `.${frac}` : ""}`);
  return Number.isFinite(n) ? lex.sign * n : null;
}

function resolveColumns(header, overrides, ds) {
  const normed = header.map(norm);
  const lower = header.map((h) => h.trim().toLowerCase());
  const cols = {};
  for (const key of [...DIMENSIONS, ...METRICS]) {
    const wanted = overrides?.[key];
    if (wanted !== undefined) {
      const w = wanted.trim().toLowerCase();
      let idx = lower.indexOf(w);
      if (idx < 0) idx = normed.indexOf(norm(w));
      if (idx < 0) throw new ToolError("invalid_input", `${ds.name}: column "${wanted}" not found (headers: ${header.slice(0, 30).join(", ").slice(0, 400)})`);
      cols[key] = idx;
      continue;
    }
    const idx = ALIASES[key].map((a) => normed.indexOf(a)).find((i) => i >= 0);
    if (idx !== undefined) cols[key] = idx;
  }
  // A header such as "Amount spent (USD)" declares the currency.
  const headerCurrency = {};
  for (const key of ["spend", "revenue"]) {
    if (cols[key] === undefined) continue;
    const m = /\(([A-Z]{3}|[$€£¥₹])\)/i.exec(header[cols[key]]);
    if (m) headerCurrency[key] = CODE_OF[m[1]] ?? m[1].toUpperCase();
  }
  return { cols, headerCurrency };
}

function resolveCurrency(markers, declared) {
  const set = new Set(markers);
  if (declared) set.add(declared.toUpperCase());
  const codes = [...set].filter((c) => c !== "$");
  const nonDollar = codes.filter((c) => !DOLLAR_CODES.has(c));
  if (codes.length > 1 || (set.has("$") && nonDollar.length)) {
    throw new ToolError("invalid_input", `Mixed currencies in the money columns (${[...set].sort().join(", ")}). Amounts in different currencies cannot be added; convert them first or analyse each currency in a separate call.`);
  }
  return codes[0] ?? (set.has("$") ? "$" : null);
}

function groupOf(rec, groupBy) {
  const week = rec.week ?? "(no date)";
  switch (groupBy) {
    case "campaign": return { label: rec.campaign, fields: { campaign: rec.campaign } };
    case "channel_campaign": return { label: `${rec.channel} / ${rec.campaign}`, fields: { channel: rec.channel, campaign: rec.campaign } };
    case "week": return { label: week, fields: { week } };
    case "channel_week": return { label: `${rec.channel} / ${week}`, fields: { channel: rec.channel, week } };
    default: return { label: rec.channel, fields: { channel: rec.channel } };
  }
}

function metricsOf(sum, present, totals) {
  const v = (k) => (present[k] ? sum[k] : null);
  const spend = v("spend") === null ? null : r2(sum.spend);
  const impressions = v("impressions") === null ? null : r4(sum.impressions);
  const clicks = v("clicks") === null ? null : r4(sum.clicks);
  const conversions = v("conversions") === null ? null : r4(sum.conversions);
  const revenue = v("revenue") === null ? null : r2(sum.revenue);
  const integerConv = conversions !== null && clicks !== null && Number.isInteger(conversions) && Number.isInteger(clicks) && conversions <= clicks;
  // Zero recorded spend usually means unpaid traffic or costs kept outside the export, so cost ratios
  // are n/a rather than a "free" 0.00 that would rank as the cheapest channel.
  const paid = spend !== null && spend > 0 ? spend : null;
  return {
    spend,
    impressions,
    clicks,
    conversions,
    revenue,
    ctr: div(clicks, impressions),
    cpc: div(paid, clicks),
    cpm: impressions !== null && paid !== null && impressions > 0 ? r4((paid / impressions) * 1000) : null,
    conversion_rate: div(conversions, clicks),
    conversion_rate_ci95: integerConv && clicks > 0 ? wilson(conversions, clicks) : null,
    cpa: div(paid, conversions),
    roas: div(revenue, spend),
    revenue_per_conversion: div(revenue, conversions),
    ...(totals ? { share_of_spend: div(spend, totals.spend), share_of_conversions: div(conversions, totals.conversions) } : {}),
  };
}

export function channelPerformance(input) {
  const groupBy = input.group_by ?? "channel";
  const minConv = input.min_conversions ?? 10;
  const blankMode = input.blank_numbers ?? "zero";
  const warnings = [];
  const datasets = [];
  const records = [];
  const markers = { spend: [], revenue: [] };
  const declared = input.currency ? input.currency.trim().toUpperCase() : null;
  const present = Object.fromEntries(METRICS.map((m) => [m, false]));
  const names = new Set();
  let totalRows = 0;
  const formatsUsed = new Set();
  for (const ds of input.data) {
    if (names.has(ds.name)) throw new ToolError("invalid_input", `Duplicate data name: ${ds.name}`);
    names.add(ds.name);
    const { header, rows, ragged } = parseCsv(ds.csv, { label: ds.name, maxRows: 200000 - totalRows });
    totalRows += rows.length;
    const { cols, headerCurrency } = resolveColumns(header, input.columns, ds);
    const metricCols = METRICS.filter((m) => cols[m] !== undefined);
    if (!metricCols.length) throw new ToolError("invalid_input", `${ds.name}: no metric columns found (tried spend/cost/amount_spent, impressions, clicks, conversions/results, revenue/conversion_value); set columns.`);
    for (const m of metricCols) present[m] = true;
    if ((groupBy === "week" || groupBy === "channel_week") && cols.date === undefined) throw new ToolError("invalid_input", `${ds.name}: group_by ${groupBy} needs a date column (tried ${ALIASES.date.join(", ")}); set columns.date.`);
    const channelFromName = cols.channel === undefined ? ds.name.replace(/\.(csv|tsv|txt)$/i, "") : null;
    if (channelFromName !== null && groupBy !== "campaign" && groupBy !== "week") warnings.push(`${ds.name}: no channel column, so its rows are labelled with the file name "${channelFromName}".`);
    for (const [k, c] of Object.entries(headerCurrency)) markers[k].push(c);

    // First pass: lex every metric cell so the decimal convention can be inferred for the whole file.
    const lexed = rows.map((r) => Object.fromEntries(metricCols.map((m) => [m, lexNumber(r[cols[m]])])));
    let format = input.number_format && input.number_format !== "auto" ? input.number_format : null;
    if (!format) {
      const inf = inferNumberFormat(lexed.flatMap((l) => Object.values(l)).filter((x) => x && !x.blank).map((x) => x.digits));
      if (!inf.format) throw new ToolError("invalid_input", `${ds.name}: numbers use both 1,234.56 and 1.234,56 styles (${inf.evidence.dot} vs ${inf.evidence.comma} cells); set number_format.`);
      format = inf.format;
      if (inf.inferred && lexed.some((l) => Object.values(l).some((x) => x && !x.blank && /^\d{1,3}(,\d{3})+$/.test(x.digits)))) warnings.push(`${ds.name}: values such as "1,234" were read with "," as the thousands separator; set number_format to "1.234,56" if your export uses decimal commas.`);
    }
    formatsUsed.add(format);
    const skipped = { blank: 0, total_row: 0, bad_number: 0, bad_date: 0, negative: 0 };
    const blankCells = Object.fromEntries(metricCols.map((m) => [m, 0]));
    let used = 0;
    rows.forEach((r, i) => {
      const dims = Object.fromEntries(DIMENSIONS.map((d) => [d, cols[d] !== undefined ? String(r[cols[d]] ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 200) : ""]));
      const l = lexed[i];
      if (Object.values(dims).every((x) => !x) && metricCols.every((m) => l[m]?.blank)) { skipped.blank++; return; }
      if (DIMENSIONS.some((d) => TOTAL.test(dims[d]))) { skipped.total_row++; return; }
      const vals = {};
      for (const m of metricCols) {
        const x = l[m];
        if (!x) { skipped.bad_number++; return; }
        if (x.blank) {
          if (blankMode === "skip_row") { skipped.bad_number++; return; }
          blankCells[m]++;
          vals[m] = 0;
          continue;
        }
        const n = toNumber(x, format);
        if (n === null) { skipped.bad_number++; return; }
        if (n < 0 && m !== "revenue") { skipped.negative++; return; }
        if (x.currency && (m === "spend" || m === "revenue")) markers[m].push(x.currency);
        vals[m] = n;
      }
      let week = null;
      let t = null;
      if (cols.date !== undefined) {
        const raw = dims.date.split(/\s+[-–]\s+/)[0]; // "2026-03-02 - 2026-03-08" ranges use their start date
        const ts = parseTimestamp(raw);
        if (!ts) {
          if (groupBy === "week" || groupBy === "channel_week") { skipped.bad_date++; return; }
        } else {
          t = ts.ms;
          week = isoWeekLabel(mondayOf(ts.ms));
        }
      }
      records.push({ channel: dims.channel || channelFromName || "(none)", campaign: dims.campaign || "(none)", week, t, vals });
      used++;
    });
    datasets.push({ name: ds.name, rows: rows.length, used, skipped, blank_cells: blankCells, number_format: format, columns: Object.fromEntries(Object.entries(cols).map(([k, i]) => [k, header[i]])) });
    const bad = Object.values(skipped).reduce((a, b) => a + b, 0) - skipped.blank;
    if (bad) warnings.push(`${ds.name}: skipped ${bad} of ${rows.length} rows (total/summary rows ${skipped.total_row}, unreadable numbers ${skipped.bad_number}, negative spend or counts ${skipped.negative}, unreadable dates ${skipped.bad_date}).`);
    const blanks = Object.entries(blankCells).filter(([, n]) => n);
    if (blanks.length) warnings.push(`${ds.name}: empty or "--" cells were counted as 0 (${blanks.map(([m, n]) => `${m} ${n}`).join(", ")}); set blank_numbers to "skip_row" to drop those rows instead.`);
    if (ragged) warnings.push(`${ds.name}: ${ragged} row(s) had a different number of fields than the header; missing fields were read as empty.`);
  }
  const currency = resolveCurrency([...markers.spend, ...markers.revenue], declared);
  if (!currency && (present.spend || present.revenue)) warnings.push("No currency symbol or code was found; money amounts are in whatever currency your export uses.");
  if (currency === "$") warnings.push('Amounts use "$" without a currency code; pass currency (e.g. "USD" or "CAD") to label them.');

  // Aggregate.
  const groups = new Map();
  const total = Object.fromEntries(METRICS.map((m) => [m, 0]));
  let tMin = null;
  let tMax = null;
  for (const rec of records) {
    const g = groupOf(rec, groupBy);
    // Labels are grouped case-insensitively ("Google Ads" = "google ads"); the first spelling seen is shown.
    const key = input.case_sensitive_labels ? g.label : g.label.toLowerCase();
    let acc = groups.get(key);
    if (!acc) groups.set(key, (acc = { group: g.label, fields: g.fields, rows: 0, sum: Object.fromEntries(METRICS.map((m) => [m, 0])) }));
    acc.rows++;
    for (const m of METRICS) if (rec.vals[m] !== undefined) { acc.sum[m] += rec.vals[m]; total[m] += rec.vals[m]; }
    if (rec.t !== null) { tMin = tMin === null ? rec.t : Math.min(tMin, rec.t); tMax = tMax === null ? rec.t : Math.max(tMax, rec.t); }
  }
  const totals = { rows: records.length, ...metricsOf(total, present, null) };
  const rows = [...groups.values()].map((g) => {
    const m = metricsOf(g.sum, present, totals);
    const confidence_notes = [];
    if (m.conversions !== null && m.conversions < minConv) confidence_notes.push(`Only ${m.conversions} conversion(s) (< ${minConv}); CPA and conversion rate are unstable.`);
    if (m.spend === 0 && (m.conversions ?? 0) > 0) confidence_notes.push("No spend recorded; CPC, CPM, CPA and ROAS are n/a (unpaid or organic traffic, or the cost is not in this export).");
    if (m.spend === 0 && !(m.conversions > 0)) confidence_notes.push("No spend and no conversions recorded.");
    return { group: g.group, ...g.fields, rows: g.rows, ...m, confidence: m.conversions !== null && m.conversions < minConv ? "low" : "ok", confidence_notes };
  });
  rows.sort((a, b) => (groupBy === "week" ? a.group.localeCompare(b.group) : (b.spend ?? 0) - (a.spend ?? 0) || (b.conversions ?? 0) - (a.conversions ?? 0) || a.group.localeCompare(b.group)));

  // Plain factual comparisons (no projections).
  const insights = [];
  const money = (x) => `${currency && currency !== "$" ? `${currency} ` : currency === "$" ? "$" : ""}${x.toFixed(2)}`;
  const reliable = rows.filter((r) => r.cpa !== null && r.conversions >= minConv);
  if (reliable.length >= 2) {
    const sorted = [...reliable].sort((a, b) => a.cpa - b.cpa || a.group.localeCompare(b.group));
    const lo = sorted[0];
    const hi = sorted[sorted.length - 1];
    insights.push(`Lowest cost per conversion: ${lo.group} at ${money(lo.cpa)} (${lo.conversions} conversions); highest: ${hi.group} at ${money(hi.cpa)} (${hi.conversions} conversions). Groups with fewer than ${minConv} conversions are not ranked.`);
  } else if (present.spend && present.conversions) insights.push(`Fewer than two groups have at least ${minConv} conversions and recorded spend, so cost per conversion is not ranked.`);
  for (const r of rows) {
    if (r.share_of_spend !== null && r.share_of_conversions !== null && r.share_of_spend - r.share_of_conversions >= 0.1) insights.push(`${r.group} took ${(r.share_of_spend * 100).toFixed(1)}% of spend but delivered ${(r.share_of_conversions * 100).toFixed(1)}% of conversions.`);
    if (r.roas !== null && r.roas < 1 && r.spend > 0) insights.push(`${r.group} recorded less revenue than spend (ROAS ${r.roas}).`);
  }
  if (present.revenue && present.spend) insights.push("ROAS uses the revenue column of your export as-is (platform-reported, usually attributed by that platform's own model); platforms can double count the same sale.");

  const notes = [];
  if (formatsUsed.size > 1) notes.push("Files used different number formats (1,234.56 and 1.234,56); each file was read with its own format.");
  if (!records.length) warnings.push("No usable rows: every row was skipped. Check the column names and number format.");
  return {
    group_by: groupBy,
    currency,
    rows,
    totals,
    insights,
    markdown_table: performanceTable(rows, totals, present, groupBy),
    data_quality: { datasets, rows_used: records.length, date_range: tMin === null ? null : { start: new Date(tMin).toISOString(), end: new Date(tMax).toISOString() } },
    definition: "Sums per group of the cells in your export. CTR = clicks / impressions; CPC = spend / clicks; CPM = spend / impressions x 1000; conversion rate = conversions / clicks (95% Wilson interval when counts are whole numbers); CPA = spend / conversions; ROAS = revenue / spend. A zero or missing denominator gives null (n/a).",
    notes,
    warnings,
  };
}

const fmtMoney = (x) => (x === null ? "n/a" : x.toFixed(2));
const fmtCount = (x) => (x === null ? "n/a" : Number.isInteger(x) ? String(x) : x.toFixed(2));
const fmtPct = (x) => (x === null ? "n/a" : `${(x * 100).toFixed(1)}%`);
const fmtRatio = (x) => (x === null ? "n/a" : x.toFixed(2));

export function performanceTable(rows, totals, present, groupBy) {
  const colsDef = [
    ["Spend", "spend", fmtMoney, present.spend],
    ["Impr.", "impressions", fmtCount, present.impressions],
    ["Clicks", "clicks", fmtCount, present.clicks],
    ["CTR", "ctr", fmtPct, present.clicks && present.impressions],
    ["CPC", "cpc", fmtMoney, present.spend && present.clicks],
    ["Conv.", "conversions", fmtCount, present.conversions],
    ["Conv. rate", "conversion_rate", fmtPct, present.conversions && present.clicks],
    ["CPA", "cpa", fmtMoney, present.spend && present.conversions],
    ["Revenue", "revenue", fmtMoney, present.revenue],
    ["ROAS", "roas", fmtRatio, present.revenue && present.spend],
    ["Share of spend", "share_of_spend", fmtPct, present.spend],
    ["Share of conv.", "share_of_conversions", fmtPct, present.conversions],
  ].filter((c) => c[3]);
  const head = [groupBy.replace(/_/g, " / "), ...colsDef.map((c) => c[0])];
  const line = (cells) => `| ${cells.join(" | ")} |`;
  const body = rows.map((r) => line([cell(r.group) + (r.confidence === "low" ? " (low conv.)" : ""), ...colsDef.map((c) => c[2](r[c[1]] ?? null))]));
  const share = (k) => ((k === "share_of_spend" ? totals.spend : totals.conversions) > 0 ? "100.0%" : "n/a");
  const tot = line(["Total", ...colsDef.map((c) => (c[1].startsWith("share_") ? share(c[1]) : c[2](totals[c[1]] ?? null)))]);
  return [line(head.map(cell)), line(head.map(() => "---")), ...body, tot].join("\n");
}

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).