diff --git a/backend/README.md b/backend/README.md index 92fb332..eba1f84 100644 --- a/backend/README.md +++ b/backend/README.md @@ -16,7 +16,8 @@ Production-ready Node.js (Express) & Supabase (PostgreSQL) backend API for the H 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. 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**: +11. Before deploying follow-up interaction history, run `migrations/20261130_add_follow_up_note_outcomes.sql` to add the outcome field and chronological lookup index. +12. 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. diff --git a/backend/migrations/20261130_add_follow_up_note_outcomes.sql b/backend/migrations/20261130_add_follow_up_note_outcomes.sql new file mode 100644 index 0000000..f5f493a --- /dev/null +++ b/backend/migrations/20261130_add_follow_up_note_outcomes.sql @@ -0,0 +1,23 @@ +ALTER TABLE public.follow_up_notes +ADD COLUMN IF NOT EXISTS outcome TEXT; + +DO $migration$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_constraint + WHERE conname = 'follow_up_notes_outcome_check' + AND conrelid = 'public.follow_up_notes'::regclass + ) THEN + ALTER TABLE public.follow_up_notes + ADD CONSTRAINT follow_up_notes_outcome_check + CHECK ( + outcome IS NULL + OR outcome IN ('reached', 'no_answer', 'message_left', 'callback_requested', 'not_interested', 'other') + ); + END IF; +END; +$migration$; + +CREATE INDEX IF NOT EXISTS idx_follow_up_notes_first_timer_created_at + ON public.follow_up_notes (first_timer_id, created_at, id); diff --git a/backend/schema.sql b/backend/schema.sql index 6ebcf23..00decba 100644 --- a/backend/schema.sql +++ b/backend/schema.sql @@ -92,6 +92,8 @@ CREATE TABLE IF NOT EXISTS follow_up_notes ( user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, note TEXT NOT NULL, contact_method TEXT, -- 'phone', 'whatsapp', 'in_person', 'email' + outcome TEXT CONSTRAINT follow_up_notes_outcome_check + CHECK (outcome IS NULL OR outcome IN ('reached', 'no_answer', 'message_left', 'callback_requested', 'not_interested', 'other')), created_at TIMESTAMPTZ DEFAULT NOW() ); @@ -102,6 +104,8 @@ CREATE INDEX IF NOT EXISTS idx_first_timers_status ON first_timers (status); CREATE INDEX IF NOT EXISTS idx_first_timers_email ON first_timers (email); CREATE INDEX IF NOT EXISTS idx_first_timers_phone ON first_timers (phone_number); CREATE INDEX IF NOT EXISTS idx_users_email ON users (email); +CREATE INDEX IF NOT EXISTS idx_follow_up_notes_first_timer_created_at + ON follow_up_notes (first_timer_id, created_at, id); -- 7. UPDATED_AT TRIGGER FUNCTION CREATE OR REPLACE FUNCTION trigger_set_timestamp() diff --git a/backend/src/controllers/firstTimerController.js b/backend/src/controllers/firstTimerController.js index 1280b07..61a36e5 100644 --- a/backend/src/controllers/firstTimerController.js +++ b/backend/src/controllers/firstTimerController.js @@ -76,6 +76,24 @@ const updateFirstTimerSchema = z.object({ followUpStatus: z.enum(["pending", "contacted", "integrated", "closed", "followed"]).optional(), assignedTo: z.string().uuid().nullable().optional(), }).strict(); +const createFollowUpNoteSchema = z.object({ + note: z.string().trim().min(1, "A follow-up note is required.").max(2000, "Follow-up notes must be 2000 characters or fewer."), + contactMethod: z.enum(["phone", "whatsapp", "in_person", "email"]), + outcome: z.enum(["reached", "no_answer", "message_left", "callback_requested", "not_interested", "other"]), +}).strict(); + +const mapFollowUpNote = (row, fallbackAuthor = null) => ({ + id: row.id, + note: row.note, + contactMethod: row.contact_method, + outcome: row.outcome ?? null, + createdAt: row.created_at, + author: row.user + ? { id: row.user.id, fullName: row.user.full_name } + : fallbackAuthor + ? { id: fallbackAuthor.id, fullName: fallbackAuthor.name } + : null, +}); // Helper function to map database snake_case row to frontend camelCase const mapToCamelCase = (row) => { @@ -106,6 +124,11 @@ const mapToCamelCase = (row) => { assignedTo: row.assigned_to, createdAt: row.created_at, updatedAt: row.updated_at, + ...(Array.isArray(row.follow_up_notes) && { + followUpNotes: row.follow_up_notes + .map((note) => mapFollowUpNote(note)) + .sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id)), + }), }; }; @@ -257,8 +280,9 @@ export const getFirstTimerById = async (req, res, next) => { id, note, contact_method, + outcome, created_at, - user:users (id, full_name, email) + user:users (id, full_name) ) `) .eq("id", id); @@ -289,6 +313,98 @@ export const getFirstTimerById = async (req, res, next) => { } }; +const getAccessibleFirstTimer = async (id, user) => { + let query = supabase + .from("first_timers") + .select("id") + .eq("id", id); + + if (user.role === USER_ROLE.TEAM_MEMBER) { + query = query.eq("assigned_to", user.id); + } + + const { data, error } = await query.maybeSingle(); + if (error) throw error; + return data; +}; + +/** + * Protected Endpoint: Retrieve the chronological interaction history for a submission + */ +export const getFollowUpNotes = async (req, res, next) => { + try { + const submission = await getAccessibleFirstTimer(req.params.id, req.user); + if (!submission) { + return res.status(404).json({ + success: false, + message: "First timer record not found.", + }); + } + + const { data, error } = await supabase + .from("follow_up_notes") + .select("id, note, contact_method, outcome, created_at, user:users (id, full_name)") + .eq("first_timer_id", req.params.id) + .order("created_at", { ascending: true }) + .order("id", { ascending: true }); + + if (error) throw error; + + return res.status(200).json({ + success: true, + data: (data || []).map((note) => mapFollowUpNote(note)), + }); + } catch (error) { + next(error); + } +}; + +/** + * Protected Endpoint: Record a follow-up interaction for a submission + */ +export const createFollowUpNote = async (req, res, next) => { + try { + const validation = createFollowUpNoteSchema.safeParse(req.body); + if (!validation.success) { + return res.status(400).json({ + success: false, + message: validation.error.issues[0].message, + }); + } + + const submission = await getAccessibleFirstTimer(req.params.id, req.user); + if (!submission) { + return res.status(404).json({ + success: false, + message: "First timer record not found.", + }); + } + + const { note, contactMethod, outcome } = validation.data; + const { data, error } = await supabase + .from("follow_up_notes") + .insert([{ + first_timer_id: req.params.id, + user_id: req.user.id, + note, + contact_method: contactMethod, + outcome, + }]) + .select("id, note, contact_method, outcome, created_at") + .single(); + + if (error) throw error; + + return res.status(201).json({ + success: true, + message: "Follow-up interaction recorded successfully.", + data: mapFollowUpNote(data, req.user), + }); + } catch (error) { + next(error); + } +}; + /** * Protected Endpoint: Update status or details of a First Timer */ diff --git a/backend/src/routes/firstTimerRoutes.js b/backend/src/routes/firstTimerRoutes.js index ee90a44..23628f8 100644 --- a/backend/src/routes/firstTimerRoutes.js +++ b/backend/src/routes/firstTimerRoutes.js @@ -3,6 +3,8 @@ import { createFirstTimer, getFirstTimers, getFirstTimerById, + getFollowUpNotes, + createFollowUpNote, updateFirstTimer, deleteFirstTimer, exportCSV, @@ -18,6 +20,8 @@ router.post("/", submissionLimiter, createFirstTimer); router.get("/", authenticateToken, requireRoles(USER_ROLE.TEAM_MEMBER, USER_ROLE.PASTOR, USER_ROLE.ADMIN), getFirstTimers); router.get("/export", authenticateToken, requireAdmin, exportCSV); +router.get("/:id/follow-up-notes", authenticateToken, requireRoles(USER_ROLE.TEAM_MEMBER, USER_ROLE.PASTOR, USER_ROLE.ADMIN), getFollowUpNotes); +router.post("/:id/follow-up-notes", authenticateToken, requireRoles(USER_ROLE.TEAM_MEMBER, USER_ROLE.PASTOR, USER_ROLE.ADMIN), createFollowUpNote); router.get("/:id", authenticateToken, requireRoles(USER_ROLE.TEAM_MEMBER, USER_ROLE.PASTOR, USER_ROLE.ADMIN), getFirstTimerById); router.patch("/:id", authenticateToken, requireRoles(USER_ROLE.TEAM_MEMBER, USER_ROLE.PASTOR, USER_ROLE.ADMIN), updateFirstTimer); diff --git a/backend/tests/accessPolicy.test.js b/backend/tests/accessPolicy.test.js index 9386bef..cc8fe7a 100644 --- a/backend/tests/accessPolicy.test.js +++ b/backend/tests/accessPolicy.test.js @@ -39,6 +39,11 @@ const store = { { id: assignedSubmissionId, full_name: "Assigned Guest", email: "assigned@example.org", phone_number: "123", gender: "male", status: "student", assigned_to: teamMemberId, follow_up_status: "pending", created_at: "2026-01-03T00:00:00.000Z" }, { id: unassignedSubmissionId, full_name: "Other Guest", email: "other@example.org", phone_number: "456", gender: "female", status: "professional", assigned_to: null, follow_up_status: "contacted", created_at: "2026-01-02T00:00:00.000Z" }, ], + follow_up_notes: [ + { id: "note-later", first_timer_id: assignedSubmissionId, user_id: pastorId, note: "Shared an invitation.", contact_method: "phone", outcome: "reached", created_at: "2026-03-02T10:00:00.000Z" }, + { id: "note-earlier", first_timer_id: assignedSubmissionId, user_id: teamMemberId, note: "No answer.", contact_method: "whatsapp", outcome: "no_answer", created_at: "2026-03-01T10:00:00.000Z" }, + { id: "note-unassigned", first_timer_id: unassignedSubmissionId, user_id: pastorId, note: "Please visit next Sunday.", contact_method: "in_person", outcome: "callback_requested", created_at: "2026-03-03T10:00:00.000Z" }, + ], }; const matches = (row, filters) => filters.every(({ field, operator, value }) => { @@ -97,6 +102,7 @@ const makeQuery = (table) => { let first = 0; let last = Number.POSITIVE_INFINITY; let head = false; + const orderings = []; const query = { select(_columns, options = {}) { @@ -118,7 +124,8 @@ const makeQuery = (table) => { or() { return this; }, - order() { + order(field, { ascending = true } = {}) { + orderings.push({ field, ascending }); return this; }, range(start, end) { @@ -148,6 +155,14 @@ const makeQuery = (table) => { }, execute(single = false) { const rows = store[table] || []; + const withNoteAuthor = (row) => { + if (table !== "follow_up_notes") return row; + const author = store.users.find((user) => user.id === row.user_id); + return { + ...row, + user: author ? { id: author.id, full_name: author.full_name } : null, + }; + }; if (action === "insert") { const inserted = values.map((value, index) => ({ @@ -159,7 +174,8 @@ const makeQuery = (table) => { ...value, })); store[table].push(...inserted); - return { data: single ? inserted[0] : inserted, error: null, count: inserted.length }; + const responseRows = inserted.map(withNoteAuthor); + return { data: single ? responseRows[0] : responseRows, error: null, count: inserted.length }; } const selected = rows.filter((row) => matches(row, filters)); @@ -181,7 +197,16 @@ const makeQuery = (table) => { if (head) { return { data: null, error: null, count: selected.length }; } - const paged = selected.slice(first, last + 1); + const ordered = table === "follow_up_notes" + ? [...selected].sort((left, right) => { + for (const { field, ascending } of orderings) { + const comparison = String(left[field] ?? "").localeCompare(String(right[field] ?? "")); + if (comparison !== 0) return ascending ? comparison : -comparison; + } + return 0; + }) + : selected; + const paged = ordered.slice(first, last + 1).map(withNoteAuthor); return { data: single ? paged[0] || null : paged, error: null, count: selected.length }; }, then(resolve, reject) { @@ -482,6 +507,110 @@ test("team members are limited to assigned submissions and follow-up status chan }); }); +test("follow-up notes preserve assignment scope, attribution, and chronological persistence", async (t) => { + await t.test("anonymous users cannot retrieve or create notes", async () => { + const path = `/first-timers/${assignedSubmissionId}/follow-up-notes`; + assert.equal((await request(path)).status, 401); + assert.equal((await request(path, { + method: "POST", + body: { note: "A call was made.", contactMethod: "phone", outcome: "reached" }, + })).status, 401); + }); + + await t.test("team members can read and add notes only for assigned submissions", async () => { + const path = `/first-timers/${assignedSubmissionId}/follow-up-notes`; + const listResponse = await request(path, { id: teamMemberId }); + const listPayload = await listResponse.json(); + + assert.equal(listResponse.status, 200); + assert.deepEqual(listPayload.data.map(({ id }) => id), ["note-earlier", "note-later"]); + assert.equal(listPayload.data[0].author.fullName, "Team Member"); + assert.equal(listPayload.data[0].outcome, "no_answer"); + + const notesBefore = store.follow_up_notes.length; + const invalidResponse = await request(path, { + id: teamMemberId, + method: "POST", + body: { note: " ", contactMethod: "phone", outcome: "reached" }, + }); + assert.equal(invalidResponse.status, 400); + assert.equal(store.follow_up_notes.length, notesBefore); + + const invalidOutcomeResponse = await request(path, { + id: teamMemberId, + method: "POST", + body: { note: "A valid note.", contactMethod: "phone", outcome: "unknown" }, + }); + assert.equal(invalidOutcomeResponse.status, 400); + assert.equal(store.follow_up_notes.length, notesBefore); + + const createResponse = await request(path, { + id: teamMemberId, + method: "POST", + body: { + note: " Invited them to the newcomers gathering. ", + contactMethod: "whatsapp", + outcome: "callback_requested", + userId: pastorId, + createdAt: "2000-01-01T00:00:00.000Z", + }, + }); + assert.equal(createResponse.status, 400); + assert.equal(store.follow_up_notes.length, notesBefore); + + const validCreateResponse = await request(path, { + id: teamMemberId, + method: "POST", + body: { + note: " Invited them to the newcomers gathering. ", + contactMethod: "whatsapp", + outcome: "callback_requested", + }, + }); + const created = await validCreateResponse.json(); + const persisted = store.follow_up_notes.find(({ id }) => id === created.data.id); + + assert.equal(validCreateResponse.status, 201); + assert.equal(created.data.note, "Invited them to the newcomers gathering."); + assert.equal(created.data.author.fullName, "Team Member"); + assert.equal(persisted.user_id, teamMemberId); + assert.equal(persisted.outcome, "callback_requested"); + assert.ok(persisted.created_at); + + const unassignedPath = `/first-timers/${unassignedSubmissionId}/follow-up-notes`; + assert.equal((await request(unassignedPath, { id: teamMemberId })).status, 404); + assert.equal((await request(unassignedPath, { + id: teamMemberId, + method: "POST", + body: { note: "Unauthorized note.", contactMethod: "phone", outcome: "reached" }, + })).status, 404); + + const refreshedResponse = await request(path, { id: teamMemberId }); + const refreshed = await refreshedResponse.json(); + assert.deepEqual( + refreshed.data.map(({ note }) => note), + ["No answer.", "Shared an invitation.", "Invited them to the newcomers gathering."] + ); + }); + + await t.test("pastors and administrators can access notes for unassigned submissions", async () => { + const path = `/first-timers/${unassignedSubmissionId}/follow-up-notes`; + const pastorResponse = await request(path, { id: pastorId }); + const pastorPayload = await pastorResponse.json(); + assert.equal(pastorResponse.status, 200); + assert.equal(pastorPayload.data[0].author.fullName, "Pastor"); + + const adminResponse = await request(path, { + id: adminId, + method: "POST", + body: { note: "Follow-up scheduled.", contactMethod: "in_person", outcome: "reached" }, + }); + const adminPayload = await adminResponse.json(); + assert.equal(adminResponse.status, 201); + assert.equal(adminPayload.data.author.fullName, "Administrator"); + }); +}); + test("pastors have oversight access while administrators retain account and export controls", async (t) => { await t.test("pastors can view all submissions, metrics, and the staff directory", async () => { for (const path of ["/first-timers", "/metrics", "/users"]) { diff --git a/src/components/dashboard/SubmissionModal.jsx b/src/components/dashboard/SubmissionModal.jsx index afd6d28..2fec82c 100644 --- a/src/components/dashboard/SubmissionModal.jsx +++ b/src/components/dashboard/SubmissionModal.jsx @@ -1,4 +1,5 @@ -import { useState } from 'react'; +import { useEffect, useState } from 'react'; +import API from '../../api/axios'; import { getMembershipInterestLabel } from '../../data/membershipInterest'; import { FaUser, @@ -17,9 +18,61 @@ import { FaShieldHalved } from 'react-icons/fa6'; +const contactMethodLabels = { + phone: 'Phone', + whatsapp: 'WhatsApp', + in_person: 'In person', + email: 'Email', +}; + +const outcomeLabels = { + reached: 'Reached', + no_answer: 'No answer', + message_left: 'Message left', + callback_requested: 'Callback requested', + not_interested: 'Not interested', + other: 'Other', +}; + const SubmissionModal = ({ data, onClose, isAdmin, canUpdateFollowUp, onToggleFollowed, onDelete }) => { const [copiedField, setCopiedField] = useState(""); const [updatingStatus, setUpdatingStatus] = useState(false); + const [followUpNotes, setFollowUpNotes] = useState([]); + const [notesLoading, setNotesLoading] = useState(true); + const [notesError, setNotesError] = useState(""); + const [noteText, setNoteText] = useState(""); + const [contactMethod, setContactMethod] = useState("phone"); + const [outcome, setOutcome] = useState("reached"); + const [savingNote, setSavingNote] = useState(false); + + useEffect(() => { + if (!data?.id) return undefined; + + let active = true; + setFollowUpNotes([]); + setNotesError(""); + setNotesLoading(true); + + API.get(`/first-timers/${data.id}/follow-up-notes`) + .then((response) => { + if (!Array.isArray(response.data?.data)) { + throw new Error('Follow-up history could not be loaded.'); + } + if (active) setFollowUpNotes(response.data.data); + }) + .catch((error) => { + if (active) { + setNotesError(error.response?.data?.message || error.message || 'Failed to load follow-up history.'); + } + }) + .finally(() => { + if (active) setNotesLoading(false); + }); + + return () => { + active = false; + }; + }, [data?.id]); const copyToClipboard = (text, fieldName) => { navigator.clipboard.writeText(text); @@ -39,6 +92,34 @@ const SubmissionModal = ({ data, onClose, isAdmin, canUpdateFollowUp, onToggleFo setUpdatingStatus(false); }; + const handleNoteSubmit = async (event) => { + event.preventDefault(); + if (savingNote || !noteText.trim()) return; + + setSavingNote(true); + setNotesError(""); + try { + const response = await API.post(`/first-timers/${data.id}/follow-up-notes`, { + note: noteText, + contactMethod, + outcome, + }); + const createdNote = response.data?.data; + if (!createdNote) { + throw new Error('Follow-up interaction could not be saved.'); + } + + setFollowUpNotes((previous) => [...previous, createdNote].sort( + (left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id) + )); + setNoteText(""); + } catch (error) { + setNotesError(error.response?.data?.message || error.message || 'Failed to save follow-up interaction.'); + } finally { + setSavingNote(false); + } + }; + return (
+ +
+
+ +

+ Follow-up History +

+
+ + {notesError && ( +

+ {notesError} +

+ )} + + {notesLoading ? ( +

Loading follow-up history...

+ ) : followUpNotes.length === 0 ? ( +

+ No follow-up interactions have been recorded. +

+ ) : ( +
    + {followUpNotes.map((interaction) => ( +
  1. +
    + + {outcomeLabels[interaction.outcome] || 'Outcome not recorded'} + + + {contactMethodLabels[interaction.contactMethod] || interaction.contactMethod || 'Method not recorded'} + + +
    +

    + {interaction.note} +

    +

    + Recorded by {interaction.author?.fullName || 'Staff member'} +

    +
  2. + ))} +
+ )} + + {canUpdateFollowUp && ( +
+

Record an interaction

+