All files / routes/admin/rrm prospects.routes.ts

99.56% Statements 229/230
96.73% Branches 89/92
100% Functions 28/28
99.54% Lines 218/219

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921                                                                                                                                                        3x   3x     3x     3x               168x                   21x                                                                                                 4x                                   2x                                       4x 4x 4x 3x 3x 7x 7x           2x       4x                                                 9x 9x 5x                                 9x 5x 2x     2x 1x             3x 3x 3x 3x 3x   3x                   3x                           3x                     3x   3x                               3x                           3x           3x                       3x               45x 45x 16x 16x   16x       39x 39x   1x           7x 10x                 36x 2x 34x 1x     33x 32x                       23x               3x 7x 7x 7x       7x   7x                   5x           2x         3x 7x 7x 7x   7x     7x 1x     6x 6x 6x 1x   5x 1x               4x             2x   5x                                                   3x 7x 7x 7x 7x         7x 7x 7x   7x 7x   7x 6x 6x 1x 1x     5x 1x 1x       4x 1x 1x     3x                           3x                         3x     5x             2x                     3x 8x 8x 8x 8x   8x 8x   8x 9x 9x           7x 6x       1x     2x 1x   1x 1x         5x   3x         3x 10x 10x 10x 10x   10x 10x   9x               9x               10x                   1x         3x 6x 6x 6x 5x 1x   2x 1x   5x         3x 6x 6x 6x 6x         6x                             4x 1x           3x   2x                     3x 5x 5x 5x   5x                       4x 2x   2x   3x                                       3x 8x 8x 8x 1x       7x   7x                               3x 1x               2x   6x         3x 2x 2x 2x 2x 2x         1x   1x         3x 3x 3x 3x 3x 3x         1x   2x                             3x 3x 3x 3x 3x   3x 3x             2x 2x 2x 2x   2x   1x                           3x 4x 4x 4x 4x         4x   3x 3x 1x     2x 2x   1x   1x   3x          
/**
 * RRM prospect admin API (F-21).
 *
 * Mounted by the RRM sub-router, which is itself mounted under `/api/admin`
 * where `contextMiddleware` and `requirePlatformAdmin` already run. Nothing in
 * this file re-applies a guard: a second `requirePlatformAdmin` would be dead
 * weight that quietly diverges from the parent's the first time the parent
 * changes.
 *
 * The response shapes here are fixed by `apps/portal/src/lib/api/admin/rrm.ts`.
 * TypeScript cannot check a shape across the wire, so every route ends in an
 * explicit serialiser rather than spreading a Drizzle row: an added column
 * would otherwise leak (`visit_token` is a live credential, `consent_evidence`
 * carries message bodies) simply by existing.
 */
 
import type { Context } from "hono";
import { Hono } from "hono";
import { z } from "zod";
import type { Dal } from "../../../dal";
import {
	InvalidSnoozeError,
	ProspectNotFoundError,
	RrmSubmissionsDal,
} from "../../../dal/rrm";
import type { RrmActorContext } from "../../../dal/rrm/prospects.dal";
import { getDb } from "../../../db";
import type { WaConversation, WaMessage } from "../../../db/schema";
import {
	RRM_DNC_REASONS,
	RRM_LOCALES,
	RRM_SOURCES,
	RRM_STAGES,
	RRM_TIERS,
} from "../../../db/schema/enums";
import type {
	RrmProspect,
	RrmProspectEvent,
	RrmSubmission,
} from "../../../db/schema/rrm";
import {
	AppError,
	ConfigurationError,
	ConflictError,
	ForbiddenError,
	NotFoundError,
	ValidationError,
} from "../../../lib/errors";
import { logger } from "../../../lib/logger";
import { buildPaginationMeta, getPagination } from "../../../lib/pagination";
import {
	handleError,
	success,
	successWithPagination,
} from "../../../lib/response";
import { isSuperAdminFromRoles } from "../../../lib/role-cache";
import type { Services } from "../../../services";
import {
	type RrmOverridableGate,
	sendToProspect,
} from "../../../services/rrm/gateway.service";
import {
	ImportHeaderError,
	importProspects,
} from "../../../services/rrm/prospect-import.service";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
	};
};
 
