Skip to content

feat(insights): show the KPI cards in two rows, as in the v2 mockup - #1037

Merged
gkhngyk merged 9 commits into
ansvisor:mainfrom
cihan-gyk:feature/insights-kpi-cards
Oct 16, 2026
Merged

gkhngyk merged 9 commits into
ansvisor:mainfrom
cihan-gyk:feature/insights-kpi-cards

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Stacked on #1036 (VIS-002), which is stacked on #1035 (VIS-001). Until those merge, this PR also shows their commits. The VIS-003 change is the last commit, d84a9b8.

Summary

The Insights KPI row becomes the v2 mockup's two rows. This is VIS-003 in the Visibility spec v2.

Row 1: today's cards

Card Value Context line
Visibility score + change "#1 of 4 brands", the brand's rank on the leaderboard
Tracked prompts prompts answered + new prompts (grey) "422 slots left · all brands" and a plan-quota bar: amber from 80%, red when full
Mentions / Citations compact totals + % change "same N prompts" with Same prompts on
Net sentiment positive % − negative %, replaces Positive sentiment "48% pos · 14% neg"

Row 2: new rates

Card Definition
Coverage prompts you appeared in ÷ prompts answered
Share of voice your mentions ÷ all tracked brands' mentions (same rule as share_of_voice_aggregates)
Avg. position mean position when named; lower is better, so a drop shows as a green "↑"
Citation rate answers citing your domain ÷ all answers

Every card has its value, a change coloured by whether it's good news, a context line and a daily sparkline. The sparkline turns red when the change is bad.

Changes follow Compare: Same prompts (#1036): with the switch on, every card's change is measured on the prompts answered in both periods. All time shows no change on any card. Before this, Mentions, Citations, Sentiment and SoV quietly compared the last 7 days there; getInsightsSummary keeps that rule for its other caller, the topic page.

The Formulas dialog now defines every card. It also adds the Visibility confidence factor, mentions ÷ (mentions + 20), which the formula box used to leave out.

Layout: 5 + 4 cards from 1280px, as in the mockup, then 3 + 2 and 4 below that, so labels don't wrap at 1024px. The cards live in insights/_kpi-cards.tsx. Their formatting rules are in kpi-format.ts and the rate math is in lib/insights-kpis.ts, shared by the values, the changes and the sparklines.

Deliberate differences from the mockup:

  • Net sentiment isn't clickable. The mockup opens Mentions, but there is no Mentions page yet; that is the separate "Mentions & Sentiment" task list.
  • The Tracked prompts "Upgrade" link is gone, because the mockup doesn't have it. The bar turns red at the limit, and the card still opens Prompts, which has the upgrade options.

InsightsData.visibilityRate is dropped: the Coverage card reads the same counts. getVisibilityRateKpi stays for Reports.

Data

Net sentiment needs negative counts and Avg. position needs a position sum. The rollups had neither; they only had the 1/position sum behind the Visibility score. Migration 00131:

  • adds negative_count and sum_position to insights_brand_daily and insights_prompt_daily, nullable like 00130, and writes them in refresh_insights_daily;
  • returns citation_answers, negative_count, sum_position, position_count and kpi_complete from insights_aggregates and insights_aggregates_daily;
  • extends insights_same_prompt_compare[_daily] (00130) with the same components, the shared prompts that appeared, and competitor mentions for share of voice;
  • adds insights_kpi_series: one row of components per day from the prompt-grain rollups, with the topic filter included, for the sparklines.

Deploy: run 00130 and 00131 together; this PR's functions replace 00130's. Then run the backfill once; it covers both:

cd server && node src/scripts/backfill-insights-daily.js

Until a day is refreshed, Net sentiment and Avg. position show "No data", and the sparklines are hidden. If the migration hasn't run at all, the new fields are missing, and the cards read that as empty rather than as 0.

Review

I ran a code review before opening this. It found 7 things and 4 are fixed:

  • missing 00131 fields were read as real zeros;
  • All time showed a hidden 7-day change on some cards;
  • a Net sentiment of 0 rendered as "±0";
  • the card formatting rules had no tests.

Left as notes:

  • Coverage reads the current window's tracked-prompt count again; Tracked prompts reads it live and outside the 24h cache.
  • The ⓘ icon sits inside a clickable card, as on the old cards.
  • 00130 and 00131 must ship together (see Deploy).

Related issue

None. Product spec: Visibility spec v2, task VIS-003. Depends on #1036 and #1035.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply 00129, 00130 and 00131, then refill the rollups (backfill script, or refresh_insights_daily per brand).
  2. Open Insights with 30d at 1280px or wider. You get two rows: 5 cards, then 4, each with a change and a sparkline.
  3. Check the values against the rest of the page:
    • Visibility and its rank match the Leaderboard.
    • Coverage matches the Tracked prompts count.
    • Mentions and Citations match the breakdown panel.
  4. Turn Same prompts off and on. Every card's change moves, and the values don't.
  5. Select All. No card shows a change.
  6. Narrow the window to 1024px. The cards show 3 + 2, then 4, and no label wraps.
  7. Open Formulas. Every card is defined, and the Visibility formula shows the confidence factor.
  8. Check light and dark mode.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): 0 errors; the 7 warnings are in code this PR doesn't touch
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run:

  • yarn test: 568/568. New tests are insights-kpis.test.ts, kpi-format.test.ts, the KPI-rate and missing-fields cases in tracking.test.ts, and the KPI changes in insights-same-prompts.test.ts.
  • yarn build: passed.
  • bash supabase/build-schema.sh: schema.sql is up to date.
  • The migration is applied and the rollups are refilled on a dev database. The rollup and raw versions of the extended same-prompt functions return the same values. I checked in the browser at 1440px and 1024px, in light and dark mode, and with All time and Same prompts on/off. The demo data has no positions, so Avg. position shows "No data" there.

