diff --git a/.agent/PROGRESS.md b/.agent/PROGRESS.md index 2dfd291..817244d 100644 --- a/.agent/PROGRESS.md +++ b/.agent/PROGRESS.md @@ -164,3 +164,34 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e - The transition rule lives in one pure, auditable place (`nextUserStatus`); the DB wrappers call it, so the rule and the code cannot drift. **Next: B2 — profile + notification prefs + SMS consent capture.** + +--- + +## B2 — Profile + notification prefs + SMS consent capture — DONE 2026-11-18 + +**Scope (from BUILD-PLAN.md):** profile update, `notification_preferences` table, SMS consent capture (timestamp, source, IP). + +**Delivered:** +- `src/db/schema.ts` — `notification_preferences` table (ARCHITECTURE §4.76): `user_id` PK→`users.id` (ON DELETE cascade), `email_enabled` (default true), `sms_enabled` (default false), `sms_consent_at`/`sms_consent_source`/`sms_consent_ip` (TCPA evidence), `reminder_lead_days` (default 7), `quiet_hours_start/end` ("21:00"/"08:00"), `digest_only` (default false). `SMS_CONSENT_SOURCES` enum (`web_signup` | `paper_form` | `admin_import`). +- `src/domain/consent.ts` — the pure TCPA rule. `phoneChanged(current, next)` (consent is bound to a number — drives the reset), `buildConsent(source, ip, at)` (opt-in evidence), `resetConsent()` (pre-opt-in state). +- `src/db/profile.ts` — DB wrappers: `updateProfile` (updates provided fields only; resets consent when the phone changes), `setSmsConsent` (opt-in populates consent fields), `getProfile`. `upsertPrefs` handles the one-to-one row. +- `src/app/api/dev/profile/route.ts` — PATCH `/api/dev/profile` (update) + POST `/api/dev/profile` (consent). +- `src/domain/consent.test.ts` — 6 tests named after the rules. +- `src/db/seed.ts` — per-user prefs row (email on, SMS off) for every seeded user. +- Migration `drizzle/0002_fearless_doctor_spectrum.sql`. + +**Verification (all exit 0):** +- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**30** total, +6 for B2) · `pnpm build` ✓ +- `pnpm db:migrate` ✓ → `pnpm db:seed` ✓ (31 prefs rows, idempotent) +- Runtime smoke test against live app + Postgres on :5433: + - opt-in `web_signup` from `192.168.1.100` → `sms_enabled=true`, `sms_consent_at/source/ip` populated ✓ + - change phone → consent reset (`sms_enabled=false`, evidence cleared) ✓ + - change a non-phone field → consent UNCHANGED ✓ + - invalid consent source → 400 ✓ + +**Decisions:** +- **Partial update, not replace.** The PATCH handler builds the patch from only the fields present in the body. A naive `{ phoneE164: body.phoneE164 ?? null }` would null the phone on every PATCH that omits it (and, since `null !== undefined`, `updateProfile` would treat that as a phone change and reset consent). This is the subtle trap this unit guards against. +- **No `one()` relation for the PK-FK column.** Drizzle 0.45.4's `one()` helper types `fields`/`references` as a tuple of non-PK columns; a column that is *both* PK and FK (`notification_preferences.user_id`) fails the typecheck. The table, FK, and all B2 code work without the relation (profile.ts queries both tables directly). Add the eager-load relation later once a working pattern exists. +- **Seed re-fetches canonical ids.** Same idempotency lesson as A2: `userRows` get fresh UUIDs each run, so prefs are seeded from the re-fetched `userRows2` ids (the assignments code already did this). + +**Next: B3 — catalog taxonomy.** diff --git a/drizzle/0002_fearless_doctor_spectrum.sql b/drizzle/0002_fearless_doctor_spectrum.sql new file mode 100644 index 0000000..49c14a2 --- /dev/null +++ b/drizzle/0002_fearless_doctor_spectrum.sql @@ -0,0 +1,14 @@ +CREATE TABLE "notification_preferences" ( + "user_id" text PRIMARY KEY NOT NULL, + "email_enabled" boolean DEFAULT true NOT NULL, + "sms_enabled" boolean DEFAULT false NOT NULL, + "sms_consent_at" timestamp with time zone, + "sms_consent_source" text, + "sms_consent_ip" text, + "reminder_lead_days" integer DEFAULT 7 NOT NULL, + "quiet_hours_start" text DEFAULT '21:00' NOT NULL, + "quiet_hours_end" text DEFAULT '08:00' NOT NULL, + "digest_only" boolean DEFAULT false NOT NULL +); +--> statement-breakpoint +ALTER TABLE "notification_preferences" ADD CONSTRAINT "notification_preferences_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action; \ No newline at end of file diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json new file mode 100644 index 0000000..67e2c4a --- /dev/null +++ b/drizzle/meta/0002_snapshot.json @@ -0,0 +1,943 @@ +{ + "id": "816e4e64-4974-4ecb-8b55-f68f145012f0", + "prevId": "1e717016-7d25-4a4e-8baa-729772a89ddd", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.assignments": { + "name": "assignments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slot_id": { + "name": "slot_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'proposed'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "responded_at": { + "name": "responded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "decline_reason": { + "name": "decline_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "confirmed_via": { + "name": "confirmed_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_count": { + "name": "reminder_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "uq_active_assignment": { + "name": "uq_active_assignment", + "columns": [ + { + "expression": "slot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"assignments\".\"status\" IN ('proposed','confirmed','completed')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "assignments_user_idx": { + "name": "assignments_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "assignments_slot_id_slots_id_fk": { + "name": "assignments_slot_id_slots_id_fk", + "tableFrom": "assignments", + "tableTo": "slots", + "columnsFrom": [ + "slot_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assignments_user_id_users_id_fk": { + "name": "assignments_user_id_users_id_fk", + "tableFrom": "assignments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.notification_preferences": { + "name": "notification_preferences", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email_enabled": { + "name": "email_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "sms_enabled": { + "name": "sms_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sms_consent_at": { + "name": "sms_consent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sms_consent_source": { + "name": "sms_consent_source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sms_consent_ip": { + "name": "sms_consent_ip", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_lead_days": { + "name": "reminder_lead_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 7 + }, + "quiet_hours_start": { + "name": "quiet_hours_start", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'21:00'" + }, + "quiet_hours_end": { + "name": "quiet_hours_end", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'08:00'" + }, + "digest_only": { + "name": "digest_only", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": {}, + "foreignKeys": { + "notification_preferences_user_id_users_id_fk": { + "name": "notification_preferences_user_id_users_id_fk", + "tableFrom": "notification_preferences", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.roles": { + "name": "roles", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color_hex": { + "name": "color_hex", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "call_time_offset_minutes": { + "name": "call_time_offset_minutes", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "requires_certification": { + "name": "requires_certification", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "default_headcount": { + "name": "default_headcount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "roles_slug_idx": { + "name": "roles_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "roles_slug_unique": { + "name": "roles_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.service_instances": { + "name": "service_instances", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_id": { + "name": "service_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "occurs_on": { + "name": "occurs_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "is_special": { + "name": "is_special", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "title_override": { + "name": "title_override", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_by": { + "name": "published_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "si_service_starts_at_idx": { + "name": "si_service_starts_at_idx", + "columns": [ + { + "expression": "service_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_occurs_on_idx": { + "name": "si_occurs_on_idx", + "columns": [ + { + "expression": "occurs_on", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_status_idx": { + "name": "si_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "service_instances_service_id_services_id_fk": { + "name": "service_instances_service_id_services_id_fk", + "tableFrom": "service_instances", + "tableTo": "services", + "columnsFrom": [ + "service_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.services": { + "name": "services", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "rrule": { + "name": "rrule", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_time_local": { + "name": "start_time_local", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_minutes": { + "name": "duration_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 75 + }, + "doors_open_minutes_before": { + "name": "doors_open_minutes_before", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "services_active_idx": { + "name": "services_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "services_name_unique": { + "name": "services_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slots": { + "name": "slots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_instance_id": { + "name": "service_instance_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slot_index": { + "name": "slot_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "call_time": { + "name": "call_time", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "slot_note": { + "name": "slot_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_trainee_slot": { + "name": "is_trainee_slot", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "paired_with_user_id": { + "name": "paired_with_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "slots_instance_role_idx": { + "name": "slots_instance_role_idx", + "columns": [ + { + "expression": "service_instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "role_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "slot_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slots_status_idx": { + "name": "slots_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slots_service_instance_id_service_instances_id_fk": { + "name": "slots_service_instance_id_service_instances_id_fk", + "tableFrom": "slots", + "tableTo": "service_instances", + "columnsFrom": [ + "service_instance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slots_role_id_roles_id_fk": { + "name": "slots_role_id_roles_id_fk", + "tableFrom": "slots", + "tableTo": "roles", + "columnsFrom": [ + "role_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "slots_paired_with_user_id_users_id_fk": { + "name": "slots_paired_with_user_id_users_id_fk", + "tableFrom": "slots", + "tableTo": "users", + "columnsFrom": [ + "paired_with_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chk_slots_single_parent": { + "name": "chk_slots_single_parent", + "value": "(service_instance_id IS NOT NULL) <> (event_id IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phone_e164": { + "name": "phone_e164", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "system_role": { + "name": "system_role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'volunteer'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending_approval'" + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "emergency_contact": { + "name": "emergency_contact", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_by": { + "name": "approved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_at": { + "name": "approved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_served_at": { + "name": "last_served_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reliability_score": { + "name": "reliability_score", + "type": "numeric(5, 2)", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "deactivated_at": { + "name": "deactivated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "users_email_lower_idx": { + "name": "users_email_lower_idx", + "columns": [ + { + "expression": "lower(\"email\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_status_idx": { + "name": "users_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_system_role_idx": { + "name": "users_system_role_idx", + "columns": [ + { + "expression": "system_role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 0627e79..18d9d73 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1794941123648, "tag": "0001_fluffy_vivisector", "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1794959606685, + "tag": "0002_fearless_doctor_spectrum", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/api/dev/profile/route.ts b/src/app/api/dev/profile/route.ts new file mode 100644 index 0000000..eb41ef6 --- /dev/null +++ b/src/app/api/dev/profile/route.ts @@ -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, + }); + } +}; diff --git a/src/db/profile.ts b/src/db/profile.ts new file mode 100644 index 0000000..c473bdb --- /dev/null +++ b/src/db/profile.ts @@ -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, +): 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 }; +} diff --git a/src/db/schema.ts b/src/db/schema.ts index 576503c..d540ba7 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -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, diff --git a/src/db/seed.ts b/src/db/seed.ts index 8a213d3..8aa56f7 100644 --- a/src/db/seed.ts +++ b/src/db/seed.ts @@ -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"); diff --git a/src/domain/consent.test.ts b/src/domain/consent.test.ts new file mode 100644 index 0000000..7a40e9e --- /dev/null +++ b/src/domain/consent.test.ts @@ -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, + }); + }); +}); diff --git a/src/domain/consent.ts b/src/domain/consent.ts new file mode 100644 index 0000000..8adb2fa --- /dev/null +++ b/src/domain/consent.ts @@ -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, + }; +}