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

100% Statements 86/86
97.87% Branches 46/47
100% Functions 7/7
100% Lines 81/81

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                            2x 2x 2x                       2x     2x     2x           2x             2x                                                                 20x 19x 19x 19x 17x 17x       1x   2x                 15x 15x       5x                                       2x 18x 18x 18x       18x 1x         17x               17x                                                                   16x           16x     17x 16x 15x           16x   16x         14x   14x                   15x                               14x 14x 15x     14x 15x 15x 15x                                       14x   2x                       2x 14x 14x 14x 14x 14x         13x 1x   12x 1x   11x 1x         10x 10x   10x 10x   9x 1x                     8x 1x                 7x         2x 2x               5x 5x 5x 14x       14x                         5x   5x                                       5x 5x           1x           5x   5x          
import { and, asc, eq, gte, inArray, isNotNull, sql } from "drizzle-orm";
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { WaMessage } from "../../../db/schema";
import * as schema from "../../../db/schema";
import type { RrmProspect } from "../../../db/schema/rrm";
import { NotFoundError, ValidationError } from "../../../lib/errors";
import { logger } from "../../../lib/logger";
import { error, handleError, success } from "../../../lib/response";
import { detectOptOut } from "../../../lib/rrm/optout";
import { requireUser } from "../../../lib/utils";
import { requireWhatsAppClient } from "../../../lib/whatsapp/client";
import type { Services } from "../../../services";
 
const CONVERSATIONS = schema.waConversations;
const MESSAGES = schema.waMessages;
const PROSPECTS = schema.rrmProspects;
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
	};
};
 
const inbox = new Hono<Env>();
 
/** Meta's 24-hour customer service window. */
const WINDOW_MS = 24 * 60 * 60 * 1000;
 
/** Cloud API's hard limit on a text body. */
const MAX_BODY_LENGTH = 4096;
 
/**
 * Enough of the message for triage to recognise the conversation without
 * dragging whole message bodies into a list response.
 */
const PREVIEW_LENGTH = 160;
 
/**
 * A backlog this deep is already an incident — P1-0.10 auto-pauses the campaign
 * long before it. The cap exists so a broken send loop cannot turn one admin
 * page load into an unbounded D1 read.
 */
const MAX_INBOX_ROWS = 200;
 
/** Mirrors `RrmInboxConversation` in apps/portal/src/lib/api/admin/rrm.ts. */
export type RrmInboxConversation = {
	prospectId: string;
	name: string | null;
	firmName: string | null;
	phoneNorm: string;
	locale: RrmProspect["locale"];
	lastInboundAt: string;
	waitingMinutes: number;
	windowExpiresAt: string | null;
	lastMessagePreview: string;
	needsOptOutReview: boolean;
};
 
/** Mirrors `RrmMessage` in apps/portal/src/lib/api/admin/rrm.ts. */
export type RrmMessage = {
	id: number;
	direction: "inbound" | "outbound";
	body: string;
	templateName: string | null;
	status: string;
	stepKey: string | null;
	dateCreated: string;
};
 
/**
 * `wa_messages.content` is a JSON *string* written by several producers, so a
 * malformed or non-text row must degrade to an empty preview rather than take
 * the whole inbox down with a parse error.
 */
function extractBody(content: string | null): string {
	if (!content) return "";
	try {
		const parsed: unknown = JSON.parse(content);
		if (parsed && typeof parsed === "object" && "body" in parsed) {
			const body = (parsed as { body: unknown }).body;
			if (typeof body === "string") return body;
		}
	} catch {
		// Not JSON — fall through to the raw string, which is still readable.
		return content.slice(0, PREVIEW_LENGTH);
	}
	return "";
}
 
/**
 * Null once the window has closed, never a timestamp in the past: the portal's
 * reply box is enabled on `windowExpiresAt !== null`, so a stale future-looking
 * value would offer a send that Meta rejects with 131047.
 */
function windowExpiry(lastInbound: Date, now: Date): string | null {
	const expiry = lastInbound.getTime() + WINDOW_MS;
	return expiry > now.getTime() ? new Date(expiry).toISOString() : null;
}
 
function toRrmMessage(message: WaMessage): RrmMessage {
	return {
		id: message.id,
		direction: message.direction,
		body: extractBody(message.content),
		templateName: message.templateName,
		status: message.status,
		stepKey: message.stepKey,
		dateCreated: message.dateCreated.toISOString(),
	};
}
 
/**
 * GET /inbox?state=unanswered
 *
 * Oldest-first, server-ordered, and there is deliberately no sort parameter:
 * an inbox item waiting over 24h is an auto-pause condition (P1-0.10), so
 * re-ordering away from oldest-first would hide the exact row that matters.
 * `waitingMinutes` is computed here for the same reason — a browser clock that
 * is five minutes fast must not change who looks oldest.
 */
