Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
65 changes: 65 additions & 0 deletions backend/migrations/20261130_add_dashboard_metrics.sql
Original file line number Diff line number Diff line change
@@ -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;
66 changes: 66 additions & 0 deletions backend/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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;
61 changes: 7 additions & 54 deletions backend/src/controllers/metricsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
101 changes: 95 additions & 6 deletions backend/tests/accessPolicy.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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];
Expand Down Expand Up @@ -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 () => {
Expand Down
Loading
Loading