const prospects = new Hono<Env>();
 
const TWENTY_FOUR_HOURS_MS = 24 * 60 * 60 * 1000;
 
/** Enough to render a whole recruitment conversation; these threads are short. */
const MESSAGE_PAGE_SIZE = 200;
 
/** The real list is ~455 rows; anything larger is a wrong file, not a big one. */
const MAX_IMPORT_BYTES = 5 * 1024 * 1024;
 
// ─────────────────────────────────────────────────────────────────────────────
// Serialisation
// ─────────────────────────────────────────────────────────────────────────────
 
/** Drizzle hands back `Date` (epoch seconds in D1); the contract is ISO. */
function iso(value: Date | null): string | null {
	return value === null ? null : value.toISOString();
}
 
/**
 * Exported so `signups.routes.ts` can build the `RrmSignup` shape
 * (`RrmProspectDto & { submissionCount, latestSubmission }`) from the exact
 * same serialisation the Prospects screen already renders, rather than a
 * second hand-maintained projection that drifts from this one.
 */
export function serializeProspect(row: RrmProspect) {
	return {
		id: row.id,
		phoneNorm: row.phoneNorm,
		name: row.name,
		firmName: row.firmName,
		tier: row.tier,
		microMarkets: row.microMarkets ?? null,
		stage: row.stage,
		stageChangedAt: row.stageChangedAt.toISOString(),
		locale: row.locale,
		localeSource: row.localeSource,
		doNotContact: row.doNotContact,
		dncReason: row.dncReason,
		source: row.source,
		// Whole object, not a three-field subset: "where did you get my number?"
		// has to be answerable from this one payload (spec §14).
		sourceDetail: row.sourceDetail ?? null,
		ownerId: row.ownerId,
		snoozeUntil: iso(row.snoozeUntil),
		firstContactedAt: iso(row.firstContactedAt),
		lastContactedAt: iso(row.lastContactedAt),
		repliedAt: iso(row.repliedAt),
		firstVisitAt: iso(row.firstVisitAt),
		interestedAt: iso(row.interestedAt),
		intentStatedAt: iso(row.intentStatedAt),
		closingsPerMonth: row.closingsPerMonth,
		notes: row.notes,
		// The DPDP evidence trail (P1-1.9). `consentBasis` is what the send
		// gate reads — genuinely, since gateway.service.ts calls
		// `canSendBusinessInitiated`; it did not when this comment was written; `consentVersion` + `consentAt` are what an operator
		// shows a regulator. Sign-ups exist because someone ticked a box —
		// the screen that lists them must be able to say which box, and when.
		consentBasis: row.consentBasis,
		consentVersion: row.consentVersion ?? null,
		consentAt: iso(row.consentAt),
		dateCreated: row.dateCreated.toISOString(),
	};
}
 
/**
 * The `RrmSubmissionSummary` contract — a fixed, minimal projection of
 * `rrm_submissions`. Deliberately excludes the realtor's OWN `name` /
 * `firmName` / `phoneNorm` (that is the prospect row) and the free-text
 * `contactNote` (operator-only, surfaced via `rrm_tasks` instead); only the
 * REFERRED contact's structured fields travel in this summary.
 *
 * Exported for `signups.routes.ts`, same reasoning as `serializeProspect`.
 */
export function serializeSubmissionSummary(row: RrmSubmission) {
	return {
		id: row.id,
		cta: row.cta,
		contactName: row.contactName,
		contactPhoneNorm: row.contactPhoneNorm,
		contactProject: row.contactProject,
		contactConsentAsserted: row.contactConsentAsserted,
		sourceDetail: row.sourceDetail,
		duplicateOfSubmissionId: row.duplicateOfSubmissionId,
		// The column is nullable in the schema (an older or malformed
		// submission may predate locale detection); the contract is not, so a
		// missing value falls back to the same default a new prospect gets.
		locale: row.locale ?? "en",
		dateCreated: row.dateCreated.toISOString(),
	};
}
 