🤖 Generated with Claude Code

cihan-gyk and others added 2 commits October 14, 2026 17:51
Adding prompts inflated every change on the Insights page: 509 new prompts
read as +203% mentions, and the breakdown counted each new prompt as a
gain from 0 (VIS-002).

A "Compare: Same prompts" switch in the filter bar, on by default and kept
in the URL (?compare=all when off), measures every change only on the
prompts answered in both periods: the Visibility change, every leaderboard
row, Mentions, Citations, Sentiment and the breakdown panel. The numbers
themselves still cover every prompt. The trend card says how many new
prompts were left out (or included, with the switch off).

The per-prompt components come from the daily rollups: migration 00130
adds them to insights_prompt_daily and insights_competitor_prompt_daily,
writes them in refresh_insights_daily, and adds
insights_same_prompt_compare[_daily]. The new columns read NULL until a
day is refreshed; such a comparison is reported incomplete and the page
compares all prompts, so the history needs one backfill run after deploy
(server/src/scripts/backfill-insights-daily.js).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The KPI row becomes the mockup's two rows (VIS-003): today's cards on the
first (Visibility with the brand's rank, Tracked prompts with the plan's
slots left, Mentions, Citations, and Net sentiment in place of Positive
sentiment), and the new rates on the second (Coverage, Share of voice,
Avg. position, Citation rate). Each card has its value, a change coloured
by whether it's good news, a line of context and a daily sparkline. Every
change follows "Compare: Same prompts", and All time shows none. The
Formulas dialog defines each metric and gains the Visibility confidence
factor.

Migration 00131 adds the negative count and the position sum to the brand
and prompt rollups, returns the new components from insights_aggregates
and the same-prompt functions, and adds insights_kpi_series for the
sparklines. Until the history is backfilled
(server/src/scripts/backfill-insights-daily.js), Net sentiment and
Avg. position show no value rather than a partial one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk this is ready for review. It's VIS-003 from the Visibility spec v2, stacked on #1036 → #1035. Until those merge, the VIS-003 change is the last commit.

It turns the Insights KPI row into the v2 mockup's two rows: Visibility, Tracked prompts (with plan slots), Mentions, Citations and Net sentiment, then Coverage, Share of voice, Avg. position and Citation rate. Every card has a change that follows "Compare: Same prompts", and a sparkline.

