All files / routes/admin/whatsapp send.routes.ts

82.97% Statements 39/47
67.85% Branches 19/28
100% Functions 2/2
82.97% Lines 39/47

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                                    2x     2x 6x 6x 6x 6x 1x     4x 4x   4x   3x 1x                 2x   2x                 2x         2x 12x 12x 12x 12x                     11x 1x     10x 10x 2x     8x       8x     7x 2x               5x                                                                             5x 4x 1x               3x 1x             2x             1x               3x   3x          
import { normalizeToE164 } from "@interioring/utils/validation/phone";
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import { error, handleError, success } from "../../../lib/response";
import { requireUser } from "../../../lib/utils";
import { requireWhatsAppClient } from "../../../lib/whatsapp/client";
import type { Services } from "../../../services";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
	};
};
 
const send = new Hono<Env>();
 
// GET /check-phone - Check if we can send a text message to this number
send.get("/check-phone", async (c) => {
	try {
		requireUser(c.get("user"));
		const phone = c.req.query("phone");
		if (!phone) {
			return error(c, "VALIDATION_ERROR", "Phone number is required", 400);
		}
 
		const dal = c.get("dal");
		const services = c.get("services");
 
		const conversation = await dal.waConversations.findByPhoneNumber(phone);
 
		if (!conversation) {
			return success(c, {
				exists: false,
				windowOpen: false,
				contactName: null,
				contactType: null,
				canSendText: false,
			});
		}
 
		const windowOpen = services.waConversation.isWindowOpen(conversation);
 
		return success(c, {
			exists: true,
			windowOpen,
			contactName: conversation.contactName,
			contactType: conversation.contactType,
			canSendText: windowOpen,
			lastCustomerMessageAt: conversation.lastCustomerMessageAt,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST / - Send ad-hoc message to any number
send.post("/", async (c) => {
	try {
		const user = requireUser(c.get("user"));
		const services = c.get("services");
		const body = await c.req.json<{
			phone: string;
			message?: string;
			templateName?: string;
			language?: string;
			components?: unknown[];
			mediaUrl?: string;
			mediaType?: "video" | "image" | "document";
			caption?: string;
		}>();
 
		if (!body.phone) {
			return error(c, "VALIDATION_ERROR", "Phone number is required", 400);
		}
 
		const e164 = normalizeToE164(body.phone);
		if (!e164) {
			return error(c, "VALIDATION_ERROR", "Invalid phone number format", 400);
		}
 
		const client = requireWhatsAppClient(c.env);
 
		// Find or create conversation for this phone number
		const conversation =
			await services.waConversation.getOrCreateConversation(e164);
 
		let result: unknown;
		if (body.templateName) {
			result = await services.waConversation.replyWithTemplate(
				conversation.id,
				body.templateName,
				body.language ?? "en",
				body.components,
				user.id,
				client,
			);
		I} else if (body.mediaUrl) {
			// Media is free-form only — Meta has no media message outside an open
			// window that is not a template header. Checked before the send so the
			// operator gets the reason rather than a Graph error.
			if (!services.waConversation.isWindowOpen(conversation)) {
				return error(
					c,
					"WINDOW_EXPIRED",
					"24-hour window expired. Media can only be sent free-form, inside an open window — ask them to message you first.",
					400,
				);
			}
			const kind = body.mediaType ?? "video";
			if (!["video", "image", "document"].includes(kind)) {
				return error(
					c,
					"VALIDATION_ERROR",
					"mediaType must be video, image or document",
					400,
				);
			}
			// Meta fetches this URL itself. A YouTube or Drive share page serves
			// HTML, not media, and is rejected — it must be a direct file URL.
			if (!/^https:\/\//.test(body.mediaUrl)) {
				return error(
					c,
					"VALIDATION_ERROR",
					"mediaUrl must be a public https:// link to the file itself",
					400,
				);
			}
			result = await services.waConversation.replyWithMedia(
				conversation.id,
				kind,
				body.mediaUrl,
				body.caption,
				user.id,
				client,
			);
		} else if (body.message) {
			if (body.message.length > 4096) {
				return error(
					c,
					"VALIDATION_ERROR",
					"Message too long. Maximum is 4096 characters.",
					400,
				);
			}
			// Check if window is open for text messages
			if (!services.waConversation.isWindowOpen(conversation)) {
				return error(
					c,
					"WINDOW_EXPIRED",
					"24-hour window expired. Use a template message instead.",
					400,
				);
			}
			result = await services.waConversation.reply(
				conversation.id,
				body.message,
				user.id,
				client,
			);
		} else {
			return error(
				c,
				"VALIDATION_ERROR",
				"Either message, templateName or mediaUrl is required",
				400,
			);
		}
 
		return success(c, { message: result, conversationId: conversation.id });
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default send;