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

100% Statements 38/38
100% Branches 18/18
100% Functions 2/2
100% Lines 38/38

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                                    1x     1x 6x 6x 6x 6x 1x     4x 4x     4x   3x 1x                 2x   2x                 2x         1x 12x 12x 12x 12x               11x 1x     10x 10x 2x     8x       8x     7x 2x               5x 4x 1x               3x 1x             2x             1x               3x   3x          
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { Services } from "../../../services";
import { success, error, handleError } from "../../../lib/response";
import { requireUser } from "../../../lib/utils";
import { requireWhatsAppClient } from "../../../lib/whatsapp/client";
import { normalizeToE164 } from "@interioring/utils/validation/phone";
 
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[];
		}>();
 
		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(body.phone);
 
		let result: unknown;
		if (body.templateName) {
			result = await services.waConversation.replyWithTemplate(
				conversation.id,
				body.templateName,
				body.language ?? "en",
				body.components,
				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 or templateName is required",
				400,
			);
		}
 
		return success(c, { message: result, conversationId: conversation.id });
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default send;