Things to look at:

  • Migration 00131 adds negative counts and position sums to the brand and prompt rollups, extends insights_aggregates[_daily] and the 00130 same-prompt functions, and adds insights_kpi_series for the sparklines. Ship it together with 00130, then run backfill-insights-daily.js once.
  • All time now shows no change on any card. getInsightsSummary keeps its 7-day rule for the topic page.
  • Two deliberate gaps vs the mockup: Net sentiment doesn't link anywhere because there's no Mentions page yet, and the Tracked prompts "Upgrade" link is gone because the mockup doesn't have it.

Code review, yarn test (568/568), lint, typecheck and build pass. I checked it on a backfilled dev database at 1440px and 1024px, in light and dark mode.

cihan-gyk and others added 5 commits October 15, 2026 19:53
…i-cards

# Conflicts:
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
…bers

insights_same_prompt_compare_daily timed out on the largest brand: 4.5 s
as the owner, over 30 s for an org member against the 8 s timeout. A SQL
function is planned without its argument values on PostgreSQL 17, and RLS
ran inside the scan.

00147 makes both same-prompt RPCs plpgsql with force_custom_plan and
security definer with an explicit org-membership check (as 00119). The
service role still reads, for the cached 24h view. Rollup rows are folded
per prompt and window first. Output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
getSamePromptComparison returned null on an RPC error, so strict mode
cached the all-prompt changes until the next tracking run. It now throws:
loadWindowedInsights wraps it in lenient(), and the breakdown panel
catches it and compares all prompts, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
00147 (ansvisor#1036) makes insights_same_prompt_compare[_daily] fast but carries
00130's output. Migrations run in number order, so it would replace
00131's version here and drop the fields the KPI cards read (negative
count, position sum and count, visible prompts, competitor mentions).

00149 is 00131's output in 00147's shape: plpgsql with force_custom_plan,
security definer with the org-membership check, rows folded per prompt
and window first. Output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@gkhngyk

gkhngyk commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

@cihan-gyk #1036 is squash-merged, so this branch and the PRs stacked on it now conflict with main. Please merge main into #1037 and carry it up the stack (#1038 → … → #1049).

  • The conflicts come from feat(insights): compare changes on the same prompts by default #1036's two fix commits (68b41fa, 9fec1c7), which this branch doesn't have yet. In feat(insights): compare changes on the same prompts by default #1036's files (insights-same-prompts.ts and its test, tracking.ts, the parity test, insights/page.tsx, en.json, types/supabase.ts), keep main's side and add this PR's own changes on top.
  • Re-run bash supabase/build-schema.sh afterwards.
  • 00147, 00148 and 00149 are already applied to production, next to 00129–00133 and 00135. If 00148 or 00149 change while you rebase, say so on the PR so we re-apply them before merge.
  • 00136, 00137 and 00138 aren't applied yet. We'll apply each one before its PR merges.

…nto feature/insights-kpi-cards

# Conflicts:
#	supabase/schema.sql
#	web/src/lib/actions/tracking.ts
…i-cards

# Conflicts:
#	supabase/schema.sql
#	web/messages/en.json
#	web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
#	web/src/lib/actions/tracking-visibility-parity.test.ts
#	web/src/lib/actions/tracking.ts
#	web/src/lib/insights-same-prompts.test.ts
#	web/src/lib/insights-same-prompts.ts
#	web/src/types/supabase.ts

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the restack is clean. Checked:

  • Against main, the diff is only this PR's work: the KPI cards, 00131 and 00149. Both migrations match what is applied in production, so nothing needs re-applying.
  • On the merged tree, schema.sql matches build-schema.sh and web tests pass (671). CI is green.
  • Timed on production as a signed-in member of the largest brand:
    • insights_kpi_series: 0.6 s for 90 days, 1.0 s for the largest topic over 30 days.
    • insights_aggregates_daily: 30 days in 26 ms.
    • Coverage's visible_prompt_stats_daily + tracked_prompt_count_daily: 0.17 s.
    • The 00149 same-prompt RPCs: 1.4 s for 30 days.
  • The cards' values, changes and sparklines share kpiRates, and Same prompts now covers every card's change.

One note, not blocking: on topic views, Coverage reads raw visible_prompt_stats + tracked_prompt_count for both windows. For one window on the largest topic the two calls together took 5.7 s, under the limit but heavy. It's the same raw path the old card used, so it will speed up with #867.

@gkhngyk
gkhngyk merged commit 5c10f7a into ansvisor:main Oct 16, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants