All files / routes/webhooks whatsapp.routes.ts

100% Statements 70/70
97.36% Branches 37/38
100% Functions 4/4
100% Lines 69/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                                                2x     2x     2x 7x 7x 7x   7x 3x     4x       2x   53x     53x 2x     51x 53x         51x 4x         47x 47x   2x     45x           45x   45x             45x         45x         44x 4x     40x 40x 40x   40x 40x 40x 40x     40x             40x 40x 40x 37x 35x               35x   35x   32x           31x         2x 2x   1x                   31x                     10x 10x                 2x           10x     10x 9x     9x                       1x       4x         40x 40x 40x 7x     7x 7x             7x             40x 40x 3x     1x                                                               10x            
import { Hono } from "hono";
import { handleCompanionMessages } from "../../companion/webhook-bridge";
import type { Dal } from "../../dal";
import { resolveEnvironment } from "../../lib/domain-utils";
import { getWhatsAppIds } from "../../lib/env-config";
import { logger } from "../../lib/logger";
import { createWhatsAppClient } from "../../lib/whatsapp/client";
import type { WhatsAppWebhookPayload } from "../../lib/whatsapp/types";
import {
	extractMessages,
	extractStatuses,
	extractTemplateStatuses,
	verifyWebhookSignature,
} from "../../lib/whatsapp/webhook";
import type { Services } from "../../services";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		dal: Dal;
		services: Services;
	};
};
 
const whatsapp = new Hono<Env>();
 
/** Unsupported subtypes that change a message we already have. */
const NOT_NEW_CONTENT = new Set(["edit", "pin", "keep_in_chat", "reaction"]);
 
// GET /whatsapp - Webhook verification (Meta sends this to verify the endpoint)
whatsapp.get("/whatsapp", async (c) => {
	const mode = c.req.query("hub.mode");
	const token = c.req.query("hub.verify_token");
	const challenge = c.req.query("hub.challenge");
 
	if (mode === "subscribe" && token === c.env.WHATSAPP_WEBHOOK_VERIFY_TOKEN) {
		return c.text(challenge ?? "", 200);
	}
 
	return c.text("Forbidden", 403);
});
 
// POST /whatsapp - Receive inbound messages and status updates
whatsapp.post("/whatsapp", async (c) => {
	// Capture raw body BEFORE parsing (needed for signature verification)
	const rawBody = await c.req.text();
 
	// Signature verification is mandatory — reject if secret is not configured
	if (!c.env.WHATSAPP_APP_SECRET) {
		return c.text("Webhook not configured", 503);
	}
 
	const signature = c.req.header("x-hub-signature-256") ?? "";
	const isValid = await verifyWebhookSignature(
		rawBody,
		signature,
		c.env.WHATSAPP_APP_SECRET,
	);
	if (!isValid) {
		return c.text("Invalid signature", 401);
	}
 
	// Always respond 200 immediately (Meta requires fast response)
	let payload: WhatsAppWebhookPayload;
	try {
		payload = JSON.parse(rawBody);
	} catch {
		return c.text("Invalid JSON", 400);
	}
 
	logger.info(
		"[WEBHOOK] Received WhatsApp event",
		JSON.stringify(payload).substring(0, 500),
	);
 
	// Process in background
	c.executionCtx.waitUntil(processWebhook(payload, c.env));
 
	return c.text("OK", 200);
});
 