function serializeEvent(row: RrmProspectEvent) {
	return {
		id: row.id,
		prospectId: row.prospectId,
		type: row.type,
		channel: row.channel,
		payload: row.payload ?? null,
		actorType: row.actorType,
		actorId: row.actorId,
		occurredAt: row.occurredAt.toISOString(),
	};
}
 
/**
 * `wa_messages.content` is a JSON blob whose shape follows the message type —
 * `{body}` for text, `{caption}` for media, `{buttonReply}` for interactive.
 * Anything with no recognised text field falls back to the raw value so the
 * timeline shows *something* rather than an empty bubble an operator would
 * read as a bug.
 */
function messageBody(row: WaMessage): string {
	try {
		const parsed: unknown = JSON.parse(row.content);
		if (parsed !== null && typeof parsed === "object") {
			const record = parsed as Record<string, unknown>;
			for (const key of ["body", "text", "caption"]) {
				const value = record[key];
				if (typeof value === "string" && value.length > 0) return value;
			}
		}
	} catch {
		// Not JSON. Older rows stored the text directly.
	}
	return row.content;
}
 
function serializeMessage(row: WaMessage) {
	return {
		id: row.id,
		direction: row.direction,
		body: messageBody(row),
		templateName: row.templateName,
		status: row.status,
		stepKey: row.stepKey,
		dateCreated: row.dateCreated.toISOString(),
	};
}
 
// ─────────────────────────────────────────────────────────────────────────────
// The 24-hour window
// ─────────────────────────────────────────────────────────────────────────────
 
/**
 * `rrm_prospects.phone_norm` is digits-only ("91XXXXXXXXXX"). WhatsApp webhooks
 * write conversations in that same form, but a row created from an E.164
 * recipient carries a leading "+". Both spellings are the same person, so a
 * miss is retried rather than reported as "never contacted".
 */
async function findConversation(
	dal: Dal,
	phoneNorm: string,
): Promise<WaConversation | undefined> {
	const direct = await dal.waConversations.findByPhoneNumber(phoneNorm);
	if (direct) return direct;
	return await dal.waConversations.findByPhoneNumber(`+${phoneNorm}`);
}
 
/**
 * The window has exactly ONE source of truth:
 * `wa_conversations.last_customer_message_at`, judged by
 * `ConversationService.isWindowOpen` — the same call the send path makes.
 *
 * There is deliberately no `rrm_windows` table. A second store for "can we
 * still reply freely" drifts from the first the moment one of them misses a
 * webhook, and the failure is silent in the direction that sends messages we
 * are not allowed to send.
 */
function windowExpiresAt(
	conversation: WaConversation | undefined,
	services: Services,
): string | null {
	if (!conversation) return null;
	if (!services.waConversation.isWindowOpen(conversation)) return null;
	const last = conversation.lastCustomerMessageAt;
	// Unreachable — `isWindowOpen` is false without it — but the null check is
	// what makes that provable rather than assumed.
	if (!last) return null;
	return new Date(last.getTime() + TWENTY_FOUR_HOURS_MS).toISOString();
}
 
// ─────────────────────────────────────────────────────────────────────────────
// Validation
// ─────────────────────────────────────────────────────────────────────────────
 
const stageEnum = z.enum(RRM_STAGES);
const tierEnum = z.enum(RRM_TIERS);
const sourceEnum = z.enum(RRM_SOURCES);
const localeEnum = z.enum(RRM_LOCALES);
const dncReasonEnum = z.enum(RRM_DNC_REASONS);
 
const listQuerySchema = z.object({
	page: z.coerce.number().int().positive().optional(),
	limit: z.coerce.number().int().positive().optional(),
	stage: stageEnum.optional(),
	tier: tierEnum.optional(),
	source: sourceEnum.optional(),
	microMarket: z.string().min(1).max(120).optional(),
	q: z.string().min(1).max(120).optional(),
});
 
