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
3 changes: 2 additions & 1 deletion backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 23 additions & 0 deletions backend/migrations/20261130_add_follow_up_note_outcomes.sql
Original file line number Diff line number Diff line change
@@ -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);
4 changes: 4 additions & 0 deletions backend/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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()
);

Expand All @@ -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()
Expand Down
118 changes: 117 additions & 1 deletion backend/src/controllers/firstTimerController.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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)),
}),
};
};

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
*/
Expand Down
4 changes: 4 additions & 0 deletions backend/src/routes/firstTimerRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import {
createFirstTimer,
getFirstTimers,
getFirstTimerById,
getFollowUpNotes,
createFollowUpNote,
updateFirstTimer,
deleteFirstTimer,
exportCSV,
Expand All @@ -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);
Expand Down
Loading
Loading