Repository navigation
fix: calculate content metrics across all opportunities - #700
Conversation
gkhngyk
left a comment
There was a problem hiding this comment.
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 noaggregates, and the KPI cards then read.avgScoreoffundefinedand crash the page. Worth defaulting:setAggregates(data.aggregates ?? { avgScore: 0, highImpactCount: 0, sentCount: 0 }).highImpactQueryis built even whenimpactis set to something other thanhigh, and then never awaited. It's harmless (the builder only runs when awaited), but building it inside theifwould 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
left a comment
There was a problem hiding this comment.
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 to00051and abash supabase/build-schema.shre-run. Nothing wrong on your side — just so it isn't a surprise. - The migration file has no trailing newline.
build-schema.shcompensates soschema.sqlis 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
left a comment
There was a problem hiding this comment.
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.
…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.
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 featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsChecklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/)yarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)