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
40 changes: 38 additions & 2 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ Production-ready Node.js (Express) & Supabase (PostgreSQL) backend API for the H
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. Before deploying the dashboard-metrics update, run `migrations/20261130_add_dashboard_metrics.sql`.
10. In **Project Settings** > **API**:
10. Before deploying the privacy-retention update, run `migrations/20261130_add_first_timer_retention.sql`. This enables `pg_cron` and schedules an hourly deletion of submissions older than 13 months; related follow-up notes are deleted by the foreign-key cascade.
11. 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 @@ -109,7 +110,42 @@ The query should return no rows. Then use only the public anon key from a non-pr

### 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.
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. Because the retention job deletes records after 13 months, these metrics only reflect records still within that retention period. 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.

### Privacy, data use, and retention

The intake information is used for individual guest follow-up and analysis of outreach, church growth, and retention. Prayer requests are optional and used for pastoral care. Administrators and pastors can access all submissions; team members can access only submissions assigned to them. Data is not shared with other organizations; Supabase and Render process it to provide the hosted service.

| Data | Purpose | Retention |
| --- | --- | --- |
| Name, phone, email, residence, preferred contact method, and contact time | Guest follow-up | 13 months from submission |
| Gender, date of birth, current status, student/professional details, and other-status details | Outreach and church growth/retention analysis and follow-up context | 13 months from submission |
| Discovery source, membership interest, and experience feedback | Outreach, growth, and retention analysis | 13 months from submission |
| Optional prayer requests | Pastoral care | 13 months from submission |
| Follow-up status, assignment, and interaction notes | Staff follow-up workflow | 13 months from submission |
| Submission identifiers and timestamps | Record management, follow-up, and enforcing the retention cutoff | 13 months from submission |

An hourly `pg_cron` job permanently deletes submissions once they are at least 13 months old. The database foreign key cascades deletion to associated follow-up notes. No backups or post-expiry statistics are retained, so dashboard totals and analysis cover only records still within the retention period. Correction or deletion requests can be sent to [contacthgbc@gmail.com](mailto:contacthgbc@gmail.com).

Verify the scheduled job and its recent status without querying guest records:

```sql
SELECT jobid, jobname, schedule, active
FROM cron.job
WHERE jobname = 'delete-expired-first-timer-data';

SELECT status, start_time, end_time, return_message
FROM cron.job_run_details
WHERE jobid = (
SELECT jobid
FROM cron.job
WHERE jobname = 'delete-expired-first-timer-data'
)
ORDER BY start_time DESC
LIMIT 10;
```

Downloaded CSV exports must also be handled under the same 13-month limit and not kept as separate backups.

---

Expand Down
43 changes: 43 additions & 0 deletions backend/migrations/20261130_add_first_timer_retention.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
CREATE EXTENSION IF NOT EXISTS pg_cron;

CREATE OR REPLACE FUNCTION public.delete_expired_first_timers()
RETURNS BIGINT
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $function$
DECLARE
deleted_count BIGINT;
BEGIN
DELETE FROM public.first_timers
WHERE created_at <= CURRENT_TIMESTAMP - INTERVAL '13 months';

GET DIAGNOSTICS deleted_count = ROW_COUNT;
RETURN deleted_count;
END;
$function$;

REVOKE ALL ON FUNCTION public.delete_expired_first_timers()
FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION public.delete_expired_first_timers()
TO service_role;

DO $schedule$
DECLARE
existing_job_id BIGINT;
BEGIN
FOR existing_job_id IN
SELECT jobid
FROM cron.job
WHERE jobname = 'delete-expired-first-timer-data'
LOOP
PERFORM cron.unschedule(existing_job_id);
END LOOP;

PERFORM cron.schedule(
'delete-expired-first-timer-data',
'0 * * * *',
'SELECT public.delete_expired_first_timers();'
);
END;
$schedule$;
44 changes: 44 additions & 0 deletions backend/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,47 @@ 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;

CREATE EXTENSION IF NOT EXISTS pg_cron;

CREATE OR REPLACE FUNCTION public.delete_expired_first_timers()
RETURNS BIGINT
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = ''
AS $function$
DECLARE
deleted_count BIGINT;
BEGIN
DELETE FROM public.first_timers
WHERE created_at <= CURRENT_TIMESTAMP - INTERVAL '13 months';

GET DIAGNOSTICS deleted_count = ROW_COUNT;
RETURN deleted_count;
END;
$function$;

REVOKE ALL ON FUNCTION public.delete_expired_first_timers()
FROM PUBLIC, anon, authenticated;
GRANT EXECUTE ON FUNCTION public.delete_expired_first_timers()
TO service_role;

DO $schedule$
DECLARE
existing_job_id BIGINT;
BEGIN
FOR existing_job_id IN
SELECT jobid
FROM cron.job
WHERE jobname = 'delete-expired-first-timer-data'
LOOP
PERFORM cron.unschedule(existing_job_id);
END LOOP;

