B2: profile + notification_preferences + SMS consent capture (TCPA)

- notification_preferences table (user_id PK->users, email/sms toggles,
  sms_consent_at/source/ip evidence, quiet hours, digest) + migration 0002
- src/domain/consent.ts: pure TCPA rule (phoneChanged/buildConsent/resetConsent)
- src/db/profile.ts: updateProfile (partial update; resets consent on phone
  change) + setSmsConsent (opt-in) + getProfile
- PATCH/POST /api/dev/profile routes
- seed: per-user prefs row (email on, SMS off)
- 6 unit tests named after the rules
This commit is contained in:
Tiel Coder
2026-11-18 00:09:05 +00:00
parent 5f0b94af6a
commit 26b31978e2
10 changed files with 1398 additions and 0 deletions
+112
View File
@@ -0,0 +1,112 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { updateProfile, setSmsConsent } from "@/db/profile";
import type { ProfilePatch } from "@/db/profile";
import type { SmsConsentSource } from "@/db/schema";
const JSON_HEADERS = { "content-type": "application/json" };
const profileSchema = z.object({
userId: z.string().min(1),
firstName: z.string().optional(),
lastName: z.string().optional(),
displayName: z.string().optional(),
phoneE164: z.string().nullable().optional(),
emergencyContact: z.string().nullable().optional(),
timezone: z.string().optional(),
});
const consentSchema = z.object({
userId: z.string().min(1),
source: z.enum(["web_signup", "paper_form", "admin_import"]),
ip: z.string().nullable().optional(),
});
/**
* PATCH /api/dev/profile — update a user's profile. If the phone number
* changes, SMS consent is reset (TCPA).
*/
export const PATCH = async (req: NextRequest) => {
let body: unknown;
try {
body = JSON.parse(await req.text());
} catch {
return new Response(JSON.stringify({ error: "invalid body" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const parsed = profileSchema.safeParse(body);
if (!parsed.success) {
return new Response(JSON.stringify({ error: "a userId is required" }), {
status: 400,
headers: JSON_HEADERS,
});
}
try {
// Only update fields actually present in the body — a PATCH must not null
// out unspecified fields (e.g. omitting phoneE164 must not wipe the phone).
const patch: ProfilePatch = {};
if (parsed.data.firstName !== undefined) patch.firstName = parsed.data.firstName;
if (parsed.data.lastName !== undefined) patch.lastName = parsed.data.lastName;
if (parsed.data.displayName !== undefined) patch.displayName = parsed.data.displayName;
if (parsed.data.phoneE164 !== undefined) patch.phoneE164 = parsed.data.phoneE164;
if (parsed.data.emergencyContact !== undefined) patch.emergencyContact = parsed.data.emergencyContact;
if (parsed.data.timezone !== undefined) patch.timezone = parsed.data.timezone;
const result = await updateProfile(parsed.data.userId, patch);
return new Response(JSON.stringify(result), {
status: 200,
headers: JSON_HEADERS,
});
} catch {
return new Response(JSON.stringify({ error: "failed to update profile" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
/**
* POST /api/dev/consent — record an explicit SMS opt-in (TCPA evidence).
*/
export const POST = async (req: NextRequest) => {
let body: unknown;
try {
body = JSON.parse(await req.text());
} catch {
return new Response(JSON.stringify({ error: "invalid body" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const parsed = consentSchema.safeParse(body);
if (!parsed.success) {
return new Response(JSON.stringify({ error: "userId and source are required" }), {
status: 400,
headers: JSON_HEADERS,
});
}
try {
const preferences = await setSmsConsent(
parsed.data.userId,
{
source: parsed.data.source as SmsConsentSource,
ip: parsed.data.ip ?? null,
},
);
return new Response(JSON.stringify({ ok: true, preferences }), {
status: 200,
headers: JSON_HEADERS,
});
} catch {
return new Response(JSON.stringify({ error: "failed to record consent" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
+120
View File
@@ -0,0 +1,120 @@
/**
* Profile + SMS consent data access (BUILD-PLAN unit B2). Thin wrappers around
* `users` and `notification_preferences`, built on the pure rule in
* `src/domain/consent.ts`.
*
* - `updateProfile` updates a user's fields; if their phone number changes,
* their SMS consent is reset (TCPA: consent is bound to a number).
* - `setSmsConsent` records an explicit opt-in (timestamp, source, IP).
*/
import { db } from "./index";
import { users, notificationPreferences } from "./schema";
import { eq } from "drizzle-orm";
import { phoneChanged, buildConsent, resetConsent } from "@/domain/consent";
import type { SmsConsentSource } from "@/db/schema";
export type ProfilePatch = Partial<{
firstName: string;
lastName: string;
displayName: string;
phoneE164: string | null;
emergencyContact: string | null;
timezone: string;
}>;
export type ConsentSourceInput = SmsConsentSource;
async function getUserById(userId: string) {
const rows = await db.select().from(users).where(eq(users.id, userId)).limit(1);
return rows[0] ?? null;
}
async function getPrefs(userId: string) {
const rows = await db
.select()
.from(notificationPreferences)
.where(eq(notificationPreferences.userId, userId))
.limit(1);
return rows[0] ?? null;
}
async function upsertPrefs(
userId: string,
patch: Record<string, unknown>,
): Promise<(typeof notificationPreferences.$inferSelect) | null> {
const existing = await getPrefs(userId);
if (existing) {
const [row] = await db
.update(notificationPreferences)
.set(patch)
.where(eq(notificationPreferences.userId, userId))
.returning();
return row;
}
const [row] = await db
.insert(notificationPreferences)
.values({ userId, ...patch })
.onConflictDoUpdate({
target: notificationPreferences.userId,
set: patch,
})
.returning();
return row;
}
/**
* Update a user's profile. When the phone number changes, their SMS consent is
* cleared (the prior consent covered the old number only). Returns the updated
* user and their (possibly reset) preferences.
*/
export async function updateProfile(
userId: string,
patch: ProfilePatch,
): Promise<{ user: (typeof users.$inferSelect); preferences: (typeof notificationPreferences.$inferSelect) | null }> {
const existing = await getUserById(userId);
if (!existing) throw new Error(`user ${userId} not found`);
const phoneChangedHere =
patch.phoneE164 !== undefined && phoneChanged(existing.phoneE164, patch.phoneE164);
const [user] = await db
.update(users)
.set({ ...patch, updatedAt: new Date() })
.where(eq(users.id, userId))
.returning();
// Reset consent when the number changes; otherwise leave prefs untouched.
let preferences;
if (phoneChangedHere) {
preferences = await upsertPrefs(userId, resetConsent());
} else {
preferences = await getPrefs(userId);
}
return { user: user!, preferences };
}
/**
* Record an explicit SMS opt-in: enable SMS and write the TCPA evidence
* (timestamp, source, IP). Upserts the preferences row.
*/
export async function setSmsConsent(
userId: string,
input: { source: ConsentSourceInput; ip: string | null },
at: Date = new Date(),
): Promise<(typeof notificationPreferences.$inferSelect) | null> {
const prefs = await getUserById(userId);
if (!prefs) throw new Error(`user ${userId} not found`);
return upsertPrefs(userId, buildConsent(input.source, input.ip, at));
}
/** Read a user's profile + preferences (for the profile screen / tests). */
export async function getProfile(userId: string) {
const [user, ...prefsRows] = await Promise.all([
getUserById(userId),
getPrefs(userId),
]);
if (!user) throw new Error(`user ${userId} not found`);
return { user, preferences: prefsRows[0] ?? null };
}
+38
View File
@@ -5,6 +5,7 @@
* users → roles → services → service_instances → slots → assignments
*
* Deliberately NOT here (added in later units, do not add "while I'm in the schema"):
* - notification_preferences (B2), notification_templates/rules/outbox (later)
* - Catalog taxonomy: skill_categories, vendors, technologies, functions,
* skills, position_skills, user_skills, skill_assessments, growth_goals (B3)
* - service_role_requirements, unavailability, events, notifications outbox
@@ -42,6 +43,10 @@ export type AssignmentSource = (typeof ASSIGNMENT_SOURCES)[number];
export const CONFIRMED_VIAS = ["app", "email_link", "sms_reply", "admin"] as const;
export type ConfirmedVia = (typeof CONFIRMED_VIAS)[number];
/** TCPA consent source recorded on SMS opt-in (ARCHITECTURE §4.76). */
export const SMS_CONSENT_SOURCES = ["web_signup", "paper_form", "admin_import"] as const;
export type SmsConsentSource = (typeof SMS_CONSENT_SOURCES)[number];
const DEFAULT_TIMEZONE = "America/New_York";
/* ------------------------------------------------------------------ users */
@@ -79,6 +84,33 @@ export const users = pgTable(
],
);
/* -------------------------------------------------- notification prefs */
/**
* Per-user notification preferences (ARCHITECTURE §4.76). One row per user
* (PK = user_id). SMS consent fields are TCPA evidence: an explicit opt-in
* records the timestamp, source, and IP. Consent is bound to a phone number,
* so changing the number clears it (see src/db/profile.ts).
*/
export const notificationPreferences = pgTable(
"notification_preferences",
{
userId: text("user_id")
.primaryKey()
.references(() => users.id, { onDelete: "cascade" }),
emailEnabled: boolean("email_enabled").notNull().default(true),
smsEnabled: boolean("sms_enabled").notNull().default(false),
smsConsentAt: timestamp("sms_consent_at", { mode: "date", withTimezone: true }),
smsConsentSource: text("sms_consent_source", { enum: SMS_CONSENT_SOURCES }),
smsConsentIp: text("sms_consent_ip"),
reminderLeadDays: integer("reminder_lead_days").notNull().default(7),
quietHoursStart: text("quiet_hours_start").notNull().default("21:00"),
quietHoursEnd: text("quiet_hours_end").notNull().default("08:00"),
digestOnly: boolean("digest_only").notNull().default(false),
},
() => [],
);
/* ------------------------------------------------------------------ roles */
export const roles = pgTable(
@@ -226,6 +258,11 @@ export const usersRelations = relations(users, ({ many }) => ({
assignments: many(assignments),
}));
export const notificationPreferencesRelations = relations(
notificationPreferences,
() => ({}),
);
export const serviceInstanceRelations = relations(serviceInstances, ({ one, many }) => ({
service: one(services),
slots: many(slots),
@@ -248,6 +285,7 @@ export const assignmentRelations = relations(assignments, ({ one }) => ({
*/
export const schema = {
users,
notificationPreferences,
roles,
services,
serviceInstances,
+24
View File
@@ -12,6 +12,7 @@ import { eq, sql } from "drizzle-orm";
import { db } from "./index";
import {
users,
notificationPreferences,
roles,
services,
serviceInstances,
@@ -148,6 +149,29 @@ async function main() {
console.log(`users: ${userRows.length} seeded`);
// Re-fetch canonical user ids for assignment references.
const userRows2 = await db.select().from(users);
// Per-user notification preferences: email on, SMS off until opted in.
const prefRows: (typeof notificationPreferences.$inferInsert)[] = userRows2.map(
(u) => ({
userId: u.id,
emailEnabled: true,
smsEnabled: false,
smsConsentAt: null,
smsConsentSource: null,
smsConsentIp: null,
reminderLeadDays: 7,
quietHoursStart: "21:00",
quietHoursEnd: "08:00",
digestOnly: false,
}),
);
for (const p of prefRows) {
await db
.insert(notificationPreferences)
.values(p)
.onConflictDoNothing({ target: notificationPreferences.userId });
}
console.log(`notification_preferences: ${prefRows.length} seeded`);
/* 6. Assignments — one confirmed volunteer per slot (round-robin) */
const volunteers = userRows2.filter((u) => u.systemRole === "volunteer");
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from "vitest";
import { buildConsent, phoneChanged, resetConsent } from "./consent";
describe("phoneChanged (B2 consent reset on number change)", () => {
it("is true when the number changes", () => {
expect(phoneChanged("+15551230001", "+15551230002")).toBe(true);
});
it("is false when the number is unchanged", () => {
expect(phoneChanged("+15551230001", "+15551230001")).toBe(false);
});
it("detects a first-time add (null -> number)", () => {
expect(phoneChanged(null, "+15551230001")).toBe(true);
expect(phoneChanged("+15551230001", null)).toBe(true);
});
});
describe("buildConsent (B2 opt-in populates consent fields)", () => {
const at = new Date("2026-11-18T12:00:00.000Z");
it("enables SMS and records timestamp, source, and IP", () => {
expect(buildConsent("web_signup", "+15550000000", at)).toEqual({
smsEnabled: true,
smsConsentAt: at,
smsConsentSource: "web_signup",
smsConsentIp: "+15550000000",
});
});
it("records admin_import with a null IP when none is available", () => {
expect(buildConsent("admin_import", null, at).smsConsentSource).toBe(
"admin_import",
);
});
});
describe("resetConsent (B2 clears consent)", () => {
it("disables SMS and clears all evidence", () => {
expect(resetConsent()).toEqual({
smsEnabled: false,
smsConsentAt: null,
smsConsentSource: null,
smsConsentIp: null,
});
});
});
+62
View File
@@ -0,0 +1,62 @@
/**
* SMS consent rule (BUILD-PLAN unit B2). Pure — no DB, no Next.js — so the
* TCPA-relevant rule is auditable and unit-tested in isolation. The DB wrappers
* in `src/db/profile.ts` call these.
*
* Two rules:
* 1. Consent is bound to a specific phone number (TCPA). If the number
* changes, the old consent no longer applies and must be cleared
* (`phoneChanged` drives the reset in `updateProfile`).
* 2. An opt-in records explicit evidence: timestamp, source, and IP
* (`buildConsent`).
*/
import type { SmsConsentSource } from "@/db/schema";
/** The consent fields on a `notification_preferences` row, in both states. */
export type ConsentFields = {
smsEnabled: boolean;
smsConsentAt: Date | null;
smsConsentSource: SmsConsentSource | null;
smsConsentIp: string | null;
};
/**
* Did the phone number change? Compares the current stored number against the
* proposed one. `null` (no number) and `""` are treated as distinct so a
* first-time add is detected. This is the predicate `updateProfile` uses to
* decide whether to reset consent.
*/
export function phoneChanged(current: string | null, next: string | null): boolean {
return (current ?? "") !== (next ?? "");
}
/**
* The consent fields written on opt-in: SMS enabled, with the timestamp,
* source, and IP that constitute TCPA evidence. `at` is injectable for tests.
*/
export function buildConsent(
source: SmsConsentSource,
ip: string | null,
at: Date = new Date(),
): ConsentFields {
return {
smsEnabled: true,
smsConsentAt: at,
smsConsentSource: source,
smsConsentIp: ip,
};
}
/**
* The consent fields in the pre-opt-in state: SMS disabled, no evidence. Used
* when the phone number changes (the prior consent no longer covers it).
*/
export function resetConsent(): ConsentFields {
return {
smsEnabled: false,
smsConsentAt: null,
smsConsentSource: null,
smsConsentIp: null,
};
}