inbox.get("/inbox", async (c) => {
	try {
		const dal = c.get("dal");
		const state = c.req.query("state") ?? "unanswered";
		// Only one state is implemented; accepting an unknown value silently
		// would return the unanswered list under a label that promised something
		// else.
		if (state !== "unanswered") {
			throw new ValidationError(
				"state must be 'unanswered' — the inbox has no other view",
			);
		}
 
		const now = new Date();
 
		// Joined on the phone rather than on `wa_messages.prospect_id`: the
		// inbound webhook writes the conversation, and `last_customer_message_at`
		// there is the single source of truth for the 24h window (see the
		// schema note on the absent `rrm_windows` table). Meta delivers `from`
		// as digits only, but an outbound-first conversation may have been
		// created in E.164, so both spellings are matched.
		const rows = await dal.db
			.select({
				conversationId: CONVERSATIONS.id,
				lastCustomerMessageAt: CONVERSATIONS.lastCustomerMessageAt,
				prospectId: PROSPECTS.id,
				name: PROSPECTS.name,
				firmName: PROSPECTS.firmName,
				phoneNorm: PROSPECTS.phoneNorm,
				locale: PROSPECTS.locale,
			})
			.from(CONVERSATIONS)
			.innerJoin(
				PROSPECTS,
				sql`${CONVERSATIONS.phoneNumber} IN (${PROSPECTS.phoneNorm}, '+' || ${PROSPECTS.phoneNorm})`,
			)
			.where(
				and(
					isNotNull(CONVERSATIONS.lastCustomerMessageAt),
					// Someone who has opted out can never be replied to, so leaving
					// them queued would keep the backlog gauge permanently tripped
					// on work no operator is allowed to do.
					eq(PROSPECTS.doNotContact, false),
					// Unanswered = nothing outbound since their last inbound. Equal
					// timestamps count as unanswered: `date_created` is second
					// precision, and erring toward showing the row is the safe half.
					sql`(${CONVERSATIONS.lastMessageAt} IS NULL OR ${CONVERSATIONS.lastMessageAt} <= ${CONVERSATIONS.lastCustomerMessageAt})`,
				),
			)
			.orderBy(asc(CONVERSATIONS.lastCustomerMessageAt), asc(PROSPECTS.id))
			.limit(MAX_INBOX_ROWS);
 
		// One prospect can own two conversation rows if a send created the E.164
		// spelling before the webhook created the digits-only one. Keep the
		// oldest, which the ASC ordering already put first.
		const oldestPerProspect = new Map<
			string,
			Omit<(typeof rows)[number], "lastCustomerMessageAt"> & {
				lastInboundAt: Date;
			}
		>();
		for (const { lastCustomerMessageAt, ...row } of rows) {
			// The WHERE clause already excludes these; the guard is what lets the
			// rest of the handler treat the timestamp as non-null without a cast.
			if (!lastCustomerMessageAt) continue;
			if (!oldestPerProspect.has(row.prospectId)) {
				oldestPerProspect.set(row.prospectId, {
					...row,
					lastInboundAt: lastCustomerMessageAt,
				});
			}
		}
		const conversations = [...oldestPerProspect.values()];
 
		if (conversations.length === 0) return success(c, []);
 
		// Every conversation's latest inbound sits at its own
		// `last_customer_message_at`, and the query returned them ascending, so
		// the first row's timestamp bounds the message scan.
		const earliest = conversations[0].lastInboundAt;
 
		const inbound = await dal.db
			.select({
				conversationId: MESSAGES.conversationId,
				content: MESSAGES.content,
			})
			.from(MESSAGES)
			.where(
				and(
					inArray(
						MESSAGES.conversationId,
						conversations.map((row) => row.conversationId),
					),
					eq(MESSAGES.direction, "inbound"),
					// A minute of slack because the two timestamps come from two
					// clocks: `last_customer_message_at` is stamped by the Worker,
					// `wa_messages.date_created` defaults to D1's `unixepoch()`. A
					// second of skew the wrong way would drop the oldest
					// conversation's own latest inbound out of the scan and clear
					// `needsOptOutReview` on the one message that needed it.
					gte(MESSAGES.dateCreated, new Date(earliest.getTime() - 60_000)),
				),
			)
			.orderBy(asc(MESSAGES.dateCreated), sql`rowid asc`);
 
		// Ascending order means the last write per conversation is the latest
		// message, which is the one triage reads and opt-out detection judges.
		const latestBody = new Map<number, string>();
		for (const row of inbound) {
			latestBody.set(row.conversationId, extractBody(row.content));
		}
 
		const items: RrmInboxConversation[] = conversations.map((row) => {
			const lastInbound = row.lastInboundAt;
			const body = latestBody.get(row.conversationId) ?? "";
			return {
				prospectId: row.prospectId,
				name: row.name,
				firmName: row.firmName,
				phoneNorm: row.phoneNorm,
				locale: row.locale,
				lastInboundAt: lastInbound.toISOString(),
				waitingMinutes: Math.max(
					0,
					Math.floor((now.getTime() - lastInbound.getTime()) / 60_000),
				),
				windowExpiresAt: windowExpiry(lastInbound, now),
				lastMessagePreview: body.slice(0, PREVIEW_LENGTH),
				// Ambiguous opt-out language only. `opt_out` is auto-suppressed
				// upstream and never reaches triage; `review` is the case where the
				// engine refuses to decide, so the UI must not offer "Interested".
				needsOptOutReview: detectOptOut(body).kind === "review",
			};
		});
 
		return success(c, items);
	} catch (err) {
		return handleError(c, err);
	}
});
 
