Skip to content

fix: calculate content metrics across all opportunities - #700

Merged
gkhngyk merged 5 commits into
ansvisor:mainfrom
BharadwajKanneveti:fix/content-kpi-aggregates
Aug 12, 2026
Merged

gkhngyk merged 5 commits into
ansvisor:mainfrom
BharadwajKanneveti:fix/content-kpi-aggregates

Conversation

@BharadwajKanneveti

@BharadwajKanneveti BharadwajKanneveti commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix content opportunity KPIs being calculated only from the current paginated page.

The High Impact, Avg. Score, and Sent metrics are now calculated server-side across the entire filtered dataset, while pagination continues to apply only to the opportunity list. This keeps KPI values consistent when navigating between pages.

Related issue

Closes #662

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

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

@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 — moving the KPIs server-side is the right call, and keeping the filter builder in one applyFilters helper is clean. One blocking problem before this can go in.

Blocking: PostgREST aggregate functions are not enabled

avgScoreQuery uses select('opportunity_score.avg()'). Aggregate functions in select are a PostgREST feature that is off unless db-aggregates-enabled is turned on, and it is off on our deployment. Verified against the live REST endpoint:

GET /rest/v1/content_opportunities?select=opportunity_score.avg()
400 {"code":"PGRST123","message":"Use of aggregate functions is not allowed"}

Because avgError is rethrown, this doesn't just zero the KPI — the whole GET /api/content/brand/:brandId returns 500, so the Content page stops loading entirely. It can't be caught in review by CI since nothing exercises the route against a real PostgREST.

Suggested fix: compute the three aggregates in a single Postgres function and call it with supabaseAdmin.rpc(...). That also collapses the current four round-trips into two — the list plus one aggregate call — which matters here because the aggregates re-scan the filtered set on every page change. Something like:

create function content_opportunity_aggregates(
  p_brand_id uuid, p_status text, p_impact text, p_type text, p_q text
) returns table (avg_score numeric, high_impact_count bigint, sent_count bigint)

with the same filter semantics as applyFilters, added as a numbered migration under supabase/migrations/.

If you'd rather keep it in JS, the two head: true counts are fine as they are — only the average needs another route.

Non-blocking

  • setAggregates(data.aggregates) trusts the field to exist. A server that hasn't been redeployed yet returns no aggregates, and the KPI cards then read .avgScore off undefined and crash the page. Worth defaulting: setAggregates(data.aggregates ?? { avgScore: 0, highImpactCount: 0, sentCount: 0 }).
  • highImpactQuery is built even when impact is set to something other than high, and then never awaited. It's harmless (the builder only runs when awaited), but building it inside the if would make the intent obvious.
  • The diff reformats the untouched .order(...) calls onto three lines each and drops the blank line before the next route handler. Reverting that noise would make the real change much easier to read.

Semantics all look right otherwise: status + .in('status', [...]) correctly yields 0 when the user filters to a non-sent status, and impact=high doesn't double-apply the filter.

@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.

This is much better — the RPC is clean, SECURITY INVOKER with a grant to authenticated is the right call (RLS on content_opportunities still applies to a direct caller), four round trips are down to two, and the data.aggregates ?? … fallback is in. I checked the aggregate logic against production data and it produces exactly what the issue describes: 766 opportunities for one brand, 372 high-impact, 100 sent — where the old page-scoped calculation could only ever count the 50 rows on screen.

One real fix left.

The search string diverges between the list and the KPIs

The data query sanitises q, the RPC does not:

// list
const search = String(q).replace(/[,()]/g, ' ');
filteredQuery.or(`title.ilike.%${search}%,description.ilike.%${search}%`);

// aggregates
p_q: q ? String(q) : null,

So for any query containing ,, ( or ) the two halves of the response describe different result sets — the list searches foo bar while the KPI cards search foo, bar. That is the exact class of mismatch this PR exists to remove, just moved from pagination to search.

The stripping is a PostgREST filter-syntax workaround and has no reason to apply to a bound function parameter, but the two must agree. Simplest is to compute it once and pass the same value to both:

const search = q ? String(q).replace(/[,()]/g, ' ') : null;

then use search inside applyFilters and as p_q. That keeps today's list behaviour unchanged and makes the aggregates match it exactly.

Two notes, neither blocking

  • Migration number collision. #703 also adds a 00050_…. Whichever merges second needs renumbering to 00051 and a bash supabase/build-schema.sh re-run. Nothing wrong on your side — just so it isn't a surprise.
  • The migration file has no trailing newline. build-schema.sh compensates so schema.sql is still valid, but it makes the generated file's spacing inconsistent with every other block.

Ping me once the search value is shared and I'll take another look.

@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.

Both points addressed exactly — search is computed once and feeds applyFilters and p_q, so the list and the KPI cards can no longer describe different result sets, and the migration ends with a newline. CI is green across all jobs.

Approving. Thanks for the quick turnaround on both rounds — the RPC version is a better piece of code than what the issue asked for.

One thing to expect on merge, not a change request: #703 also adds a 00050_… migration. Whichever lands second gets renumbered to 00051 with a bash supabase/build-schema.sh re-run. I'll handle it on my side if this merges first.

@gkhngyk
gkhngyk merged commit 6c7ba4b into ansvisor:main Aug 12, 2026
3 checks passed
gkhngyk added a commit that referenced this pull request Aug 18, 2026
…ot forgotten (#736)

* ci: flag pull requests that change a migration so the apply step is not forgotten

A migration file is only half of a migration. The other half — applying it to
the hosted database — is a manual step after merge, and nothing carried that
reminder across a merge someone else authored. It has been missed twice: #709
left prompt_suggestions absent from every fresh install, and 00050 merged with
#700 without being applied, so content_opportunity_aggregates did not exist and
the Content page failed for all fifty brands holding 7,561 opportunities. Both
were contributor pull requests, and both surfaced as a customer-visible error
rather than as something we caught.

A PR touching supabase/migrations/ is now labelled needs-migration. A label
rather than a failing check: a hard failure would block a PR for something that
is not wrong with the code, and a bare annotation scrolls away — which is
exactly how this was missed. The label shows in the PR list, survives on the
merged PR, and stays searchable afterwards.

The workflow runs on pull_request_target because both incidents came from forks
and labelling needs write permission there. It never checks out or executes the
PR's branch; the file list comes from the API, so an untrusted branch has
nothing to influence. Editing a migration counts as much as adding one, and
dropping the last migration from a branch clears the label again, so it always
means "this still needs applying".

check-drift.sh is the second net: it reads the repo and prints a read-only
query reporting anything the code expects and a database lacks. No credentials
and no connection, so it is safe to run against production and works for
self-hosters. The strongest of its three checks is the last — every .rpc() the
application actually calls resolves to a function that exists — because it
verifies what users hit rather than what the migrations declare. Run against
the hosted database it reports no drift across 19 functions, 43 tables and 14
called RPCs; seeded with names that do not exist, it reports all three.

Closes #728

* ci: let the guard create its label, and never fail a PR over that step

Labels on a pull request go through the issues API, and creating a repo label
needs `issues: write` — `pull-requests: write` attaches an existing label but
cannot create a missing one. Without the extra scope the first PR to touch a
migration in a fork of this repo would 403 on setup.

The failure is also no longer thrown. Attaching the label is the job; failing
the run over the step that creates it would put a red mark on a PR while
telling nobody anything useful. The status is logged instead, and 422 (already
exists) stops being a special case since it is the normal path from the second
run onward.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Content: KPI cards mix page-scoped stats with the brand-wide total

2 participants