const patchSchema = z.object({
	name: z.string().trim().max(200).nullable().optional(),
	firmName: z.string().trim().max(200).nullable().optional(),
	tier: tierEnum.nullable().optional(),
	ownerId: z.string().min(1).nullable().optional(),
	notes: z.string().max(5000).nullable().optional(),
	locale: localeEnum.optional(),
});
 
/**
 * `reason` is required, not optional. Every stage move lands in an append-only
 * event row, and a stage change nobody explained is the thing that cannot be
 * reconstructed afterwards.
 */
const stageSchema = z.object({
	stage: stageEnum,
	reason: z.string().trim().min(1).max(500),
});
 
/**
 * Restricted to the four `rrm_prospects.dnc_reason` values. The portal contract
 * types this `string`, but SQLite does not enforce a text enum — free text here
 * would write a value the send gate has never heard of into the column it
 * checks before every send.
 */
const dncSchema = z.object({ reason: dncReasonEnum });
 
const snoozeSchema = z.object({ days: z.number().int().positive() });
 
/**
 * `ids` capped at 200 — the same order of magnitude as one import batch, and
 * comfortably clear of D1's 100-bound-parameter ceiling since each id is
 * applied one `setStage` call at a time rather than in a single statement.
 * `reason` has a higher floor than the single-prospect `stageSchema`: this
 * moves many rows on one operator action, so "why" earns three characters
 * minimum instead of one.
 */
/**
 * Lane E. The justification is REQUIRED and long enough to be a sentence,
 * because the whole value of this row is that somebody had to write down why —
 * and a 3-character reason is how "we decided this was fine" becomes
 * unreconstructable a year later when someone asks.
 */
const outreachBasisSchema = z.object({
	ids: z.array(z.string().min(1)).min(1).max(200),
	justification: z.string().trim().min(40).max(2000),
	policyVersion: z.string().trim().min(1).max(64),
});
 
/**
 * A forced send names its gates and its reason.
 *
 * `RrmOverridableGate` is the authority on which gates exist — suppression,
 * do-not-contact and consent are absent from it deliberately, so this enum
 * cannot grow to include them without someone editing the gateway's type and
 * reading why they are missing.
 */
const overrideGateEnum = z.enum([
	"halted",
	"frequency",
	"quiet_hours",
] satisfies [RrmOverridableGate, ...RrmOverridableGate[]]);
 
const sendSchema = z.object({
	templateName: z.string().trim().min(1).max(200),
	variables: z.array(z.string().max(1000)).max(10).optional(),
	stepKey: z.string().trim().min(1).max(120).optional(),
	override: z
		.object({
			gates: z.array(overrideGateEnum).min(1),
			reason: z.string().trim().min(20).max(2000),
		})
		.optional(),
});
 
const bulkStageSchema = z.object({
	ids: z.array(z.string().min(1)).min(1).max(200),
	stage: stageEnum,
	reason: z.string().trim().min(3).max(500),
});
 
/** `handleError` has no ZodError branch, so validation failures are named here. */
function parseOrThrow<T>(schema: z.ZodType<T>, value: unknown): T {
	const result = schema.safeParse(value);
	if (result.success) return result.data;
	const detail = result.error.issues
		.map((issue) => `${issue.path.join(".") || "body"}: ${issue.message}`)
		.join("; ");
	throw new ValidationError(detail);
}
 
async function readJson(c: Context<Env>): Promise<unknown> {
	try {
		return await c.req.json();
	} catch {
		throw new ValidationError("Request body must be valid JSON");
	}
}
 
/** Query params arrive as strings; an empty one means "unset", not "invalid". */
function cleanQuery(raw: Record<string, string>): Record<string, string> {
	return Object.fromEntries(
		Object.entries(raw).filter(([, value]) => value !== ""),
	);
}
 
/**
 * DAL and service errors are transport-agnostic on purpose. This is the single
 * place they are given HTTP meaning.
 */
function toHttpError(err: unknown): unknown {
	if (err instanceof ProspectNotFoundError)
		return new NotFoundError("Prospect");
	if (err instanceof InvalidSnoozeError)
		return new ValidationError(err.message);
	// Column names are operator-facing and contain no personal data, so the
	// message can be echoed verbatim — it is the only useful thing to say.
	if (err instanceof ImportHeaderError) return new ValidationError(err.message);
	return err;
}
 
