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:
@@ -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 };
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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");
|
||||
|
||||
Reference in New Issue
Block a user