PERFORM cron.schedule(
'delete-expired-first-timer-data',
'0 * * * *',
'SELECT public.delete_expired_first_timers();'
);
END;
$schedule$;
90 changes: 73 additions & 17 deletions backend/src/controllers/firstTimerController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,75 @@ import { z } from "zod";
import { USER_ROLE } from "../../../shared/userRoles.js";
import { supabase } from "../config/supabase.js";

const membershipInterestValues = ["interested", "more_info", "not_now"];
const optionalText = z.string().trim().nullish();
const dateOfBirthSchema = z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "Date of birth is required.")
.refine((value) => {
const date = new Date(`${value}T00:00:00.000Z`);
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
}, "Date of birth must be a valid date.");

const createFirstTimerSchema = z.object({
fullName: z.string().trim().min(1, "Full name is required."),
gender: z.enum(["male", "female"], {
required_error: "Gender is required.",
}),
dateOfBirth: dateOfBirthSchema,
phoneNumber: z.string().trim().min(7, "Phone number is too short."),
email: z.string().trim().email("Invalid email address."),
residenceAddress: z.string().trim().min(1, "Residence address is required."),
status: z.enum(["student", "professional", "other"], {
required_error: "Status is required.",
}),
studentLevel: optionalText,
studentFaculty: optionalText,
studentDepartment: optionalText,
studentInstitution: optionalText,
professionalOrganization: optionalText,
professionalOccupation: optionalText,
otherStatus: optionalText,
howDidYouHear: z.string().trim().min(1, "Please let us know how you heard about us."),
membershipInterest: z.enum(["interested", "more_info", "not_now", ""]).nullish(),
experienceToday: optionalText,
bestContactTime: optionalText,
preferredContactMethod: optionalText,
prayerRequests: optionalText,
}).superRefine((data, ctx) => {
if (data.status === "student") {
for (const [field, label] of [
["studentInstitution", "Institution"],
["studentFaculty", "Faculty"],
["studentDepartment", "Department"],
["studentLevel", "Level"],
]) {
if (!data[field]) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: [field],
message: `${label} is required.`,
});
}
}
}

if (data.status === "professional" && !data.professionalOccupation) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["professionalOccupation"],
message: "Occupation is required.",
});
}

if (data.status === "other" && !data.otherStatus) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["otherStatus"],
message: "Please specify your status.",
});
}
});

