diff --git a/backend/README.md b/backend/README.md index 1df804b..dc8b43c 100644 --- a/backend/README.md +++ b/backend/README.md @@ -14,7 +14,8 @@ Production-ready Node.js (Express) & Supabase (PostgreSQL) backend API for the H 6. For an existing database, run `migrations/20261128_add_membership_interest.sql` in the Supabase SQL Editor to add the optional membership-interest field without changing existing submissions. 7. Before deploying the session-revocation update, run `migrations/20261129_add_session_version.sql` in the Supabase SQL Editor. 8. Before deploying the database-access update, run `migrations/20261129_lock_down_supabase_rls.sql`. -9. In **Project Settings** > **API**: +9. Before deploying the dashboard-metrics update, run `migrations/20261130_add_dashboard_metrics.sql`. +10. In **Project Settings** > **API**: - Copy your **Project URL** (`SUPABASE_URL`) - Copy your **service_role** secret (`SUPABASE_SERVICE_ROLE_KEY`) - Keep the service-role secret private; it bypasses database row-level security. @@ -104,6 +105,10 @@ WHERE schemaname = 'public' The query should return no rows. Then use only the public anon key from a non-privileged client to attempt a direct read and insert against `first_timers`; both should be denied. Confirm public intake still succeeds through `POST /api/first-timers`. +### Dashboard metrics + +The dashboard metrics endpoint aggregates totals, follow-up counts, and discovery sources in PostgreSQL, avoiding the submissions endpoint's page size and REST row limit. The daily count uses the `Africa/Lagos` calendar day, from local midnight up to (but excluding) the following local midnight. Apply `migrations/20261130_add_dashboard_metrics.sql` to existing databases before deploying the backend. If the endpoint is unavailable, the dashboard displays an explicit unavailable state instead of presenting partial totals. + --- ## 4. API Endpoints Reference diff --git a/backend/migrations/20261130_add_dashboard_metrics.sql b/backend/migrations/20261130_add_dashboard_metrics.sql new file mode 100644 index 0000000..46d3ead --- /dev/null +++ b/backend/migrations/20261130_add_dashboard_metrics.sql @@ -0,0 +1,65 @@ +CREATE OR REPLACE FUNCTION public.get_dashboard_metrics(p_as_of TIMESTAMPTZ) +RETURNS JSONB +LANGUAGE SQL +STABLE +SECURITY INVOKER +SET search_path = '' +AS $function$ + WITH local_day AS ( + SELECT (p_as_of AT TIME ZONE 'Africa/Lagos')::DATE AS local_date + ), + day_bounds AS ( + SELECT + local_date::TIMESTAMP AT TIME ZONE 'Africa/Lagos' AS start_at, + (local_date + 1)::TIMESTAMP AT TIME ZONE 'Africa/Lagos' AS end_at + FROM local_day + ), + totals AS ( + SELECT + COUNT(*) AS total_submissions, + COUNT(*) FILTER ( + WHERE first_timers.created_at >= day_bounds.start_at + AND first_timers.created_at < day_bounds.end_at + ) AS daily_submissions, + COUNT(*) FILTER ( + WHERE first_timers.follow_up_status <> 'pending' + ) AS followed_up + FROM public.first_timers + CROSS JOIN day_bounds + ), + source_counts AS ( + SELECT + COALESCE(how_did_you_hear, 'Not Specified') AS source, + COUNT(*) AS source_count + FROM public.first_timers + GROUP BY 1 + ), + source_totals AS ( + SELECT + COALESCE( + jsonb_object_agg(source, source_count), + '{}'::JSONB + ) AS discovery_sources_breakdown, + COALESCE( + (array_agg(source ORDER BY source_count DESC, source))[1], + 'None' + ) AS top_discovery_source, + COALESCE(MAX(source_count), 0) AS top_discovery_count + FROM source_counts + ) + SELECT jsonb_build_object( + 'totalSubmissions', totals.total_submissions, + 'dailySubmissions', totals.daily_submissions, + 'followedUp', totals.followed_up, + 'topDiscoverySource', source_totals.top_discovery_source, + 'topDiscoveryCount', source_totals.top_discovery_count, + 'discoverySourcesBreakdown', source_totals.discovery_sources_breakdown + ) + FROM totals + CROSS JOIN source_totals; +$function$; + +REVOKE ALL ON FUNCTION public.get_dashboard_metrics(TIMESTAMPTZ) +FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.get_dashboard_metrics(TIMESTAMPTZ) +TO service_role; diff --git a/backend/schema.sql b/backend/schema.sql index f9aafe1..6c213de 100644 --- a/backend/schema.sql +++ b/backend/schema.sql @@ -168,3 +168,69 @@ END $$; REVOKE ALL ON TABLE first_timers, users, follow_up_notes FROM anon, authenticated; GRANT ALL ON TABLE first_timers, users, follow_up_notes TO service_role; + +CREATE OR REPLACE FUNCTION public.get_dashboard_metrics(p_as_of TIMESTAMPTZ) +RETURNS JSONB +LANGUAGE SQL +STABLE +SECURITY INVOKER +SET search_path = '' +AS $function$ + WITH local_day AS ( + SELECT (p_as_of AT TIME ZONE 'Africa/Lagos')::DATE AS local_date + ), + day_bounds AS ( + SELECT + local_date::TIMESTAMP AT TIME ZONE 'Africa/Lagos' AS start_at, + (local_date + 1)::TIMESTAMP AT TIME ZONE 'Africa/Lagos' AS end_at + FROM local_day + ), + totals AS ( + SELECT + COUNT(*) AS total_submissions, + COUNT(*) FILTER ( + WHERE first_timers.created_at >= day_bounds.start_at + AND first_timers.created_at < day_bounds.end_at + ) AS daily_submissions, + COUNT(*) FILTER ( + WHERE first_timers.follow_up_status <> 'pending' + ) AS followed_up + FROM public.first_timers + CROSS JOIN day_bounds + ), + source_counts AS ( + SELECT + COALESCE(how_did_you_hear, 'Not Specified') AS source, + COUNT(*) AS source_count + FROM public.first_timers + GROUP BY 1 + ), + source_totals AS ( + SELECT + COALESCE( + jsonb_object_agg(source, source_count), + '{}'::JSONB + ) AS discovery_sources_breakdown, + COALESCE( + (array_agg(source ORDER BY source_count DESC, source))[1], + 'None' + ) AS top_discovery_source, + COALESCE(MAX(source_count), 0) AS top_discovery_count + FROM source_counts + ) + SELECT jsonb_build_object( + 'totalSubmissions', totals.total_submissions, + 'dailySubmissions', totals.daily_submissions, + 'followedUp', totals.followed_up, + 'topDiscoverySource', source_totals.top_discovery_source, + 'topDiscoveryCount', source_totals.top_discovery_count, + 'discoverySourcesBreakdown', source_totals.discovery_sources_breakdown + ) + FROM totals + CROSS JOIN source_totals; +$function$; + +REVOKE ALL ON FUNCTION public.get_dashboard_metrics(TIMESTAMPTZ) +FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.get_dashboard_metrics(TIMESTAMPTZ) +TO service_role; diff --git a/backend/src/controllers/metricsController.js b/backend/src/controllers/metricsController.js index 3853713..fed950b 100644 --- a/backend/src/controllers/metricsController.js +++ b/backend/src/controllers/metricsController.js @@ -5,65 +5,18 @@ import { supabase } from "../config/supabase.js"; */ export const getDashboardMetrics = async (req, res, next) => { try { - // 1. Total Submissions Count - const { count: totalSubmissions, error: totalErr } = await supabase - .from("first_timers") - .select("*", { count: "exact", head: true }); - - if (totalErr) throw totalErr; - - // 2. Today's Submissions Count - const todayStart = new Date(); - todayStart.setHours(0, 0, 0, 0); - - const { count: dailySubmissions, error: dailyErr } = await supabase - .from("first_timers") - .select("*", { count: "exact", head: true }) - .gte("created_at", todayStart.toISOString()); - - if (dailyErr) throw dailyErr; - - // 3. Followed Up Count (where status is not 'pending') - const { count: followedUpCount, error: followUpErr } = await supabase - .from("first_timers") - .select("*", { count: "exact", head: true }) - .neq("follow_up_status", "pending"); - - if (followUpErr) throw followUpErr; - - // 4. Discovery Sources Breakdown & Top Source - const { data: sourcesData, error: sourcesErr } = await supabase - .from("first_timers") - .select("how_did_you_hear"); - - if (sourcesErr) throw sourcesErr; - - const sourceCounts = {}; - (sourcesData || []).forEach((row) => { - const source = row.how_did_you_hear || "Not Specified"; - sourceCounts[source] = (sourceCounts[source] || 0) + 1; + const { data, error } = await supabase.rpc("get_dashboard_metrics", { + p_as_of: new Date().toISOString(), }); - let topDiscoverySource = "None"; - let topDiscoveryCount = 0; - - Object.entries(sourceCounts).forEach(([source, count]) => { - if (count > topDiscoveryCount) { - topDiscoveryCount = count; - topDiscoverySource = source; - } - }); + if (error) throw error; + if (!data || typeof data !== "object" || Array.isArray(data)) { + throw new Error("Dashboard metrics query returned an invalid result."); + } return res.status(200).json({ success: true, - data: { - totalSubmissions: totalSubmissions || 0, - dailySubmissions: dailySubmissions || 0, - followedUp: followedUpCount || 0, - topDiscoverySource, - topDiscoveryCount, - discoverySourcesBreakdown: sourceCounts, - }, + data, }); } catch (error) { next(error); diff --git a/backend/tests/accessPolicy.test.js b/backend/tests/accessPolicy.test.js index 63aae26..555151c 100644 --- a/backend/tests/accessPolicy.test.js +++ b/backend/tests/accessPolicy.test.js @@ -46,6 +46,48 @@ const matches = (row, filters) => filters.every(({ field, operator, value }) => return true; }); +const getLagosDayBounds = (asOf) => { + const dateParts = Object.fromEntries( + new Intl.DateTimeFormat("en-US", { + timeZone: "Africa/Lagos", + year: "numeric", + month: "2-digit", + day: "2-digit", + }) + .formatToParts(new Date(asOf)) + .map(({ type, value }) => [type, value]) + ); + const start = Date.parse(`${dateParts.year}-${dateParts.month}-${dateParts.day}T00:00:00+01:00`); + return { start, end: start + 24 * 60 * 60 * 1000 }; +}; + +const aggregateMetrics = (rows, asOf) => { + const { start, end } = getLagosDayBounds(asOf); + const discoverySourcesBreakdown = {}; + + for (const row of rows) { + const source = row.how_did_you_hear || "Not Specified"; + discoverySourcesBreakdown[source] = (discoverySourcesBreakdown[source] || 0) + 1; + } + + const topDiscovery = Object.entries(discoverySourcesBreakdown) + .sort(([sourceA, countA], [sourceB, countB]) => countB - countA || sourceA.localeCompare(sourceB))[0]; + + return { + totalSubmissions: rows.length, + dailySubmissions: rows.filter((row) => { + const createdAt = new Date(row.created_at).getTime(); + return createdAt >= start && createdAt < end; + }).length, + followedUp: rows.filter((row) => row.follow_up_status !== "pending").length, + topDiscoverySource: topDiscovery?.[0] || "None", + topDiscoveryCount: topDiscovery?.[1] || 0, + discoverySourcesBreakdown, + }; +}; + +let metricsRowsFactory = null; +let metricsRpcError = null; const makeQuery = (table) => { let action = "select"; let values; @@ -151,10 +193,20 @@ const makeQuery = (table) => { let server; let baseUrl; let originalFrom; +let originalRpc; before(async () => { originalFrom = supabase.from; + originalRpc = supabase.rpc; supabase.from = (table) => makeQuery(table); + supabase.rpc = (functionName, parameters) => { + assert.equal(functionName, "get_dashboard_metrics"); + const rows = metricsRowsFactory ? metricsRowsFactory(parameters.p_as_of) : store.first_timers; + return Promise.resolve({ + data: metricsRpcError ? null : aggregateMetrics(rows, parameters.p_as_of), + error: metricsRpcError, + }); + }; server = express(); server.use(app); @@ -170,6 +222,7 @@ after(async () => { server.close((error) => error ? reject(error) : resolve()); }); supabase.from = originalFrom; + supabase.rpc = originalRpc; for (const [name, value] of Object.entries(originalEnv)) { if (value === undefined) { delete process.env[name]; @@ -331,14 +384,50 @@ test("pastors have oversight access while administrators retain account and expo }); await t.test("metrics return counts based on all submissions", async () => { - const response = await request("/metrics", { id: adminId }); - const payload = await response.json(); + metricsRowsFactory = (asOf) => { + const { start, end } = getLagosDayBounds(asOf); + return [ + { created_at: new Date(start - 1).toISOString(), follow_up_status: "pending", how_did_you_hear: "Poster" }, + { created_at: new Date(start).toISOString(), follow_up_status: "contacted", how_did_you_hear: "Friend" }, + { created_at: new Date(end - 1).toISOString(), follow_up_status: "integrated", how_did_you_hear: "Friend" }, + { created_at: new Date(end).toISOString(), follow_up_status: "pending", how_did_you_hear: "Poster" }, + ...Array.from({ length: 12 }, (_, index) => ({ + created_at: new Date(start + (index + 1) * 1000).toISOString(), + follow_up_status: index % 2 === 0 ? "contacted" : "pending", + how_did_you_hear: index < 8 ? "Friend" : null, + })), + ]; + }; + + let response; + let payload; + try { + response = await request("/metrics", { id: adminId }); + payload = await response.json(); + } finally { + metricsRowsFactory = null; + } assert.equal(response.status, 200); - assert.equal(payload.data.totalSubmissions, 3); - assert.equal(payload.data.followedUp, 2); - assert.equal(payload.data.topDiscoverySource, "Not Specified"); - assert.equal(payload.data.topDiscoveryCount, 3); + assert.equal(payload.data.totalSubmissions, 16); + assert.equal(payload.data.dailySubmissions, 14); + assert.equal(payload.data.followedUp, 8); + assert.equal(payload.data.topDiscoverySource, "Friend"); + assert.equal(payload.data.topDiscoveryCount, 10); + assert.equal(payload.data.discoverySourcesBreakdown["Not Specified"], 4); + }); + + await t.test("metrics database failures return an API error", async (t) => { + t.mock.method(console, "error", () => {}); + metricsRpcError = new Error("Metrics query failed."); + let response; + try { + response = await request("/metrics", { id: adminId }); + } finally { + metricsRpcError = null; + } + + assert.equal(response.status, 500); }); await t.test("administrators can export submissions", async () => { diff --git a/src/components/dashboard/MetricsCards.jsx b/src/components/dashboard/MetricsCards.jsx index 362cae6..1a2c137 100644 --- a/src/components/dashboard/MetricsCards.jsx +++ b/src/components/dashboard/MetricsCards.jsx @@ -3,59 +3,31 @@ import API from '../../api/axios'; import { FaFileImport, FaCalendarDay, FaUserCheck, FaShareNodes } from "react-icons/fa6"; const MetricsCards = () => { - const [metrics, setMetrics] = useState({ - totalSubmissions: 0, - dailySubmissions: 0, - followedUp: 0, - topDiscoverySource: "No data", - topDiscoveryCount: 0, - }); + const [metrics, setMetrics] = useState(null); const [loading, setLoading] = useState(true); + const [unavailable, setUnavailable] = useState(false); useEffect(() => { const fetchMetrics = async () => { - setLoading(true); try { - // Try dedicated metrics endpoint first const res = await API.get("/metrics"); - if (res.data?.data) { - setMetrics(res.data.data); - } - } catch (error) { - console.warn("Metrics endpoint failed, falling back to direct calculation", error); - try { - const res = await API.get("/first-timers"); - const submissions = res.data?.data || []; - - const today = new Date().toISOString().split('T')[0]; - const daily = submissions.filter(sub => sub.createdAt?.split('T')[0] === today).length; - - const sourceCounts = {}; - submissions.forEach(sub => { - if (sub.howDidYouHear) { - sourceCounts[sub.howDidYouHear] = (sourceCounts[sub.howDidYouHear] || 0) + 1; - } - }); - - let topSource = "No data"; - let maxCount = 0; - Object.entries(sourceCounts).forEach(([src, cnt]) => { - if (cnt > maxCount) { - maxCount = cnt; - topSource = src; - } - }); - - setMetrics({ - totalSubmissions: submissions.length, - dailySubmissions: daily, - followedUp: submissions.filter(s => s.followUpStatus && s.followUpStatus !== 'pending').length, - topDiscoverySource: topSource, - topDiscoveryCount: maxCount, - }); - } catch (fallbackError) { - console.error("Failed to load metrics", fallbackError); + const data = res.data?.data; + if ( + !data || + typeof data.totalSubmissions !== "number" || + typeof data.dailySubmissions !== "number" || + typeof data.followedUp !== "number" || + typeof data.topDiscoverySource !== "string" || + typeof data.topDiscoveryCount !== "number" || + !data.discoverySourcesBreakdown || + typeof data.discoverySourcesBreakdown !== "object" || + Array.isArray(data.discoverySourcesBreakdown) + ) { + throw new Error("Metrics endpoint returned an invalid response."); } + setMetrics(data); + } catch { + setUnavailable(true); } finally { setLoading(false); } @@ -64,6 +36,17 @@ const MetricsCards = () => { fetchMetrics(); }, []); + if (unavailable) { + return ( +
+ Dashboard metrics are unavailable right now. Please try again later. +
+ ); + } + return (
{/* Total Submissions */} @@ -76,7 +59,7 @@ const MetricsCards = () => { Total Submissions

- {loading ? "..." : metrics.totalSubmissions} + {loading || !metrics ? "..." : metrics.totalSubmissions}

@@ -88,10 +71,10 @@ const MetricsCards = () => {

- Daily Submissions + Daily Submissions (Africa/Lagos)

- {loading ? "..." : metrics.dailySubmissions} + {loading || !metrics ? "..." : metrics.dailySubmissions}

@@ -106,7 +89,7 @@ const MetricsCards = () => { Followed Up

- {loading ? "..." : metrics.followedUp} + {loading || !metrics ? "..." : metrics.followedUp}

@@ -121,11 +104,11 @@ const MetricsCards = () => { Discovery Sources
-

- {loading ? "..." : metrics.topDiscoverySource}: +

+ {loading || !metrics ? "..." : metrics.topDiscoverySource}:

- {loading ? "" : metrics.topDiscoveryCount} + {loading || !metrics ? "" : metrics.topDiscoveryCount}

diff --git a/src/components/dashboard/__tests__/MetricsCards.test.jsx b/src/components/dashboard/__tests__/MetricsCards.test.jsx new file mode 100644 index 0000000..126c965 --- /dev/null +++ b/src/components/dashboard/__tests__/MetricsCards.test.jsx @@ -0,0 +1,49 @@ +import { render, screen, within } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import MetricsCards from '../MetricsCards'; + +const { mockGet } = vi.hoisted(() => ({ mockGet: vi.fn() })); + +vi.mock('../../../api/axios', () => ({ + default: { get: mockGet }, +})); + +describe('dashboard metrics cards', () => { + beforeEach(() => { + mockGet.mockReset(); + }); + + it('displays valid zero metrics without requesting a paginated submissions list', async () => { + mockGet.mockResolvedValue({ + data: { + data: { + totalSubmissions: 0, + dailySubmissions: 0, + followedUp: 0, + topDiscoverySource: 'None', + topDiscoveryCount: 0, + discoverySourcesBreakdown: {}, + }, + }, + }); + + render(); + + expect(await screen.findAllByText('0')).toHaveLength(4); + for (const heading of ['Total Submissions', 'Daily Submissions (Africa/Lagos)', 'Followed Up']) { + expect(within(screen.getByRole('heading', { name: heading }).parentElement).getByText('0')).toBeInTheDocument(); + } + expect(mockGet).toHaveBeenCalledTimes(1); + expect(mockGet).toHaveBeenCalledWith('/metrics'); + }); + + it('shows an unavailable state when metrics fail instead of using page-level totals', async () => { + mockGet.mockRejectedValue(new Error('Metrics service unavailable')); + + render(); + + expect(await screen.findByRole('alert')).toHaveTextContent('Dashboard metrics are unavailable'); + expect(mockGet).toHaveBeenCalledTimes(1); + expect(mockGet).toHaveBeenCalledWith('/metrics'); + }); +});