/**
 * `reason` is required, not optional: every write these routes make lands in
 * the append-only event log, and an unexplained one cannot be reconstructed
 * from anywhere else.
 */
function operatorContext(
	user: { id: string } | null,
	reason: string,
): RrmActorContext {
	return { actorType: "operator", actorId: user?.id ?? null, reason };
}
 
// ─────────────────────────────────────────────────────────────────────────────
// Routes
// ─────────────────────────────────────────────────────────────────────────────
 
// GET /api/admin/rrm/prospects
prospects.get("/", async (c) => {
	try {
		const dal = c.get("dal");
		const filters = parseOrThrow(listQuerySchema, cleanQuery(c.req.query()));
		// One normalisation, used for the query AND the meta, so `meta.total`
		// always describes the page that was actually run. Planning has been
		// misled once by a count that did not match the list.
		const { page, limit } = getPagination(filters.page, filters.limit);
 
		const { items, total } = await dal.rrmProspects.list({
			stage: filters.stage,
			tier: filters.tier,
			source: filters.source,
			microMarket: filters.microMarket,
			q: filters.q,
			page,
			limit,
		});
 
		return successWithPagination(
			c,
			items.map(serializeProspect),
			buildPaginationMeta(total, page, limit),
		);
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// POST /api/admin/rrm/prospects/import — multipart CSV
prospects.post("/import", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
 
		const tokenSecret = c.env.RRM_TOKEN_SECRET;
		// Checked before the file is read: an import that writes 455 prospects and
		// cannot mint a single visit link has produced 455 unusable rows.
		if (!tokenSecret) {
			throw new ConfigurationError("RRM_TOKEN_SECRET is not configured");
		}
 
		const form = await c.req.formData();
		const file = form.get("file");
		if (!(file instanceof File)) {
			throw new ValidationError("A CSV file is required in the `file` field");
		}
		if (file.size > MAX_IMPORT_BYTES) {
			throw new ValidationError(
				`CSV exceeds the ${MAX_IMPORT_BYTES / (1024 * 1024)}MB limit`,
			);
		}
 
		// Parsing, dedupe (§5.3) and the batch record all live in the service.
		// `rejects` is returned untouched — `row` is a file LINE number, and any
		// arithmetic here would send an operator to the wrong line of their CSV.
		const result = await importProspects(await file.text(), {
			db: dal.db,
			tokenSecret,
			uploadedBy: user?.id ?? null,
			filename: file.name,
		});
 
		return success(c, result);
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// POST /api/admin/rrm/prospects/outreach-basis
//
// Lane E — record a documented decision to contact publicly listed business
// numbers, so cold outreach is possible WITHOUT relabelling scraped rows as
// having opted in.
//
// `docs/operations/whatsapp-consent.md` §7 always said this would be needed:
// "If the campaign ever needs cold outreach to imported numbers, that is a
// separate decision with a separate legal basis, made deliberately — not
// something an operator can reach by clicking send." This is the deliberate
// act. It is not a send button and it is not a default.
//
// THIS IS NOT CONSENT, and three things in this handler keep that true:
//
//   1. It only ever moves `none` -> `public_listing`. A row carrying a real
//      opt-in is left ALONE — overwriting `user_initiated` with a weaker basis
//      would destroy the evidence that someone actually asked to hear from us,
//      to make a number look the same as its neighbours.
//   2. The justification is stored verbatim against every row it touches,
//      with the operator's id. "Who decided, and why" survives them leaving.
//   3. It writes a `note_added` event per prospect, so the decision is on the
//      timeline an operator reads, not only in a column.
prospects.post("/outreach-basis", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
		Iif (!user?.id) {
			throw new ValidationError(
				"An authenticated operator is required — this decision is recorded against a person",
			);
		}
		const actorId = user.id;
		const body = parseOrThrow(outreachBasisSchema, await readJson(c));
		const now = new Date();
 
		let recorded = 0;
		const skipped: { id: string; reason: string }[] = [];
 
		for (const id of body.ids) {
			const prospect = await dal.rrmProspects.findById(id);
			if (!prospect) {
				skipped.push({ id, reason: "not_found" });
				continue;
			}
			// Never downgrade a real opt-in. See (1) above.
			if (prospect.consentBasis !== "none") {
				skipped.push({ id, reason: `already ${prospect.consentBasis}` });
				continue;
			}
			// A number somebody asked us to stop using is not reachable by
			// deciding it is. Suppression and DNC outrank this entirely.
			if (prospect.doNotContact) {
				skipped.push({ id, reason: "do_not_contact" });
				continue;
			}
 
			await dal.rrmProspects.update(id, {
				consentBasis: "public_listing",
				consentAt: now,
				consentVersion: body.policyVersion,
				consentEvidence: {
					decidedBy: actorId,
					justification: body.justification,
					capturedAt: now.toISOString(),
					...(prospect.sourceDetail?.listingUrl
						? { listingUrl: prospect.sourceDetail.listingUrl }
						: {}),
				},
			});
 
			await dal.rrmEvents.append({
				prospectId: id,
				type: "note_added",
				actorType: "operator",
				actorId,
				payload: {
					kind: "outreach_basis_recorded",
					basis: "public_listing",
					policyVersion: body.policyVersion,
					justification: body.justification,
				},
				occurredAt: now,
			});
			recorded += 1;
		}
 
		return success(c, {
			recorded,
			skipped,
			basis: "public_listing",
			policyVersion: body.policyVersion,
		});
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// POST /api/admin/rrm/prospects/bulk-stage
//
// Loose-ends review §1.4: the "known numbers" send has no bulk action today,
// so an operator moves 20+ prospects to `contacted` one row at a time. This
// reuses `setStage` per id rather than a bulk UPDATE so every move still gets
// its own `stage_changed` event (spec §0 rule 7) and the forward-only /
// absorbing rules still apply row by row.
prospects.post("/bulk-stage", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
		const body = parseOrThrow(bulkStageSchema, await readJson(c));
 
		let moved = 0;
		const skipped: { id: string; reason: string }[] = [];
 
		for (const id of body.ids) {
			try {
				const result = await dal.rrmProspects.setStage(id, body.stage, {
					...operatorContext(user, body.reason),
					...(body.stage === "do_not_contact"
						? { dncReason: "manual" as const }
						: {}),
				});
				if (result.changed) {
					moved += 1;
				} else {
					// DNC/terminal rows land here via "absorbing" / "backwards" —
					// one row's refusal must not abort the rest of the batch.
					skipped.push({ id, reason: result.reason });
				}
			} catch (err) {
				if (err instanceof ProspectNotFoundError) {
					skipped.push({ id, reason: "not_found" });
				} else {
					logger.error(`bulk-stage failed for prospect ${id}:`, err);
					skipped.push({ id, reason: "error" });
				}
			}
		}
 
		return success(c, { moved, skipped });
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// GET /api/admin/rrm/prospects/:id
prospects.get("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const services = c.get("services");
		const id = c.req.param("id");
 
		const prospect = await dal.rrmProspects.findById(id);
		if (!prospect) throw new NotFoundError("Prospect", id);
 
		const [timeline, conversation, submissions] = await Promise.all([
			dal.rrmEvents.timelineFor(id),
			findConversation(dal, prospect.phoneNorm),
			new RrmSubmissionsDal(dal.db).findByProspectId(id),
		]);
 
		// Most prospects have never been messaged. No conversation is the normal
		// state, not a missing record: empty thread, closed window.
		const messages = conversation
			? await dal.waMessages.findByConversationId(
					conversation.id,
					0,
					MESSAGE_PAGE_SIZE,
				)
			: [];
 
		return success(c, {
			prospect: serializeProspect(prospect),
			timeline: timeline.map(serializeEvent),
			messages: messages.map(serializeMessage),
			windowExpiresAt: windowExpiresAt(conversation, services),
			// Review §3.3: a referral's contact details used to exist only as free
			// text in `rrm_tasks.notes`. Newest first, same convention as `timeline`.
			submissions: submissions.map(serializeSubmissionSummary),
		});
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// PATCH /api/admin/rrm/prospects/:id
prospects.patch("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const patch = parseOrThrow(patchSchema, await readJson(c));
		if (Object.keys(patch).length === 0) {
			throw new ValidationError("No fields provided");
		}
		const updated = await dal.rrmProspects.update(c.req.param("id"), patch);
		return success(c, serializeProspect(updated));
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// POST /api/admin/rrm/prospects/:id/stage
prospects.post("/:id/stage", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
		const body = parseOrThrow(stageSchema, await readJson(c));
 
		// `setStage` re-runs the forward-only rule and writes the row and its
		// `stage_changed` event in one batch (spec §0 rule 7). Never write
		// `stage` directly.
		const result = await dal.rrmProspects.setStage(
			c.req.param("id"),
			body.stage,
			{
				...operatorContext(user, body.reason),
				// The DAL routes `do_not_contact` through `markDnc`, which needs an
				// enum reason; the operator's free text stays on the event.
				...(body.stage === "do_not_contact"
					? { dncReason: "manual" as const }
					: {}),
			},
		);
 
		// A refusal is a NORMAL outcome, not an error status. The UI has to be
		// able to say why nothing moved instead of appearing to do nothing.
		if (!result.changed) {
			return success(c, {
				changed: false,
				stage: result.prospect.stage,
				reason: result.reason,
			});
		}
		return success(c, { changed: true, stage: result.prospect.stage });
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// POST /api/admin/rrm/prospects/:id/reply
//
// Review §3.4: "Replied?" used to need a full stage-move — two screens away
// from the Sign-ups row. Same code path as `/stage` (`setStage`, so
// `replied_at` and the `stage_changed` event are written identically), with
// the reason fixed so every one-click reply is attributable to this button
// rather than a hand-typed note.
prospects.post("/:id/reply", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
 
		const result = await dal.rrmProspects.setStage(
			c.req.param("id"),
			"replied",
			{
				...operatorContext(user, "operator_confirmed_reply"),
			},
		);
 
		// Already replied is a harmless double-click, not a conflict — the
		// button's job is already done. Anything else that blocked the move
		// (DNC absorbing it, or a terminal/further-along prospect refusing to
		// go backwards) is a real conflict: there is nothing "updated" to show.
		if (!result.changed && result.reason !== "unchanged") {
			throw new ConflictError(`Cannot mark replied: ${result.reason}`);
		}
		return success(c, serializeProspect(result.prospect));
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// POST /api/admin/rrm/prospects/:id/send
//
// The operator's way to send an RRM template to one prospect.
//
// It exists because there wasn't one. An operator who wanted to message a
// prospect had exactly two options: the inbox reply box, which is free-form
// and only works inside an open 24-hour window; or admin Quick Send, which
// will message any number at all and applies NONE of the RRM gates — not
// suppression, not do-not-contact, not consent, not the caps. The safe path
// did not cover the common case, so the unsafe one was the only one that
// worked.
//
// This routes an operator send through `sendToProspect`, which is the single
// choke point every gate lives behind. `actor.type` is "operator" — the
// scheduled path sends as "system" and cannot override anything, which is the
// whole point of the distinction.
prospects.post("/:id/send", async (c) => {
	try {
		const user = c.get("user");
		if (!user?.id) {
			throw new ValidationError(
				"An authenticated operator is required — a forced send is recorded against a person",
			);
		}
		const body = parseOrThrow(sendSchema, await readJson(c));
 
		const result = await sendToProspect(
			{ db: getDb(c.env.DB), env: c.env },
			{
				prospectId: c.req.param("id"),
				intent: "freeform_or_template",
				templateName: body.templateName,
				variables: body.variables,
				stepKey: body.stepKey,
				actor: { type: "operator", id: user.id },
				override: body.override,
			},
		);
 
		// A blocked send is not a server fault and not a 500 — it is the system
		// answering. 409 with the decision, so the UI can say which gate and
		// offer the override rather than showing "something went wrong".
		if (!result.ok) {
			throw new AppError(
				409,
				`RRM_SEND_${result.decision.toUpperCase()}`,
				result.detail
					? `Send blocked: ${result.decision} (${result.detail})`
					: `Send blocked: ${result.decision}`,
			);
		}
		return success(c, result);
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// POST /api/admin/rrm/prospects/:id/dnc
prospects.post("/:id/dnc", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
		const body = parseOrThrow(dncSchema, await readJson(c));
		const updated = await dal.rrmProspects.markDnc(
			c.req.param("id"),
			body.reason,
			operatorContext(user, body.reason),
		);
		return success(c, serializeProspect(updated));
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// POST /api/admin/rrm/prospects/:id/snooze
prospects.post("/:id/snooze", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
		const body = parseOrThrow(snoozeSchema, await readJson(c));
		const updated = await dal.rrmProspects.snooze(
			c.req.param("id"),
			body.days,
			operatorContext(user, `snoozed ${body.days}d by operator`),
		);
		return success(c, serializeProspect(updated));
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// POST /api/admin/rrm/prospects/:id/erase — DPDP deletion request (spec §9.3)
//
// Orchestrates every store the loose-ends review (D3) found PII surviving in:
// the prospect row, its submissions (realtor's own fields + the referred
// contact's structured details AND `contactNote`), and the free-text notes on
// its `confirm_intent` tasks. `rrm_prospect_events` is deliberately excluded —
// append-only by design, and payloads are ids/enums, not personal data (see
// the PII grep note in the DAL comments). D1 has no cross-table transaction,
// so a failure partway through leaves a partially-scrubbed prospect rather
// than none at all; re-running `/erase` on the same id is safe; every step
// here is idempotent.
prospects.post("/:id/erase", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
		const id = c.req.param("id");
 
		const prospect = await dal.rrmProspects.findById(id);
		if (!prospect) throw new NotFoundError("Prospect", id);
 
		// Suppression FIRST, and by phone. `erase` nulls the prospect row but
		// leaves `rrm_suppression` to its caller, and D1 has no transaction to
		// span the two: if the second half fails, the number must already be the
		// one that is permanently blocked, or a re-import resurrects someone who
		// asked to be forgotten.
		await dal.rrmSuppression.suppress(prospect.phoneNorm, "deletion_request");
		await dal.rrmProspects.erase(id, operatorContext(user, "deletion_request"));
		await new RrmSubmissionsDal(dal.db).scrubForProspect(id);
		await dal.rrmProspects.scrubTaskNotes(id);
 
		return success(c, { erased: true });
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
// DELETE /api/admin/rrm/prospects/:id — HARD delete, super_admin only
//
// For test/scraped data that should never have existed on the board at all
// (loose-ends review §3.6) — NOT the DPDP path. `/erase` keeps the row so the
// campaign never re-messages that number; this removes it entirely, which is
// exactly wrong for a real prospect and exactly right for "Review Agent" /
// "Ravi Referrer" left behind by a test pass. Gated on `super_admin` rather
// than the parent router's `admin`-or-`super_admin` `requirePlatformAdmin`,
// since an irreversible delete is a strictly higher bar than the rest of this
// file.
prospects.delete("/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const user = c.get("user");
		const id = c.req.param("id");
 
		// Belt-and-braces: the parent router's `requirePlatformAdmin` already
		// guarantees a session, but a null user here must fail closed rather
		// than reach `findByUserId` with a meaningless id.
		if (!user) throw new ForbiddenError("Super admin access required");
 
		const roles = await dal.userTenantRoles.findByUserId(user.id);
		if (!isSuperAdminFromRoles(roles)) {
			throw new ForbiddenError("Super admin access required");
		}
 
		const prospect = await dal.rrmProspects.findById(id);
		if (!prospect) throw new NotFoundError("Prospect", id);
 
		await dal.rrmProspects.hardDelete(id);
 
		return c.body(null, 204);
	} catch (err) {
		return handleError(c, toHttpError(err));
	}
});
 
export default prospects;