const updateFirstTimerSchema = z.object({
followUpStatus: z.enum(["pending", "contacted", "integrated", "closed", "followed"]).optional(),
assignedTo: z.string().uuid().nullable().optional(),
Expand Down Expand Up @@ -73,27 +141,15 @@ const mapToSnakeCase = (data) => {
*/
export const createFirstTimer = async (req, res, next) => {
try {
const payload = req.body;

if (!payload.fullName || !payload.email || !payload.phoneNumber) {
return res.status(400).json({
success: false,
message: "Full Name, Email, and Phone Number are required fields.",
});
}

if (
payload.membershipInterest !== undefined &&
payload.membershipInterest !== null &&
payload.membershipInterest !== "" &&
!membershipInterestValues.includes(payload.membershipInterest)
) {
const validation = createFirstTimerSchema.safeParse(req.body);
if (!validation.success) {
return res.status(400).json({
success: false,
message: "Membership interest must be a supported option.",
message: validation.error.issues[0].message,
});
}

const payload = validation.data;
const dbPayload = mapToSnakeCase(payload);

const { data, error } = await supabase
Expand Down
33 changes: 32 additions & 1 deletion backend/tests/accessPolicy.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,10 +266,16 @@ test("public signup is closed and intake cannot assign or pre-mark submissions",
body: {
fullName: "Guest",
email: "guest@example.org",
phoneNumber: "789",
phoneNumber: "08000000000",
gender: "male",
dateOfBirth: "2000-01-01",
residenceAddress: "Somewhere",
status: "student",
studentInstitution: "Example University",
studentFaculty: "Science",
studentDepartment: "Biology",
studentLevel: "300",
howDidYouHear: "friend",
followUpStatus: "contacted",
assignedTo: teamMemberId,
},
Expand All @@ -279,6 +285,7 @@ test("public signup is closed and intake cannot assign or pre-mark submissions",
assert.equal(response.status, 201);
assert.equal(payload.data.followUpStatus, "pending");
assert.equal(payload.data.assignedTo, null);
assert.equal(payload.data.prayerRequests, null);
});

await t.test("intake rejects missing required fields without inserting a submission", async () => {
Expand All @@ -291,6 +298,30 @@ test("public signup is closed and intake cannot assign or pre-mark submissions",
assert.equal(response.status, 400);
assert.equal(store.first_timers.length, countBefore);
});

await t.test("intake rejects incomplete student details without inserting a submission", async () => {
const countBefore = store.first_timers.length;
const response = await request("/first-timers", {
method: "POST",
body: {
fullName: "Student Guest",
email: "student@example.org",
phoneNumber: "08000000000",
gender: "female",
dateOfBirth: "2000-01-01",
residenceAddress: "Somewhere",
status: "student",
studentInstitution: "Example University",
studentFaculty: "Science",
studentDepartment: "",
studentLevel: "300",
howDidYouHear: "friend",
},
});

assert.equal(response.status, 400);
assert.equal(store.first_timers.length, countBefore);
});
});

test("anonymous, disabled, and role-restricted requests are rejected", async (t) => {
Expand Down
36 changes: 35 additions & 1 deletion src/pages/Hero.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ const Hero = () => {
</section>

{/* Card Form Container */}
<div className="max-w-6xl mx-auto -mt-10 sm:-mt-16 lg:-mt-20 relative z-20 px-3 sm:px-6 pb-16 sm:pb-20">
<div className="max-w-6xl mx-auto -mt-10 sm:-mt-16 lg:-mt-20 relative z-20 px-3 sm:px-6 pb-16 sm:pb-20 space-y-6">
<div className="bg-white rounded-2xl sm:rounded-3xl shadow-lg overflow-hidden border border-gray-100">
<form onSubmit={handleSubmit} className="p-4 sm:p-8 md:p-12 space-y-6 sm:space-y-8">
<div className="flex justify-between items-center border-b border-gray-100 pb-4 sm:pb-5 mb-4 sm:mb-8">
Expand Down Expand Up @@ -651,6 +651,40 @@ const Hero = () => {
)}
</form>
</div>
{/* Privacy Notice */}
<section
aria-labelledby="privacy-notice-title"
className="rounded-xl border border-blue-200 bg-blue-50 p-4 text-sm text-slate-700"
>
<h3 id="privacy-notice-title" className="font-bold text-slate-900 text-[14px] md:text-[16px]">
Privacy and data use
</h3>
<ul className="mt-2 list-disc space-y-2 pl-5">
<li>
We use your information to follow up with you and assess our outreach, church growth, and retention.
Student, professional, and demographic details support this work. Prayer requests are optional and
used for pastoral care.
</li>
<li>
We retain submissions and related follow-up notes for 13 months from submission, then delete them.
We keep no backup copies or post-expiry statistics.
</li>
<li>
We do not share your information with other organizations.
</li>
<li>
To request a correction or deletion, email{" "}
<a
className="font-semibold text-blue-800 underline"
href="mailto:contacthgbc@gmail.com"
>
contacthgbc@gmail.com
</a>
.
</li>
</ul>
</section>

</div>
</main>
<Footer />
Expand Down
15 changes: 14 additions & 1 deletion src/pages/__tests__/Hero.test.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { act, fireEvent, render, screen } from '@testing-library/react';
import { act, fireEvent, render, screen, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter } from 'react-router-dom';
import Hero from '../Hero';
Expand Down Expand Up @@ -59,6 +59,19 @@ describe('first-timer submission form', () => {
expect(mockPost).not.toHaveBeenCalled();
});

it('displays the privacy notice and keeps prayer requests optional', () => {
const { container } = renderHero();
const privacyNotice = screen.getByRole('region', { name: 'Privacy and data use' });
const prayerRequest = container.querySelector('[name="prayerRequests"]');

expect(privacyNotice).toHaveTextContent('13 months');
expect(within(privacyNotice).getByRole('link', { name: 'contacthgbc@gmail.com' })).toHaveAttribute(
'href',
'mailto:contacthgbc@gmail.com'
);
expect(prayerRequest).not.toHaveAttribute('required');
});

it('shows success after submission and resets the form', async () => {
mockPost.mockResolvedValue({ data: { success: true } });
const { container } = renderHero();
Expand Down
2 changes: 1 addition & 1 deletion src/pages/dashboard/Overview.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const Overview = () => {
<tr key={item.id} className="hover:bg-slate-50/80 transition-colors group">
<td className="px-4 sm:px-6 py-3.5 sm:py-4">
<div className="flex items-center gap-3">
<div className="h-9 w-9 sm:h-10 sm:w-10 shrink-0 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center font-bold text-xs border border-indigo-100 group-hover:bg-indigo-600 group-hover:text-white transition-all duration-300">
<div className="h-9 w-9 sm:h-10 sm:w-10 shrink-0 rounded-full bg-indigo-50 text-indigo-600 flex items-center justify-center font-bold text-xs border border-indigo-100 group-hover:bg-indigo-600 group-hover:text-white transition-all duration-300">
{item.fullName.split(' ').map(n => n[0]).join('')}
</div>
<span className="font-semibold text-slate-700 whitespace-nowrap text-sm">{item.fullName}</span>
Expand Down
Loading