All files / dal/rrm prospects.dal.ts

99.17% Statements 120/121
98.34% Branches 119/121
100% Functions 21/21
100% Lines 107/107

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                          26x 26x 26x 26x                               26x     26x   26x 26x                                                                                                                                                                                                                               9x   9x         1x 1x 1x         4x 4x 4x           5x       837x         4490x         4490x       588x         588x                     4x 3x         3x       13x 13x 13x 13x   13x         1x 1x         13x       4x 4x         13x   13x       13x   13x                   13x         13x           67x 67x   66x 66x 66x   67x                                                     67x                         66x       8x   7x 7x 7x 7x 7x 7x 7x 7x 1x       1x     7x   6x 6x 6x                               1268x           1267x 2x 2x         1265x 1265x 19x     1246x 1246x                                                 1246x                                       10x 9x 9x   9x                     9x 7x                             9x                                   9x                   7x   4x 3x 3x   3x                                       3x                             6x       6x                                                   8x 7x   7x                                                                                                                                     7x                                                 3x   2x                     2631x 2631x 2625x                         1246x   20x         18x   35x   1x   3x       1169x                     1338x                        
import type { SQL } from "drizzle-orm";
import { and, asc, count, desc, eq, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../../db/schema";
import type {
	NewRrmProspect,
	NewRrmProspectEvent,
	RrmProspect,
	RrmProspectEvent,
} from "../../db/schema/rrm";
import { generateId } from "../../lib/ids";
import { decideStage, type RrmStage } from "../../lib/rrm/stage";
 
const PROSPECTS = schema.rrmProspects;
const EVENTS = schema.rrmProspectEvents;
const SUBMISSIONS = schema.rrmSubmissions;
const TASKS = schema.rrmTasks;
 
// Derived from the schema rather than re-imported from enums.ts: the table is
// the single source of truth, so a column whose enum changes breaks callers at
// compile time instead of at insert time.
export type RrmTier = NonNullable<RrmProspect["tier"]>;
export type RrmSource = RrmProspect["source"];
export type RrmFirmType = NonNullable<RrmProspect["firmType"]>;
export type RrmLocale = RrmProspect["locale"];
export type RrmLocaleSource = NonNullable<RrmProspect["localeSource"]>;
export type RrmDncReason = NonNullable<RrmProspect["dncReason"]>;
export type RrmConsentBasis = RrmProspect["consentBasis"];
export type RrmEventType = RrmProspectEvent["type"];
export type RrmActorType = RrmProspectEvent["actorType"];
export type RrmChannel = NonNullable<RrmProspectEvent["channel"]>;
 
const DAY_MS = 86_400_000;
 
/** Spec §5.1: operator triage to `not_now` parks the prospect for 60 days. */
export const NOT_NOW_SNOOZE_DAYS = 60;
 
const DEFAULT_PAGE_SIZE = 50;
const MAX_PAGE_SIZE = 200;
 
/**
 * Who caused a write, and whether the prospect themselves is the trigger.
 *
 * `actorType` is NOT NULL on the event table on purpose — every row in the
 * audit trail has to be attributable — so it is required here too.
 */
export type RrmActorContext = {
	actorType: RrmActorType;
	actorId?: string | null;
	/** Free text stored on the event, e.g. "operator triage". Never PII. */
	reason?: string;
	channel?: RrmChannel;
	/**
	 * True when the trigger is an inbound message from that person. The ONLY
	 * thing that releases `do_not_contact` — see `decideStage()`.
	 */
	viaInbound?: boolean;
	/** Used when a stage move to `do_not_contact` is routed through `markDnc`. */
	dncReason?: RrmDncReason;
};
 
export type CreateProspectInput = {
	/** '91XXXXXXXXXX', digits only. Normalise before calling. */
	phoneNorm: string;
	source: RrmSource;
	name?: string | null;
	firmName?: string | null;
	firmType?: RrmFirmType | null;
	tier?: RrmTier | null;
	microMarkets?: string[] | null;
	sourceDetail?: RrmProspect["sourceDetail"];
	stage?: RrmStage;
	locale?: RrmLocale;
	localeSource?: RrmLocaleSource | null;
	ownerId?: string | null;
	closingsPerMonth?: number | null;
	notes?: string | null;
	consentBasis?: RrmConsentBasis;
	consentVersion?: string | null;
	consentAt?: Date | null;
	consentEvidence?: RrmProspect["consentEvidence"];
	/**
	 * Defaults to `imported`. A landing-page signup passes `form_submitted`
	 * instead so the funnel does not count an organic arrival as a list import.
	 */
	eventType?: RrmEventType;
	eventPayload?: Record<string, unknown>;
	actor?: RrmActorContext;
};
 
/**
 * `visitToken` is here rather than on `create` because the token is
 * HMAC(prospectId) — it cannot exist until the id does. Writing `null` is how a
 * leaked link is revoked, which is the reason the column is stored at all.
 */
export type UpdateProspectPatch = {
	name?: string | null;
	firmName?: string | null;
	tier?: RrmTier | null;
	ownerId?: string | null;
	notes?: string | null;
	locale?: RrmLocale;
	visitToken?: string | null;
	/**
	 * Lane E only. Written by `POST /prospects/outreach-basis` and nothing
	 * else — an import must never set these, or a scraped list becomes an
	 * outreach campaign by omission, which is exactly what `none` defaults
	 * against.
	 */
	consentBasis?: RrmProspect["consentBasis"];
	consentAt?: Date | null;
	consentVersion?: string | null;
	consentEvidence?: RrmProspect["consentEvidence"];
};
 
export type ListProspectsFilters = {
	stage?: RrmStage;
	tier?: RrmTier;
	/**
	 * `organic` = came to us through the landing page. This is the filter the
	 * Sign-ups screen lives on — a warm inbound buried among 455 scraped names
	 * is the one person the operator most needs to see.
	 */
	source?: RrmSource;
	microMarket?: string;
	/** Substring over name, firm name and phone. Pass digits for a phone search. */
	q?: string;
	page?: number;
	limit?: number;
};
 
export type ListProspectsResult = {
	items: RrmProspect[];
	total: number;
};
 
/**
 * Deliberately returns the rejection instead of a boolean. A transition that is
 * dropped for a reason nobody recorded is indistinguishable from a bug at 2am,
 * so the caller always has something to log.
 */
export type SetStageResult =
	| { changed: true; prospect: RrmProspect; from: RrmStage; to: RrmStage }
	| {
			changed: false;
			prospect: RrmProspect;
			reason: "unchanged" | "backwards" | "absorbing";
	  };
 
export class ProspectNotFoundError extends Error {
	code = "NOT_FOUND";
	constructor() {
		super("Prospect not found");
	}
}
 
export class DuplicateProspectError extends Error {
	code = "DUPLICATE_PHONE";
	constructor(public phoneNorm: string) {
		super(`A prospect already exists for ${phoneNorm}`);
	}
}
 
export class InvalidSnoozeError extends Error {
	code = "INVALID_SNOOZE";
	constructor(public days: number) {
		super(`Snooze must be a positive number of days, got ${days}`);
	}
}
 
/** `%` and `_` are LIKE wildcards; a search for "50%" must not match everything. */
function escapeLike(value: string): string {
	return value.replace(/[\\%_]/g, "\\$&");
}
 
export class RrmProspectsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	// ── Reads ────────────────────────────────────────────────────────────────
 
	async findById(id: string): Promise<RrmProspect | undefined> {
		const rows = await this.db
			.select()
			.from(PROSPECTS)
			.where(eq(PROSPECTS.id, id))
			.limit(1);
		return rows[0];
	}
 
	async findByPhone(phoneNorm: string): Promise<RrmProspect | undefined> {
		const rows = await this.db
			.select()
			.from(PROSPECTS)
			.where(eq(PROSPECTS.phoneNorm, phoneNorm))
			.limit(1);
		return rows[0];
	}
 
	/**
	 * Looks up the stored token only. Signature verification lives in
	 * lib/rrm/token.ts and stays out of the DAL — the DAL has no secret, and
	 * matching the stored value is the half that makes revocation work.
	 */
	async findByVisitToken(token: string): Promise<RrmProspect | undefined> {
		// The column is nullable and uniquely indexed, so an empty token would
		// otherwise match nothing slowly instead of failing fast.
		if (!token) return undefined;
		const rows = await this.db
			.select()
			.from(PROSPECTS)
			.where(eq(PROSPECTS.visitToken, token))
			.limit(1);
		return rows[0];
	}
 
	async list(filters: ListProspectsFilters = {}): Promise<ListProspectsResult> {
		const conditions: SQL[] = [];
		if (filters.stage) conditions.push(eq(PROSPECTS.stage, filters.stage));
		if (filters.tier) conditions.push(eq(PROSPECTS.tier, filters.tier));
		Iif (filters.source) conditions.push(eq(PROSPECTS.source, filters.source));
 
		if (filters.microMarket) {
			// `micro_markets` is a JSON array. Matching the quoted element rather
			// than the bare name keeps "Kokapet" from matching "Kokapet Extension",
			// and a LIKE on one small text column beats a json_each() join that D1
			// would have to plan per row.
			const needle = `%"${escapeLike(filters.microMarket)}"%`;
			conditions.push(
				sql`${PROSPECTS.microMarkets} LIKE ${needle} ESCAPE '\\'`,
			);
		}
 
		if (filters.q) {
			// One pre-parenthesised OR rather than drizzle's `or()`, whose return is
			// typed `SQL | undefined` and would need a guard for a case that cannot
			// happen with a fixed argument list.
			const needle = `%${escapeLike(filters.q)}%`;
			conditions.push(
				sql`(${PROSPECTS.name} LIKE ${needle} ESCAPE '\\' OR ${PROSPECTS.firmName} LIKE ${needle} ESCAPE '\\' OR ${PROSPECTS.phoneNorm} LIKE ${needle} ESCAPE '\\')`,
			);
		}
 
		const where = conditions.length > 0 ? and(...conditions) : undefined;
 
		const limit = Math.min(
			Math.max(Math.trunc(filters.limit ?? DEFAULT_PAGE_SIZE), 1),
			MAX_PAGE_SIZE,
		);
		const page = Math.max(Math.trunc(filters.page ?? 1), 1);
 
		const items = await this.db
			.select()
			.from(PROSPECTS)
			.where(where)
			// `id` breaks ties so page 2 cannot repeat a row from page 1 when a
			// whole import shares a `date_created` second.
			.orderBy(desc(PROSPECTS.dateCreated), asc(PROSPECTS.id))
			.limit(limit)
			.offset((page - 1) * limit);
 
		const totals = await this.db
			.select({ value: count() })
			.from(PROSPECTS)
			.where(where);
 
		return { items, total: totals[0]?.value ?? 0 };
	}
 
	// ── Writes ───────────────────────────────────────────────────────────────
 
	async create(input: CreateProspectInput): Promise<RrmProspect> {
		const existing = await this.findByPhone(input.phoneNorm);
		if (existing) throw new DuplicateProspectError(input.phoneNorm);
 
		const id = generateId();
		const now = new Date();
		const stage: RrmStage = input.stage ?? "sourced";
 
		const values: NewRrmProspect = {
			id,
			phoneNorm: input.phoneNorm,
			source: input.source,
			name: input.name ?? null,
			firmName: input.firmName ?? null,
			firmType: input.firmType ?? null,
			tier: input.tier ?? null,
			microMarkets: input.microMarkets ?? null,
			sourceDetail: input.sourceDetail ?? null,
			stage,
			stageChangedAt: now,
			ownerId: input.ownerId ?? null,
			locale: input.locale ?? "en",
			localeSource: input.localeSource ?? null,
			// An imported row must land on the value that BLOCKS sending: nobody
			// has agreed to anything yet.
			consentBasis: input.consentBasis ?? "none",
			consentVersion: input.consentVersion ?? null,
			consentAt: input.consentAt ?? null,
			consentEvidence: input.consentEvidence ?? null,
			closingsPerMonth: input.closingsPerMonth ?? null,
			notes: input.notes ?? null,
			dateCreated: now,
			dateUpdated: now,
		};
 
		await this.db.batch([
			this.db.insert(PROSPECTS).values(values),
			this.db.insert(EVENTS).values([
				this.eventRow({
					prospectId: id,
					type: input.eventType ?? "imported",
					payload: input.eventPayload ?? { source: input.source, stage },
					actor: input.actor ?? { actorType: "system" },
					occurredAt: now,
				}),
			]),
		]);
 
		return await this.mustFind(id);
	}
 
	async update(id: string, patch: UpdateProspectPatch): Promise<RrmProspect> {
		const current = await this.mustFind(id);
 
		const sets: Partial<NewRrmProspect> = {};
		if (patch.name !== undefined) sets.name = patch.name;
		if (patch.firmName !== undefined) sets.firmName = patch.firmName;
		if (patch.tier !== undefined) sets.tier = patch.tier;
		if (patch.ownerId !== undefined) sets.ownerId = patch.ownerId;
		if (patch.notes !== undefined) sets.notes = patch.notes;
		if (patch.visitToken !== undefined) sets.visitToken = patch.visitToken;
		if (patch.locale !== undefined) {
			sets.locale = patch.locale;
			// Someone typed this in, so it outranks anything `detectLocale()` later
			// infers from a message. Losing that distinction is how a person who
			// asked for Telugu gets sent English again.
			sets.localeSource = "stated";
		}
 
		if (Object.keys(sets).length === 0) return current;
 
		sets.dateUpdated = new Date();
		await this.db.update(PROSPECTS).set(sets).where(eq(PROSPECTS.id, id));
		return await this.mustFind(id);
	}
 
	/**
	 * The only way a stage moves.
	 *
	 * Spec §0 invariant 7: "No stage is set by a UI click that isn't also an
	 * event row." The row write and the `stage_changed` event therefore go out in
	 * one `db.batch` — the funnel is built from events, so a stage without its
	 * event is a hole in the only number this programme is measured on.
	 */
	async setStage(
		id: string,
		proposed: RrmStage,
		ctx: RrmActorContext,
	): Promise<SetStageResult> {
		const current = await this.mustFind(id);
 
		// `do_not_contact` is not merely a stage: it is the flag the send gate
		// reads. Writing the stage alone would leave the gateway happily messaging
		// someone marked opted out, so this routes to the method that sets both
		// rather than trusting every caller to remember.
		if (proposed === "do_not_contact") {
			const prospect = await this.markDnc(id, ctx.dncReason ?? "manual", ctx);
			return current.stage === "do_not_contact"
				? { changed: false, prospect, reason: "unchanged" }
				: { changed: true, prospect, from: current.stage, to: proposed };
		}
 
		const decision = decideStage(current.stage, proposed, ctx.viaInbound);
		if (!decision.change) {
			return { changed: false, prospect: current, reason: decision.reason };
		}
 
		const now = new Date();
		await this.db.batch([
			this.db
				.update(PROSPECTS)
				.set({
					stage: decision.stage,
					stageChangedAt: now,
					dateUpdated: now,
					...this.stageTimestamps(decision.stage, current, now),
				})
				.where(eq(PROSPECTS.id, id)),
			this.db.insert(EVENTS).values([
				this.eventRow({
					prospectId: id,
					type: "stage_changed",
					payload: {
						from: current.stage,
						to: decision.stage,
						reason: ctx.reason ?? null,
					},
					actor: ctx,
					occurredAt: now,
				}),
			]),
		]);
 
		return {
			changed: true,
			prospect: await this.mustFind(id),
			from: current.stage,
			to: decision.stage,
		};
	}
 
	/**
	 * Suppression. Deliberately does NOT go through `decideStage()`: the
	 * forward-only rule exists to protect funnel progress, and applying it here
	 * would let a re-reported opt-out be dropped as "unchanged" while the
	 * `do_not_contact` flag stayed clear. Stopping messages must never be
	 * conditional on the ordering rule.
	 */
	async markDnc(
		id: string,
		reason: RrmDncReason,
		ctx: RrmActorContext,
	): Promise<RrmProspect> {
		const current = await this.mustFind(id);
		const now = new Date();
		const stageMoved = current.stage !== "do_not_contact";
 
		const events: NewRrmProspectEvent[] = [
			this.eventRow({
				prospectId: id,
				type: "opted_out",
				payload: { reason, from: current.stage },
				actor: ctx,
				occurredAt: now,
			}),
		];
		// The funnel counts `stage_changed`, so a real move needs its own row even
		// though `opted_out` already records the cause.
		if (stageMoved) {
			events.push(
				this.eventRow({
					prospectId: id,
					type: "stage_changed",
					payload: {
						from: current.stage,
						to: "do_not_contact",
						reason,
					},
					actor: ctx,
					occurredAt: now,
				}),
			);
		}
 
		await this.db.batch([
			this.db
				.update(PROSPECTS)
				.set({
					doNotContact: true,
					// Latest reason wins — an opt-out that escalates to hostile should
					// read as hostile — but `dnc_at` keeps the moment they first said
					// stop, which is the date a complaint would be measured against.
					dncReason: reason,
					dncAt: current.dncAt ?? now,
					stage: "do_not_contact",
					stageChangedAt: stageMoved ? now : current.stageChangedAt,
					dateUpdated: now,
				})
				.where(eq(PROSPECTS.id, id)),
			this.db.insert(EVENTS).values(events),
		]);
 
		return await this.mustFind(id);
	}
 
	async snooze(
		id: string,
		days: number,
		ctx: RrmActorContext,
	): Promise<RrmProspect> {
		// A negative or NaN snooze silently un-snoozes the prospect and the next
		// scheduler tick messages them again. Fail loudly instead.
		if (!Number.isFinite(days) || days <= 0) throw new InvalidSnoozeError(days);
 
		const current = await this.mustFind(id);
		const now = new Date();
		const until = new Date(now.getTime() + days * DAY_MS);
 
		await this.db.batch([
			this.db
				.update(PROSPECTS)
				.set({ snoozeUntil: until, dateUpdated: now })
				.where(eq(PROSPECTS.id, id)),
			this.db.insert(EVENTS).values([
				this.eventRow({
					prospectId: id,
					type: "snoozed",
					payload: {
						days,
						until: until.toISOString(),
						stage: current.stage,
					},
					actor: ctx,
					occurredAt: now,
				}),
			]),
		]);
 
		return await this.mustFind(id);
	}
 
	/**
	 * `first_visit_at = MIN(existing, incoming)`, as one statement.
	 *
	 * NOT "if null then set". Capture retries in-process and Cloudflare delivers
	 * out of order, so the second call to arrive is routinely the earlier event;
	 * a null-check would freeze the later timestamp and make time-to-first-visit
	 * wrong in the one direction that flatters the numbers. Doing it in SQL also
	 * removes the read-modify-write race between two concurrent captures.
	 *
	 * @param occurredAtMs epoch MILLISECONDS, stamped by the Go worker.
	 */
	async recordFirstVisit(id: string, occurredAtMs: number): Promise<void> {
		const seconds = Math.floor(occurredAtMs / 1000);
		// Unqualified column name on purpose: SQLite's UPDATE ... SET expression
		// resolves against the row being updated, and drizzle would otherwise
		// render a table-qualified reference here.
		await this.db
			.update(PROSPECTS)
			.set({
				firstVisitAt: sql`MIN(COALESCE(first_visit_at, ${seconds}), ${seconds})`,
				dateUpdated: new Date(),
			})
			.where(eq(PROSPECTS.id, id));
	}
 
	/**
	 * DPDP erasure (spec §9.3). Nulls every column except the four that have to
	 * survive: `id` and `phone_norm` so the number stays suppressed through a
	 * re-import, `do_not_contact` + `dnc_reason` so the gate keeps refusing, and
	 * `date_created` so the retention clock is still auditable.
	 *
	 * This method only ever touches `rrm_prospects` — it does not know about
	 * `rrm_submissions`, `rrm_tasks`, `rrm_visits` or `wa_messages`. The
	 * `/erase` ROUTE (`routes/admin/rrm/prospects.routes.ts`) is what
	 * orchestrates a full DPDP erasure: it calls this method, then
	 * `RrmSubmissionsDal.scrubForProspect()` and `scrubTaskNotes()` below, then
	 * `RrmSuppressionDal.suppress()`, so one request clears every store this
	 * campaign currently has a scrub for. `rrm_visits` and the message bodies
	 * in `wa_messages` are NOT covered by any of the three and remain a known
	 * gap (loose-ends review D3) — no DAL owns that erasure yet.
	 */
	async erase(id: string, ctx?: RrmActorContext): Promise<void> {
		const current = await this.mustFind(id);
		const now = new Date();
 
		await this.db.batch([
			this.db
				.update(PROSPECTS)
				.set({
					name: null,
					firmName: null,
					firmType: null,
					tier: null,
					microMarkets: null,
					// The listing URL and scrape metadata are personal data; `source`
					// itself is a bare category ("maps"), is NOT NULL, and falsifying it
					// would be worse than keeping it.
					sourceDetail: null,
					snoozeUntil: null,
					ownerId: null,
					localeSource: null,
					visitToken: null,
					consentVersion: null,
					consentAt: null,
					consentEvidence: null,
					firstContactedAt: null,
					lastContactedAt: null,
					repliedAt: null,
					firstVisitAt: null,
					interestedAt: null,
					intentStatedAt: null,
					closingsPerMonth: null,
					notes: null,
					// NOT NULL columns cannot be nulled, so they go to the values that
					// block every outbound path.
					stage: "do_not_contact",
					stageChangedAt: now,
					locale: "en",
					consentBasis: "none",
					doNotContact: true,
					dncReason: "deletion_request",
					dncAt: current.dncAt ?? now,
					dateUpdated: now,
				})
				.where(eq(PROSPECTS.id, id)),
			this.db.insert(EVENTS).values([
				this.eventRow({
					prospectId: id,
					type: "deleted",
					// No names, no phone, no prior stage detail: copying the erased
					// values into an append-only table would defeat the erasure.
					payload: { reason: "deletion_request" },
					actor: ctx ?? { actorType: "operator" },
					occurredAt: now,
				}),
			]),
		]);
	}
 
	/**
	 * DPDP erasure, the tasks half (review D3). `rrm_tasks` has no DAL of its
	 * own — `services/rrm/submission.service.ts` writes rows and
	 * `routes/admin/rrm/tasks.routes.ts` reads/completes them directly against
	 * `schema.rrmTasks` — so this lives here, on the DAL that owns the
	 * prospect the tasks belong to. Nulls `notes` only: that free-text field is
	 * where a referred contact's name and phone end up (a `confirm_intent`
	 * task's notes quote `rrm_submissions.contact_note` — see that column's
	 * comment in `db/schema/rrm.ts`), and `rrm_tasks` has no other personal-
	 * data column. Called by the `/erase` ROUTE alongside `erase()` and
	 * `RrmSubmissionsDal.scrubForProspect()`.
	 */
	async scrubTaskNotes(prospectId: string): Promise<void> {
		await this.db
			.update(TASKS)
			.set({ notes: null })
			.where(eq(TASKS.prospectId, prospectId));
	}
 
	/**
	 * HARD delete — removes the row, not a scrub. Deliberately different from
	 * `erase()`: DPDP erasure keeps the prospect (nulled, suppressed, still
	 * counted) so the campaign never re-messages that number and the funnel
	 * stays reproducible; this REMOVES it, for test/scraped data that should
	 * never have existed on the board at all (loose-ends review §3.6). It is
	 * the test-data exception, not a second erasure path — nothing else in
	 * this codebase should call it.
	 *
	 * No FK exists between the rrm tables, so the cascade — submissions, tasks,
	 * then the append-only event log, then the prospect — is manual, in one
	 * `db.batch`. Deleting from `rrm_prospect_events` here does not contradict
	 * `RrmEventsDal`'s "no delete, ever" rule: that rule protects the audit
	 * trail from being edited out from under a LIVE prospect, and there is no
	 * prospect left once this batch commits.
	 *
	 * @throws ProspectNotFoundError if the id does not exist.
	 */
	async hardDelete(id: string): Promise<void> {
		await this.mustFind(id);
 
		await this.db.batch([
			this.db.delete(SUBMISSIONS).where(eq(SUBMISSIONS.prospectId, id)),
			this.db.delete(TASKS).where(eq(TASKS.prospectId, id)),
			this.db.delete(EVENTS).where(eq(EVENTS.prospectId, id)),
			this.db.delete(PROSPECTS).where(eq(PROSPECTS.id, id)),
		]);
	}
 
	// ── Internals ────────────────────────────────────────────────────────────
 
	private async mustFind(id: string): Promise<RrmProspect> {
		const row = await this.findById(id);
		if (!row) throw new ProspectNotFoundError();
		return row;
	}
 
	/**
	 * The timestamp columns a stage entry stamps (spec §5.1). Each "first" column
	 * is written once: a prospect who replies, goes quiet and replies again kept
	 * the same `replied_at`, so cohort timings stay comparable.
	 */
	private stageTimestamps(
		to: RrmStage,
		current: RrmProspect,
		now: Date,
	): Partial<NewRrmProspect> {
		switch (to) {
			case "contacted":
				return {
					firstContactedAt: current.firstContactedAt ?? now,
					lastContactedAt: now,
				};
			case "replied":
				return { repliedAt: current.repliedAt ?? now };
			case "interested":
				return { interestedAt: current.interestedAt ?? now };
			case "intent_stated":
				return { intentStatedAt: current.intentStatedAt ?? now };
			case "not_now":
				return {
					snoozeUntil: new Date(now.getTime() + NOT_NOW_SNOOZE_DAYS * DAY_MS),
				};
			default:
				return {};
		}
	}
 
	private eventRow(input: {
		prospectId: string;
		type: RrmEventType;
		payload: Record<string, unknown> | null;
		actor: RrmActorContext;
		occurredAt: Date;
	}): NewRrmProspectEvent {
		return {
			id: generateId(),
			prospectId: input.prospectId,
			type: input.type,
			channel: input.actor.channel ?? null,
			payload: input.payload,
			actorType: input.actor.actorType,
			actorId: input.actor.actorId ?? null,
			occurredAt: input.occurredAt,
		};
	}
}