/**
 * POST /messages/send — free-form operator reply.
 *
 * Every refusal here is a typed 4xx rather than a 500. Outside the 24h window
 * Meta answers a free-form send with 131047, which surfaces to an operator as
 * an opaque failure; refusing before the call turns that into a sentence the
 * UI can print.
 */
inbox.post("/messages/send", async (c) => {
	try {
		const user = requireUser(c.get("user"));
		const dal = c.get("dal");
		const services = c.get("services");
		const payload = await c.req.json<{
			prospectId?: unknown;
			body?: unknown;
		}>();
 
		if (typeof payload.prospectId !== "string" || !payload.prospectId.trim()) {
			throw new ValidationError("prospectId is required");
		}
		if (typeof payload.body !== "string" || !payload.body.trim()) {
			throw new ValidationError("body is required");
		}
		if (payload.body.length > MAX_BODY_LENGTH) {
			throw new ValidationError(
				`body must be ${MAX_BODY_LENGTH} characters or fewer`,
			);
		}
 
		const prospectId = payload.prospectId.trim();
		const text = payload.body;
 
		const prospect = await dal.rrmProspects.findById(prospectId);
		if (!prospect) throw new NotFoundError("Prospect", prospectId);
 
		if (prospect.doNotContact) {
			return error(
				c,
				"DO_NOT_CONTACT",
				"This prospect is marked do-not-contact and cannot be messaged.",
				409,
			);
		}
 
		// Suppression is phone-keyed and outlives the prospect row, so it is
		// checked separately from the prospect's own flag rather than assumed to
		// agree with it.
		if (await dal.rrmSuppression.isSuppressed(prospect.phoneNorm)) {
			return error(
				c,
				"SUPPRESSED",
				"This number is on the suppression list and cannot be messaged.",
				409,
			);
		}
 
		const conversation =
			(await dal.waConversations.findByPhoneNumber(prospect.phoneNorm)) ??
			(await dal.waConversations.findByPhoneNumber(`+${prospect.phoneNorm}`));
 
		// No conversation means they have never messaged us, which is the same
		// answer as a closed window: a free-form send is not available.
		Eif (!conversation || !services.waConversation.isWindowOpen(conversation)) {
			return error(
				c,
				"WINDOW_CLOSED",
				"The 24-hour reply window is closed. Use an approved template instead.",
				409,
			);
		}
 
		const client = requireWhatsAppClient(c.env);
		const result = await client.sendText(conversation.phoneNumber, text);
		const wamid = result.messages[0]?.id ?? null;
		const now = new Date();
 
		// `prospectId` is stamped on the row so the frequency and lifetime caps
		// count this send alongside every other subsystem's.
		const stored = await dal.waMessages.create({
			conversationId: conversation.id,
			wamid,
			direction: "outbound",
			type: "text",
			content: JSON.stringify({ body: text }),
			status: "sent",
			prospectId: prospect.id,
			sentBy: user.id,
			dateCreated: now,
			dateUpdated: now,
		});
 
		await dal.waConversations.update(conversation.id, { lastMessageAt: now });
 
		await dal.rrmEvents.append({
			prospectId: prospect.id,
			type: "message_sent",
			channel: "whatsapp",
			actorType: "operator",
			actorId: user.id,
			payload: { wamid, messageId: stored.id, freeForm: true },
			occurredAt: now,
		});
 
		// Replying IS the thing "Mark replied" on Sign-ups records, so a reply
		// typed here records itself — the same `setStage` call that route makes
		// (`replied_at` is written once, on first entry, by the DAL). The button
		// stays: a reply sent from a handset still needs it.
		//
		// Best-effort on purpose. The message is already with Meta by now; a
		// failed bookkeeping write must not turn a delivered reply into a 500
		// that invites the operator to send it twice. A refusal (`changed:
		// false` — DNC, or a prospect already further along) is the forward-only
		// rule working, exactly as it is for the button.
		try {
			await dal.rrmProspects.setStage(prospect.id, "replied", {
				actorType: "operator",
				actorId: user.id,
				reason: "operator_replied_from_inbox",
			});
		} catch (err) {
			logger.error(
				"[RRM inbox] reply sent but marking the prospect replied failed:",
				err,
			);
		}
 
		return success(c, toRrmMessage(stored));
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default inbox;