All files / services/rrm inbound.service.ts

98.61% Statements 71/72
100% Branches 41/41
100% Functions 7/7
98.55% Lines 68/69

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                                                                                                            1x     1x     1x                                                                                               1x                 17x 42x                             1x                                                                                                               49x                   49x                                         9x                   9x                                         9x         9x       6x         9x                     9x                                                   23x 22x 22x 22x 20x   2x                     49x   49x 2x                                         47x                         47x 12x                         35x 49x 49x 1x                                               34x 34x 34x         5x 1x 1x 1x   4x 2x 2x 2x   2x     29x 29x   29x 29x 12x 1x           11x 2x       2x 2x       9x   9x             9x 9x             17x 3x     14x       14x 2x                                                       12x 12x                                                         12x         12x 12x    
/**
 * Inbound WhatsApp routing for the RRM programme (F-21, RRM Phase 1).
 *
 * The webhook applies no `phone_number_id` filter of its own (every message on
 * the WABA lands in the ordinary WhatsApp inbox regardless of which number it
 * was sent to). The route decides whether a message arrived on the marketing
 * number and, if so, hands it here. Everything below assumes that gate has
 * already passed — this module does not re-check `phoneNumberId`.
 *
 * Two rules shape this file:
 *
 *  1. NEVER LOSE A TAP-IN. Someone who messages `wa.me/91996337…` without
 *     going through the landing-page form (P1-4.6) still becomes a prospect —
 *     through the SAME guard rails the form and the CSV import use
 *     (`resolveOrRejectProspectByPhone`), so a number the import would have
 *     refused cannot walk in through WhatsApp either.
 *  2. NEVER WRITE THE MESSAGE. The audit event this module appends carries a
 *     wamid and nothing else — never the phone, never the text. Meta's id is
 *     reproducible evidence (it can be looked up against the Cloud API later);
 *     the words cannot be un-said if this table is ever exported.
 *
 * `RRM_EVENT_TYPES` has no `inbound_message` entry, and this module's schema
 * is frozen — it does not own migrations. `message_received` is the type
 * already in the enum for exactly this signal: `ramp.routes.ts` and
 * `metrics.routes.ts` already SELECT `count(...) where type = 'message_received'`
 * to compute reply-rate and ramp-gate numbers. Nothing in the codebase wrote
 * that type before this file — this handler is what completes it, not a
 * workaround.
 */
 