async function processWebhook(
	payload: WhatsAppWebhookPayload,
	env: CloudflareBindings,
) {
	try {
		// InterioringAI companion prototype: anything that arrived on the Meta
		// test number is handled here and skipped by everything below — no
		// inbox row. Runs before the token check because the companion has its
		// own token (and works without one, logging sends).
		const companionHandled = await handleCompanionMessages(
			extractMessages(payload),
			env,
		);
 
		if (!env.WHATSAPP_ACCESS_TOKEN) {
			return;
		}
 
		const { getDb } = await import("../../db");
		const { createDal } = await import("../../dal");
		const { createServices } = await import("../../services");
 
		const db = getDb(env.DB);
		const dal = createDal(db);
		const services = createServices(dal, env);
		const { phoneNumberId, wabaId } = getWhatsAppIds(
			resolveEnvironment(env.ENVIRONMENT),
		);
		const client = createWhatsAppClient({
			phoneNumberId,
			accessToken: env.WHATSAPP_ACCESS_TOKEN,
			wabaId,
		});
 
		// Process inbound messages
		const messages = extractMessages(payload);
		logger.info(`[WEBHOOK] Extracted ${messages.length} inbound messages`);
		for (const { message, contactName } of messages) {
			if (companionHandled.has(message.id)) continue;
			logger.info(
				`[WEBHOOK] Inbound: from=${message.from}, type=${message.type}, id=${message.id}`,
			);
 
			// Per-message isolation. Meta delivers messages in a batch and
			// retries the WHOLE batch, so letting one bad message reach the
			// outer catch silently drops every message after it — and the retry
			// meets the same bad message again. Skip the one, keep the rest.
			try {
				const { conversation, newChat } =
					await services.waConversation.addInboundMessage(message, contactName);
				// Auto mark as read
				await client.markAsRead(message.id);
 
				// Meta tells us a message arrived but not what was in it (a poll, a
				// view-once photo). Ask for it again rather than leave the customer
				// waiting on an answer to something nobody here can read. Not for
				// an edit, pin or reaction: those act on a message we already have.
				if (
					message.type === "unsupported" &&
					!NOT_NEW_CONTENT.has(message.unsupported?.type ?? "") &&
					conversation
				) {
					try {
						await services.waConversation.askToResend(conversation.id, client);
					} catch (err) {
						logger.error("[WEBHOOK] Resend request error:", err);
					}
				}
 
				// A new chat — the contact's first message, or their first after a
				// quiet week. Two independent things happen, each isolated from
				// the other: the customer gets an acknowledgement, and support
				// gets an email. Neither is for a designer; `contactType` is
				// resolved against the pro directory when the conversation is
				// created, so a designer's thread is already marked.
				if (newChat && conversation && conversation.contactType !== "pro") {
					// What a homeowner hears back, once, immediately.
					//
					// This reply used to hang off the retired referral funnel,
					// which was the only thing that triggered it; it now hangs off
					// the generic new-chat path, so the number keeps answering the
					// people who message it. `newChat` is claimed atomically by
					// `waConversations.claimNewChat`, which is what makes this
					// exactly one reply per new chat and nothing at all on a
					// thread we have already greeted — a chatty homeowner does not
					// get two.
					try {
						await services.waConversation.reply(
							conversation.id,
							acknowledgementText(),
							// null = a system send. `sent_by` is an FK to users.id,
							// so a fabricated id would throw.
							null,
							client,
						);
					} catch (err) {
						logger.error("[WEBHOOK] New-chat acknowledgement error:", err);
					}
 
					// Support is emailed until the assistant (#1087) answers them.
					// The phone and the message text go in the email, never in a
					// log line.
					try {
						// contactType is set once, when the chat starts: a designer who
						// has since put this number on their profile is not a lead.
						if (!(await dal.pros.findByWhatsappNumber(message.from))) {
							const { notifyInternalLeadership } = await import(
								"../../lib/internal-notifications"
							);
							await notifyInternalLeadership(env, dal, {
								event: "whatsapp_chat_internal",
								conversationId: conversation.id,
								name: contactName || conversation.contactName,
								phone: message.from,
								contactType: conversation.contactType,
								inquiryId: conversation.inquiryId,
								firstMessage: message.text?.body ?? `[${message.type}]`,
								inboxUrl: `${env.PORTAL_URL || "https://portal.interioring.com"}/admin/whatsapp/inbox?id=${conversation.id}`,
							});
						}
					} catch (err) {
						logger.error("[WEBHOOK] New-chat alert error:", err);
					}
				}
			} catch (err) {
				logger.error("[WEBHOOK] Inbound message error:", err);
			}
		}
 
		// Process status updates
		const statuses = extractStatuses(payload);
		logger.info(`[WEBHOOK] Extracted ${statuses.length} status updates`);
		for (const status of statuses) {
			logger.info(
				`[WEBHOOK] Status: wamid=${status.id}, status=${status.status}, errors=${JSON.stringify(status.errors ?? [])}`,
			);
			const errorCode = status.errors?.[0]?.code?.toString() ?? undefined;
			await services.waConversation.updateMessageStatus(
				status.id,
				status.status,
				errorCode,
			);
 
			// Also update campaign recipient if applicable
			await dal.waCampaigns.updateRecipientStatusByWamid(
				status.id,
				status.status,
			);
		}
 
		// Process template status updates (approvals, rejections, etc.)
		const templateStatuses = extractTemplateStatuses(payload);
		for (const event of templateStatuses) {
			await services.waTemplate.handleStatusWebhook(event);
		}
	} catch (err) {
		logger.error("[WEBHOOK] WhatsApp processing error:", err);
	}
}
 
export default whatsapp;
 
/**
 * What a homeowner hears back, once, immediately.
 *
 * Free-form and in-window: they messaged us seconds ago, so this needs no
 * approved template and costs nothing against the ceiling.
 *
 * Deliberately says almost nothing. It confirms we have them and that a person
 * is coming — it does not ask the five qualification questions, because those
 * are an operator's job until the slot-filler exists, and a bot interrogating
 * someone who has just reached out is a worse first impression than a short
 * wait.
 *
 * SAYS NOTHING ABOUT HOW THEY FOUND US, ON PURPOSE.
 * While the referral programme existed this reply took a referrer's name and
 * opened with "<name> asked us to …" — it only ever fired on a referred
 * homeowner. It now fires on EVERY new non-pro chat (the `newChat` branch in
 * `processWebhook`), and most of those people were not referred by anyone:
 * they tapped a `wa.me` link on the marketplace, on a `go.` campaign page, or
 * typed the number off an ad. Keeping the old sentence with "Someone" in place
 * of the name told all of them a third party had been in touch on their
 * behalf, which is simply untrue and unanswerable — there is no "someone" for
 * them to ask about. So the claim is gone rather than genericised. What is
 * left is true of everyone who can receive it: they wrote in, we have it, a
 * person is coming.
 */
export function acknowledgementText(): string {
	return (
		"Thanks for getting in touch! We can put together a free interior " +
		"design estimate for your home — no cost and no obligation.\n\n" +
		"One of our team will message you shortly to understand what you have in mind."
	);
}