diff --git a/backend/README.md b/backend/README.md index f865a6c..92fb332 100644 --- a/backend/README.md +++ b/backend/README.md @@ -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. @@ -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. --- diff --git a/backend/migrations/20261130_add_first_timer_retention.sql b/backend/migrations/20261130_add_first_timer_retention.sql new file mode 100644 index 0000000..9031145 --- /dev/null +++ b/backend/migrations/20261130_add_first_timer_retention.sql @@ -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$; diff --git a/backend/schema.sql b/backend/schema.sql index 6c213de..6ebcf23 100644 --- a/backend/schema.sql +++ b/backend/schema.sql @@ -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$; diff --git a/backend/src/controllers/firstTimerController.js b/backend/src/controllers/firstTimerController.js index ea9fe0d..1280b07 100644 --- a/backend/src/controllers/firstTimerController.js +++ b/backend/src/controllers/firstTimerController.js @@ -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(), @@ -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 diff --git a/backend/tests/accessPolicy.test.js b/backend/tests/accessPolicy.test.js index ba836fd..9386bef 100644 --- a/backend/tests/accessPolicy.test.js +++ b/backend/tests/accessPolicy.test.js @@ -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, }, @@ -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 () => { @@ -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) => { diff --git a/src/pages/Hero.jsx b/src/pages/Hero.jsx index 81db331..85dbf6d 100644 --- a/src/pages/Hero.jsx +++ b/src/pages/Hero.jsx @@ -243,7 +243,7 @@ const Hero = () => { {/* Card Form Container */} -
+
@@ -651,6 +651,40 @@ const Hero = () => { )}
+ {/* Privacy Notice */} +
+

+ Privacy and data use +

+
    +
  • + 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. +
  • +
  • + 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. +
  • +
  • + We do not share your information with other organizations. +
  • +
  • + To request a correction or deletion, email{" "} + + contacthgbc@gmail.com + + . +
  • +
+
+