import { and, eq, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import { PartnersDal } from "../../dal/partners/partners.dal";
import { RrmEventsDal } from "../../dal/rrm/events.dal";
import type { RrmActorContext } from "../../dal/rrm/prospects.dal";
import {
	DuplicateProspectError,
	RrmProspectsDal,
} from "../../dal/rrm/prospects.dal";
import * as schema from "../../db/schema";
import type { RrmProspect } from "../../db/schema/rrm";
import { logger } from "../../lib/logger";
import { detectOptOut, normaliseForMatching } from "../../lib/rrm/optout";
import {
	type EngagementContext,
	tryEngageReferral,
} from "../partners/engagement.service";
import {
	type ProspectRejectReason,
	resolveOrRejectProspectByPhone,
	toProspectPhoneNorm,
} from "./prospect-resolver.service";
import { onProspectOptedOut, onProspectReplied } from "./scheduler.service";
 
const EVENTS = schema.rrmProspectEvents;
 
/** The event type this module reads/writes for idempotency and for the ramp/metrics reply count. */
const INBOUND_EVENT_TYPE = "message_received" as const;
 
/** The stage transition an inbound message on the marketing number justifies. */
const REPLIED_ACTOR: RrmActorContext = {
	actorType: "system",
	reason: "inbound_message",
};
 
export type RrmInboundContext = {
	db: DrizzleD1Database<typeof schema>;
	/**
	 * Needed only to run the ladder's branch triggers — cancelling pending
	 * steps and sending the acknowledgement both go through the gateway.
	 * Omit it and the reply is still recorded; the ladder just is not told.
	 */
	env?: CloudflareBindings;
	/** Injectable clock. Defaults to now. */
	now?: Date;
	/**
	 * Passed straight through to the referral branch. Injected here rather than
	 * imported there so the service that decides WHETHER to acknowledge never
	 * needs to know how to send — and so a unit test can assert a state
	 * transition without a WhatsApp client.
	 */
	acknowledge?: EngagementContext["acknowledge"];
};
 
export type RrmInboundInput = {
	/** wa_id digits, e.g. `"919876543210"` — no leading `+`. */
	from: string;
	/** Meta's message id. The ONLY thing the audit event and dedupe key on. */
	wamid: string;
	/** The WhatsApp contact's profile name, if Meta sent one. */
	contactName?: string;
	/** The phone_number_id the message arrived on. Routing already happened
	 * in the caller; this is carried through for logging/interface parity
	 * only and is not re-checked here. */
	phoneNumberId: string;
	/** The text body, when the message has one. Decides whether an UNKNOWN sender is a partner. */
	text?: string;
};
 
/**
 * The business runs ONE WhatsApp number (owner decision, 2026-08-28): it
 * serves login OTPs, homeowner notifications and the partner programme.
 * So "a message arrived on the marketing number" no longer means "a
 * partner wrote to us" — it could be anyone. A KNOWN prospect is matched by
 * phone regardless of text; an UNKNOWN sender becomes a prospect only if
 * their first message is one of the openers the partner page prefills
 * (or a close paraphrase). Everything else stays an ordinary conversation.
 */
const PARTNER_OPENER_PATTERNS: readonly RegExp[] = [
	/partner programme/i,
	/partner program\b/i,
	/contact to refer/i,
	/పార్ట్‌నర్ ప్రోగ్రామ్/,
	/రిఫర్ చేయాలి/,
];
 
export function looksLikePartnerMessage(text: string | undefined): boolean {
	if (!text) return false;
	return PARTNER_OPENER_PATTERNS.some((re) => re.test(text));
}
 
/**
 * The way back from STOP, and the only one there is.
 *
 * Nothing else in the codebase ever sets `partners.notify_whatsapp` back to
 * true — no admin route, no partner-app toggle — so without this a partner who
 * replied STOP is silent forever short of a hand edit in Drizzle Studio. START
 * is the convention every WhatsApp user already knows, and it costs a set.
 *
 * Matched on the WHOLE normalised message, not as a substring: "start" re-opens
 * the channel, "start the work next month" is an ordinary message that happens
 * to begin with the word.
 */
const PARTNER_OPT_IN_WORDS = new Set(["start", "unstop", "resume"]);
 
export type RrmInboundOutcome =
	/** This wamid was already processed — Meta redelivered the webhook. */
	| { outcome: "duplicate" }
	/** A prospect owns this number and has opted out. Nothing was written. */
	| { outcome: "suppressed" }
	/** The prospect (existing or newly created) was moved to `replied` — or
	 * was already further along, in which case only the audit event landed. */
	| { outcome: "replied"; prospectId: string }
	/** They asked us to stop. DNC is set and the ladder is cancelled. */
	| { outcome: "opted_out"; prospectId: string }
	/** `resolveOrRejectProspectByPhone` refused the number, or it did not
	 * normalise at all. Nothing was written. */
	| { outcome: "rejected"; reason: ProspectRejectReason }
	/** Unknown sender whose message is not a partner opener — not ours to enrol. */
	| { outcome: "ignored"; reason: "not_partner_message" }
	/**
	 * The message carried one of our referral codes. A HOMEOWNER, not a
	 * recruitment prospect — nothing in the RRM funnel was touched.
	 *
	 * `engaged` is TRUE only when this message is what moved the referral. A
	 * homeowner's second, third and fourth message all match the same live
	 * referral and land here too (see `engageByPhone`), so a caller that
	 * announces the engagement — `whatsapp.routes.ts` does — has to be able to
	 * tell the transition from the traffic after it, or the partner is sent the
	 * same "they messaged us" template once per message.
	 */
	| { outcome: "referral_engaged"; referralId: string; engaged: boolean }
	/**
	 * A PARTNER asked us to stop. `partners.notify_whatsapp` is off and nothing
	 * else was touched — see the guard for why this is not `opted_out`.
	 */
	| { outcome: "partner_opted_out"; partnerId: string }
	/**
	 * A partner wrote to us about something else — or asked for their updates
	 * back with START, which is applied before this is returned. Recorded in
	 * the ordinary WhatsApp inbox by the caller (which stores every inbound
	 * before routing); nothing further here to do but say so.
	 */
	| { outcome: "partner_message"; partnerId: string };
 
/**
 * Has this exact inbound message already been recorded?
 *
 * Scoped to `message_received` rather than "any event with this wamid": that
 * is the only event type this module writes, so it is also the only place a
 * redelivered webhook could have left a trace. `json_extract` rather than a
 * dedicated column — the payload is deliberately the only place a wamid is
 * stored, and adding an indexed column for one lookup is a schema change this
 * module does not own.
 */
async function wasAlreadyProcessed(
	db: DrizzleD1Database<typeof schema>,
	wamid: string,
): Promise<boolean> {
	const rows = await db
		.select({ id: EVENTS.id })
		.from(EVENTS)
		.where(
			and(
				eq(EVENTS.type, INBOUND_EVENT_TYPE),
				sql`json_extract(${EVENTS.payload}, '$.wamid') = ${wamid}`,
			),
		)
		.limit(1);
	return rows.length > 0;
}
 
/**
 * Is this the prospect's first ever inbound message?
 *
 * Counted off `message_received` — the event this module writes for every
 * inbound — and NOT off `replied_at`. The stage rule is forward-only, and
 * `submission.service.ts` puts every go-form sign-up straight at `interested`,
 * which outranks `replied`; `setStage("replied")` is refused for them and the
 * stamp never lands. Reading the stamp would answer "yes, first" to every
 * message such a prospect ever sends, and re-send the acknowledgement each
 * time. The same is true of `joined`, which does not stamp it either.
 *
 * Runs BEFORE this message's own event is appended, so a first message sees
 * zero rows. Same `EVENTS` shape as `wasAlreadyProcessed` above.
 */
async function isFirstInbound(
	db: DrizzleD1Database<typeof schema>,
	prospectId: string,
): Promise<boolean> {
	const rows = await db
		.select({ id: EVENTS.id })
		.from(EVENTS)
		.where(
			and(
				eq(EVENTS.prospectId, prospectId),
				eq(EVENTS.type, INBOUND_EVENT_TYPE),
			),
		)
		.limit(1);
	return rows.length === 0;
}
 
/**
 * Moves an existing (non-suppressed) prospect to `replied` and appends the
 * wamid audit event.
 *
 * Two sequential DAL calls, not one batch: `setStage` owns its own
 * prospect-row + `stage_changed` atomic write (spec §0 rule 7), and this
 * module does not own `prospects.dal.ts` to fold a third statement into it. A
 * crash between the two leaves a `replied` prospect with the reply event
 * still to land — Meta's redelivery (or the person's next message) closes
 * that gap, and nothing here has moved backwards in the meantime.
 */
async function markReplied(
	prospects: RrmProspectsDal,
	events: RrmEventsDal,
	prospect: RrmProspect,
	wamid: string,
	now: Date,
): Promise<RrmInboundOutcome> {
	const staged = await prospects.setStage(
		prospect.id,
		"replied",
		REPLIED_ACTOR,
	);
	if (!staged.changed) {
		// Not an error: a prospect already at `interested` or beyond stays
		// there (forward-only), but the reply still has to be on the record —
		// it is what the ramp gate and "Replied?" column read.
		logger.info(
			`[RRM inbound] stage left at ${staged.prospect.stage} (${staged.reason}) for prospect ${prospect.id}`,
		);
	}
 
	await events.append({
		prospectId: prospect.id,
		type: INBOUND_EVENT_TYPE,
		// Attributed to the prospect, not `system`: they sent this message.
		// Matches the convention in dal/rrm/events.dal.test.ts.
		actorType: "prospect",
		channel: "whatsapp",
		payload: { wamid },
		occurredAt: now,
	});
 
	return { outcome: "replied", prospectId: prospect.id };
}
 
/**
 * Routes one inbound WhatsApp message on the marketing number into the RRM
 * funnel. Idempotent on `wamid`; every branch that resolves to a real
 * prospect writes exactly one `message_received` event carrying it.
 */
/**
 * Tell the ladder what happened. Isolated on purpose: a failure here must
 * never lose the inbound message itself, which is already recorded by the
 * time we get called.
 */
async function notifyLadder(
	ctx: RrmInboundContext,
	prospectId: string,
	what: "replied" | "opted_out",
	now: Date,
	/**
	 * Their first ever inbound — no prior `message_received` event. It decides
	 * whether the ladder sends the sign-up acknowledgement to someone who has no
	 * run, which is every organic sign-up off the go form. Deliberately not read
	 * off `replied_at`: see `isFirstInbound`.
	 */
	firstReply = false,
): Promise<void> {
	if (!ctx.env) return;
	try {
		const branchCtx = { db: ctx.db, env: ctx.env, now };
		if (what === "replied") {
			await onProspectReplied(branchCtx, prospectId, { firstReply });
		} else {
			await onProspectOptedOut(branchCtx, prospectId);
		}
	} catch (err) {
		console.error(`[RRM_INBOUND] ladder ${what} trigger failed:`, err);
	}
}
 
export async function handleRrmInbound(
	ctx: RrmInboundContext,
	input: RrmInboundInput,
): Promise<RrmInboundOutcome> {
	const now = ctx.now ?? new Date();
 
	if (await wasAlreadyProcessed(ctx.db, input.wamid)) {
		return { outcome: "duplicate" };
	}
 
	// ── The referral branch, and why it sits HERE ────────────────────────
	//
	// Before `findByPhone` below, not merely before the unknown-sender gate
	// further down. The tempting placement is next to `looksLikePartnerMessage`
	// — homeowners are strangers, so guard the enrolment path — and it misses
	// the case that matters: a homeowner whose number is ALREADY an
	// `rrm_prospects` row, imported from a CP list or belonging to a partner
	// buying their own home. That number matches on phone, gets `markReplied`,
	// and advances the RECRUITMENT funnel while the referral it was actually
	// about stays `forwarded` forever.
	//
	// So the code is read first, off the message text, before the phone is
	// consulted at all. On a match we return immediately: nothing below runs,
	// so a homeowner can never reach `resolveOrRejectProspectByPhone` or
	// `prospects.create` and be enrolled as a recruitment target.
	//
	// On no match we fall through completely unchanged — every pre-existing
	// test in this file still passing is the signal that that is true.
	const engagement = await tryEngageReferral(
		{ db: ctx.db, now, acknowledge: ctx.acknowledge },
		{
			from: input.from,
			fromPhoneNorm:
				toProspectPhoneNorm(
					input.from.startsWith("+") ? input.from : `+${input.from}`,
				) ?? "",
			wamid: input.wamid,
			text: input.text,
			contactName: input.contactName,
		},
	);
	if (engagement.matched) {
		return {
			outcome: "referral_engaged",
			referralId: engagement.referralId,
			engaged: engagement.engaged,
		};
	}
 
	// wa_id arrives as bare digits ('91XXXXXXXXXX'). `toProspectPhoneNorm` /
	// the resolver both parse via libphonenumber-js's default-country mode,
	// which only reads a bare country-code prefix correctly when it is told
	// there IS one — hence the '+'. This is the repo's one phone normaliser
	// (`@interioring/utils/validation/phone`, via prospect-resolver.service.ts);
	// nothing new is being parsed here.
	const rawPhone = input.from.startsWith("+") ? input.from : `+${input.from}`;
	const phoneNorm = toProspectPhoneNorm(rawPhone);
	if (!phoneNorm) {
		return { outcome: "rejected", reason: "invalid_phone" };
	}
 
	// ── The partner guard, and why it is not `markDnc` ───────────────────
	//
	// Every notification we send a partner ends "Reply STOP to stop these
	// updates", so partners WILL reply STOP — to the one number that also
	// carries their login code. Below this point the recruitment path treats an
	// opt-out as `markDnc`, and `verify-otp` refuses to send a login code to a
	// do-not-contact number: a partner who used the word we told them to use
	// would be locked out of their own account and their own money.
	//
	// So a partner's STOP turns off exactly one thing — the notifications they
	// asked us to stop — and a partner is NEVER enrolled as a recruitment
	// prospect. Placed after the referral branch (a homeowner is not a partner)
	// and before every prospect read, because those reads are what it exists to
	// prevent.
	//
	// ponytail: `detectOptOut` is the recruitment detector, so a bare "no" in
	// answer to an ops question also turns updates off. Deliberate — it is the
	// same word list a partner was told to use, and a wrongly-quiet channel is
	// recoverable by replying START (below), which is also the only way back:
	// nothing else in the codebase ever sets `notify_whatsapp` to true again.
	// Give partners their own narrower list if that turns out to bite.
	const partners = new PartnersDal(ctx.db);
	const partner = await partners.findByPhone(phoneNorm);
	if (partner) {
		// Checked BEFORE the opt-out detector, not after: the detector owns a
		// long multilingual phrase list that this one word must never fall
		// into, and a partner asking for their updates back is the one message
		// we cannot afford to read as another refusal.
		if (PARTNER_OPT_IN_WORDS.has(normaliseForMatching(input.text))) {
			await partners.update(partner.id, { notifyWhatsapp: true });
			logger.info(`[RRM inbound] partner ${partner.id} opted back in`);
			return { outcome: "partner_message", partnerId: partner.id };
		}
		if (detectOptOut(input.text).kind === "opt_out") {
			await partners.update(partner.id, { notifyWhatsapp: false });
			logger.info(`[RRM inbound] partner ${partner.id} opted out of updates`);
			return { outcome: "partner_opted_out", partnerId: partner.id };
		}
		return { outcome: "partner_message", partnerId: partner.id };
	}
 
	const prospects = new RrmProspectsDal(ctx.db);
	const events = new RrmEventsDal(ctx.db);
 
	const existing = await prospects.findByPhone(phoneNorm);
	if (existing) {
		if (existing.doNotContact) {
			return { outcome: "suppressed" };
		}
 
		// An unambiguous opt-out stops everything before anything else runs.
		// `detectOptOut` deliberately routes "not now" to review rather than
		// suppression, so a later-please never becomes a permanent block.
		if (detectOptOut(input.text).kind === "opt_out") {
			await prospects.markDnc(existing.id, "opt_out", {
				actorType: "prospect",
				channel: "whatsapp",
			});
			await notifyLadder(ctx, existing.id, "opted_out", now);
			return { outcome: "opted_out", prospectId: existing.id };
		}
 
		// Asked before `markReplied` appends this message's own event.
		const firstReply = await isFirstInbound(ctx.db, existing.id);
 
		const result = await markReplied(
			prospects,
			events,
			existing,
			input.wamid,
			now,
		);
		await notifyLadder(ctx, existing.id, "replied", now, firstReply);
		return result;
	}
 
	// No prospect yet: the tap-in-without-the-form path (P1-4.6). The SAME
	// front door the CSV import and the landing-page form use, so a number
	// either of them would refuse cannot become a prospect through WhatsApp.
	// Unknown sender on a shared number: only a partner opener enrols them.
	if (!looksLikePartnerMessage(input.text)) {
		return { outcome: "ignored", reason: "not_partner_message" };
	}
 
	const resolved = await resolveOrRejectProspectByPhone(rawPhone, {
		db: ctx.db,
	});
 
	if (resolved.outcome === "reject") {
		return { outcome: "rejected", reason: resolved.reason };
	}
 
	/* v8 ignore start -- defensive: findByPhone above already returned
	 * undefined for this phoneNorm, so the resolver's own existing-prospect
	 * lookup cannot find one moments later outside of a concurrent-request
	 * race. Handled the same way as the direct lookup rather than risking
	 * a duplicate-phone insert below. */
	if (resolved.outcome === "existing") {
		if (resolved.prospect.doNotContact) {
			return { outcome: "suppressed" };
		}
		return await markReplied(
			prospects,
			events,
			resolved.prospect,
			input.wamid,
			now,
		);
	}
	/* v8 ignore stop */
 
	// resolved.outcome === "create": genuinely new. The creation's own event
	// IS the wamid audit event (`eventType`/`eventPayload` override the DAL's
	// default `imported` event) — a tap-in was never imported, and this way
	// the branch writes exactly one event for "a message arrived" rather than
	// one for "imported" plus a second for the reply.
	let created: RrmProspect;
	try {
		created = await prospects.create({
			phoneNorm: resolved.phoneNorm,
			source: "organic",
			consentBasis: "user_initiated",
			name: input.contactName?.trim() || null,
			consentAt: now,
			consentEvidence: { wamid: input.wamid },
			eventType: INBOUND_EVENT_TYPE,
			eventPayload: { wamid: input.wamid },
			actor: { actorType: "prospect", channel: "whatsapp" },
		});
	} catch (err) {
		/* v8 ignore start -- defensive: only reachable if a second delivery for
		 * this same brand-new number wins the unique-phone insert between our
		 * `findByPhone` miss above and this call. `DuplicateProspectError`'s own
		 * message embeds the phone, so it must never reach the caller's error
		 * log; the person's next message finds the row via `findByPhone` above
		 * and routes normally, so nothing is lost by stopping here. */
		if (err instanceof DuplicateProspectError) {
			return { outcome: "duplicate" };
		}
		throw err;
		/* v8 ignore stop */
	}
 
	// A freshly created prospect always starts at `sourced` (no `stage` is
	// passed to `create()` above), and `sourced` → `replied` is always
	// forward, so this move — unlike the one in `markReplied` — cannot be
	// refused by the forward-only rule. No `staged.changed` check needed.
	await prospects.setStage(created.id, "replied", REPLIED_ACTOR);
 
	// Always a first reply: the row did not exist a moment ago. Hardcoded rather
	// than asked — `create()` above already wrote this message's
	// `message_received` event, so `isFirstInbound` would now answer "no".
	await notifyLadder(ctx, created.id, "replied", now, true);
	return { outcome: "replied", prospectId: created.id };
}