Skip to content

feat(insights): add CSV export button on the Answer Engine Insights page header #38

Closed

Description

@gkhngyk

What

Add a Export CSV button to the top-right of the Answer Engine
Insights page header, next to the existing action buttons. Clicking it
downloads the currently-filtered prompt results as a CSV file the user
can open in Excel / Google Sheets / a BI tool.

This is the first of several export endpoints we're rolling out — start
with this one. Citations / AI Traffic / etc. will come as separate
issues.

Why

Marketers and analysts regularly want to pivot, filter, or chart the
raw result data outside the dashboard. Right now their only option is
to take screenshots or read individual rows in the UI. A one-click CSV
export turns "I want to play with this data" into a 5-second
operation.

Where the button goes

The header lives at:

  • web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
    around line 1714 — the <div className="flex items-start justify-between gap-4"> wrapping the title + action buttons.

Two things to handle:

  1. The right-side action cluster currently renders only when
    !isCloud
    (line 1723). Move it (or duplicate the wrapping div)
    so the Export button is always visible while Test Single
    Prompt / Run All stay self-host-only.
  2. The button itself uses the existing Button component from
    @/components/ui/button, variant="outline", with a Download icon
    from lucide-react (import { Download } from "lucide-react";).
    Match the style of the other buttons in that cluster.

What to export

The page already loads PromptResultWithText[] into the results
state (look for getPromptResults in page.tsx). Export exactly
what's currently loaded
— that means the active filters
automatically apply
(date range, model, region, topic) because the
data was already fetched with those filters.

Each row in the CSV should have these columns (flattened):

Column Source
created_at r.createdAt (ISO string)
prompt r.promptText
topic r.topicName ?? ""
platform r.platform
model r.modelUsed ?? ""
region r.region ?? ""
mention_count r.mentionCount
citation_count r.citationCount
visibility_score r.visibilityScore
sentiment r.sentiment
citation_urls `r.citations.map(c => c.url).join("
competitor_mentions r.competitorMentions?.map(c => \${c.name}:${c.mention_count}`).join("

Do not include the full response text — it's long, often
multi-paragraph, and breaks CSV parsers. Citations and competitor
mentions get flattened to pipe-separated strings (CSV-safe).

CSV building

A tiny helper is enough — no library needed. Create something like
web/src/lib/csv.ts:

function escape(value: unknown): string {
  if (value === null || value === undefined) return "";
  const s = String(value);
  // Wrap in quotes if it contains comma, quote, or newline.
  if (/[",\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
  return s;
}

export function toCsv(rows: Record<string, unknown>[], headers: string[]): string {
  const headerLine = headers.join(",");
  const dataLines = rows.map((row) =>
    headers.map((h) => escape(row[h])).join(","),
  );
  return [headerLine, ...dataLines].join("\n");
}

In the page, when the button is clicked, build the rows in the
shape above and trigger a download:

const csv = toCsv(rowsForExport, headerArray);
const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `ansvisor_${brand.slug}_results_${new Date().toISOString().slice(0, 10)}.csv`;
a.click();
URL.revokeObjectURL(url);

File naming convention: ansvisor_<brand-slug>_results_<YYYY-MM-DD>.csv.

Disabled state

The button should be disabled when:

  • results.length === 0 (nothing to export)
  • The page is still loading (isLoading === true)

Show a subtle tooltip on hover when disabled — something like "No
results in the current filter — adjust filters or run a tracking
job"
.

How to verify

  • Navigate to /dashboard/insights with a brand that has tracked
    results → Export button is visible top-right
  • Click → file downloads with the correct name pattern
  • Open the CSV in Excel / Google Sheets → columns line up, no
    extra quotes, no broken rows
  • Apply a date filter (e.g. last 7 days) → re-export → file only
    contains rows within that range
  • Same for region / model filters
  • Brand with zero results → button is disabled with tooltip
  • Cloud and self-host modes both show the button (only Test
    Single Prompt / Run All stay self-host-only)

Out of scope

Don't include in this PR:

  • Excel format (CSV only for now)
  • Async / background export
  • Other datasets (Citations, AI Traffic, etc. — coming as separate
    issues)
  • Plan gating / rate limiting (cap is handled implicitly by the
    existing PROMPT_RESULTS_ROW_LIMIT)
  • Adding the helper to MCP / REST API

Contribution guide

See CONTRIBUTING.md for branch naming, commit
conventions, and PR workflow.

Activity

  1. added
    enhancement
    good first issue
    help wanted
    on May 18, 2026
  2. gkhngyk commented on May 21, 2026

    @gkhngyk
    ContributorAuthor

    @sourabh-31 Would you like to work on this issue?

  3. sourabh-31 commented on May 21, 2026

    @sourabh-31
    Contributor

    @sourabh-31 Would you like to work on this issue?

    Hey @gkhngyk, I started looking into this issue, but I’m currently hitting a blocker on the Insights page.

    Right now the page is showing the empty state (“No tracking data yet”), and when I click “Run Prompt Now”, it finishes with “analysis complete - 0 results saved”. Because of that, I don’t have any prompt result data available to test/export against.

    Am I missing a setup step or seed data for this flow? Would appreciate some guidance on how to get actual results populated so I can work on the CSV export properly.

  4. gkhngyk commented on May 21, 2026

    @gkhngyk
    ContributorAuthor

    Hey @sourabh-31 — quick note before the answer: this is a real gap in our contributor setup, not something you did wrong. The fact that you can't just pnpm dev and see a populated dashboard is friction on us, and we're sorry it slowed you down. Seed data is something we're actively working on (going to open a separate issue for it shortly so it's tracked publicly).

    Now to your specific question — a few things to clear up:

    The cloud trial doesn't help here

    The trial you start on app.ansvisor.com lives in our production Supabase, which is a completely separate database from the one your local instance points to. Auth, organizations, subscriptions, brands, prompt results — none of it is shared. So there's no way (and you wouldn't want) to bridge them.

    You don't actually need a subscription locally

    When IS_CLOUD is unset (the default for self-host / local dev), the plan resolver returns the unlimited self_hosted plan and skips the subscription check entirely. So plan gating is not what's blocking you.

    Why "Run Prompt Now" returns 0 results

    The tracking pipeline needs:

    • OPENAI_API_KEY / ANTHROPIC_API_KEY / GOOGLE_GENERATIVE_AI_API_KEY in server/.env for the direct-API providers
    • CLORO_API_KEY + CLORO_WEBHOOK_URL for the scraper-backed providers (ChatGPT / Claude / Perplexity / Gemini web UIs)

    Cloro is a paid third-party service, which is exactly the kind of thing a contributor shouldn't have to sign up for to ship a UI feature. This is the gap I mentioned above.

    Unblocker for this PR specifically

    For the CSV export you actually don't need real tracked data — you just need some rows in prompt_results to drive the UI. The fastest path: open Supabase Studio against your local instance and insert ~10 rows directly into prompt_results with realistic values (you can crib the column shape from web/src/lib/actions/insights.ts — look for PromptResultWithText). That's enough to iterate on the button, the disabled state, the CSV output, and the file naming.

    Once seed data lands you'll be able to skip that step entirely. In the meantime, sorry for the extra mile. Ping back when you've got a draft and I'll review.

  5. sourabh-31 commented on May 21, 2026

    @sourabh-31
    Contributor

    @gkhngyk a PR has been created regarding this feature. Kindly take a look at it when you get time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementgood first issuehelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions