All files / routes/pro whatsapp-recipients.routes.ts

95.55% Statements 129/135
88.46% Branches 46/52
100% Functions 11/11
95.52% Lines 128/134

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                                                                                                1x   1x                             7x                                 9x     9x 9x 1x   8x 1x   7x       5x     5x 5x   5x       1x   4x 4x     4x       18x 18x 1x   17x       9x 1x   8x 1x   7x 3x   4x 1x   3x 1x   2x 1x   1x 1x           1x       2x 2x 2x 2x 1x         1x           1x       7x 7x 7x 7x 7x         7x 7x 7x     7x 7x               2x 2x         2x 2x   1x             2x   5x           1x       7x 7x 7x 7x 7x 7x                 6x 6x 6x 1x 1x       5x 2x 1x   1x 1x           3x 1x       2x 2x             1x 1x   1x   6x           1x       2x 2x 2x 2x 2x 2x 2x   1x 1x   1x   1x           1x       5x 5x 5x 5x 5x 5x 5x 1x     4x 4x             3x 3x   1x   4x           1x       4x 4x 4x 4x 4x   4x 4x           2x 2x   2x 2x   1x           2x         2x            
import {
	MAX_WHATSAPP_RECIPIENTS_PER_PRO,
	WHATSAPP_OTP_RESEND_COOLDOWN_SECONDS,
} from "@interioring/utils/constants/whatsapp";
import {
	isValidIndianMobile,
	normalizeToE164,
} from "@interioring/utils/validation/phone";
import { Hono } from "hono";
import {
	AlreadyVerifiedError,
	type Dal,
	DuplicateRecipientError,
	OtpCooldownError,
	OtpExpiredError,
	OtpMismatchError,
	RecipientLimitError,
	RecipientNotFoundError,
} from "../../dal";
import type {
	CreatedRecipient,
} from "../../dal/pro-whatsapp-recipients.dal";
import type { ProWhatsAppRecipient } from "../../db/schema/pro-whatsapp-recipients";
import { sendWhatsAppOtp } from "../../lib/communication/whatsapp-otp";
import {
	AppError,
	BadRequestError,
	ConflictError,
	NotFoundError,
	ValidationError,
} from "../../lib/errors";
import { handleError, success } from "../../lib/response";
import type { Services } from "../../services";
import { requireProAccess } from "../../middleware";
import { logger } from "../../lib/logger";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		proId: string;
		proRole: string;
	};
};
 
const whatsappRecipients = new Hono<Env>();
 
const MAX_LABEL_LEN = 32;
 
function toPublic(r: {
	id: number;
	proId: string;
	label: string;
	number: string;
	isPrimary: boolean;
	notificationsEnabled: boolean;
	verifiedAt: Date | null;
	otpExpiresAt: Date | null;
	otpLastSentAt: Date | null;
	dateCreated: Date;
	dateUpdated: Date;
}) {
	return {
		id: r.id,
		proId: r.proId,
		label: r.label,
		number: r.number,
		isPrimary: r.isPrimary,
		notificationsEnabled: r.notificationsEnabled,
		isVerified: r.verifiedAt !== null,
		verifiedAt: r.verifiedAt,
		otpPendingUntil: r.verifiedAt === null ? r.otpExpiresAt : null,
		otpLastSentAt: r.otpLastSentAt,
		dateCreated: r.dateCreated,
		dateUpdated: r.dateUpdated,
	};
}
 
function parseLabel(input: unknown): string {
	Iif (typeof input !== "string") {
		throw new ValidationError("label must be a string");
	}
	const trimmed = input.trim();
	if (trimmed.length === 0) {
		throw new ValidationError("label cannot be empty");
	}
	if (trimmed.length > MAX_LABEL_LEN) {
		throw new ValidationError(`label must be ${MAX_LABEL_LEN} chars or fewer`);
	}
	return trimmed;
}
 
function parseNumber(input: unknown): string {
	Iif (typeof input !== "string") {
		throw new ValidationError("number must be a string");
	}
	const trimmed = input.trim();
	const digitsOnly = trimmed.replace(/[\s\-()]/g, "");
	// Accept either 10-digit national or already E.164.
	if (
		!isValidIndianMobile(digitsOnly) &&
		!normalizeToE164(digitsOnly)
	) {
		throw new ValidationError("number is not a valid Indian mobile number");
	}
	const e164 = normalizeToE164(digitsOnly);
	Iif (!e164) {
		throw new ValidationError("number could not be normalised to E.164");
	}
	return e164;
}
 
function parseId(raw: string): number {
	const id = Number.parseInt(raw, 10);
	if (!Number.isInteger(id) || id <= 0) {
		throw new ValidationError("Invalid recipient id");
	}
	return id;
}
 
function mapDalError(err: unknown): never {
	if (err instanceof RecipientLimitError) {
		throw new BadRequestError(err.message);
	}
	if (err instanceof DuplicateRecipientError) {
		throw new ConflictError(err.message);
	}
	if (err instanceof RecipientNotFoundError) {
		throw new NotFoundError("Recipient");
	}
	if (err instanceof AlreadyVerifiedError) {
		throw new ConflictError(err.message);
	}
	if (err instanceof OtpExpiredError) {
		throw new BadRequestError(err.message);
	}
	if (err instanceof OtpMismatchError) {
		throw new BadRequestError(err.message);
	}
	Eif (err instanceof OtpCooldownError) {
		throw new AppError(429, "OTP_COOLDOWN", err.message);
	}
	throw err;
}
 
// GET /api/pro/:proId/whatsapp-recipients
whatsappRecipients.get(
	"/:proId/whatsapp-recipients",
	requireProAccess,
	async (c) => {
		try {
			const dal = c.get("dal");
			const proId = c.get("proId");
			const rows = await dal.proWhatsAppRecipients.listByProId(proId);
			return success(c, {
				recipients: rows.map(toPublic),
				maxAllowed: MAX_WHATSAPP_RECIPIENTS_PER_PRO,
			});
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// POST /api/pro/:proId/whatsapp-recipients
whatsappRecipients.post(
	"/:proId/whatsapp-recipients",
	requireProAccess,
	async (c) => {
		try {
			const dal = c.get("dal");
			const proId = c.get("proId");
			const user = c.get("user");
			const body = await c.req.json<{
				label?: unknown;
				number?: unknown;
				isPrimary?: unknown;
			}>();
			const label = parseLabel(body.label);
			const number = parseNumber(body.number);
			const makePrimary = body.isPrimary === true;
 
			let created: CreatedRecipient;
			try {
				created = await dal.proWhatsAppRecipients.create({
					proId,
					label,
					number,
					makePrimary,
					actorUserId: user?.id,
				});
			} catch (err) {
				mapDalError(err);
				return; // unreachable — mapDalError throws.
			}
 
			// Fire OTP via WhatsApp. Failure here logs but doesn't roll back the row;
			// the recipient can resend from the UI.
			try {
				await sendWhatsAppOtp(c.env, created.recipient.number, created.otpCode);
			} catch (sendErr) {
				logger.error(
					"[whatsapp-recipients] OTP send failed for recipient",
					created.recipient.id,
					sendErr,
				);
			}
 
			return success(c, { recipient: toPublic(created.recipient) }, 201);
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// PATCH /api/pro/:proId/whatsapp-recipients/:id
whatsappRecipients.patch(
	"/:proId/whatsapp-recipients/:id",
	requireProAccess,
	async (c) => {
		try {
			const dal = c.get("dal");
			const proId = c.get("proId");
			const user = c.get("user");
			const id = parseId(c.req.param("id"));
			const body = await c.req.json<{
				label?: unknown;
				notificationsEnabled?: unknown;
				isPrimary?: unknown;
			}>();
			const patch: {
				label?: string;
				notificationsEnabled?: boolean;
				isPrimary?: boolean;
			} = {};
			if (body.label !== undefined) patch.label = parseLabel(body.label);
			if (body.notificationsEnabled !== undefined) {
				Eif (typeof body.notificationsEnabled !== "boolean") {
					throw new ValidationError("notificationsEnabled must be a boolean");
				}
				patch.notificationsEnabled = body.notificationsEnabled;
			}
			if (body.isPrimary !== undefined) {
				if (typeof body.isPrimary !== "boolean") {
					throw new ValidationError("isPrimary must be a boolean");
				}
				Eif (body.isPrimary === false) {
					throw new ValidationError(
						"Primary cannot be unset directly — promote another recipient instead",
					);
				}
				patch.isPrimary = body.isPrimary;
			}
			if (Object.keys(patch).length === 0) {
				throw new ValidationError("No fields provided");
			}
 
			let updated: ProWhatsAppRecipient;
			try {
				updated = await dal.proWhatsAppRecipients.updatePartial(
					id,
					proId,
					patch,
					user?.id,
				);
			} catch (err) {
				mapDalError(err);
				return;
			}
			return success(c, { recipient: toPublic(updated) });
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// DELETE /api/pro/:proId/whatsapp-recipients/:id
whatsappRecipients.delete(
	"/:proId/whatsapp-recipients/:id",
	requireProAccess,
	async (c) => {
		try {
			const dal = c.get("dal");
			const proId = c.get("proId");
			const user = c.get("user");
			const id = parseId(c.req.param("id"));
			try {
				await dal.proWhatsAppRecipients.delete(id, proId, user?.id);
			} catch (err) {
				mapDalError(err);
				return;
			}
			return success(c, { deleted: true });
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// POST /api/pro/:proId/whatsapp-recipients/:id/verify
whatsappRecipients.post(
	"/:proId/whatsapp-recipients/:id/verify",
	requireProAccess,
	async (c) => {
		try {
			const dal = c.get("dal");
			const proId = c.get("proId");
			const user = c.get("user");
			const id = parseId(c.req.param("id"));
			const body = await c.req.json<{ code?: unknown }>();
			if (typeof body.code !== "string" || !/^\d+$/.test(body.code)) {
				throw new ValidationError("code must be a numeric string");
			}
			let updated: ProWhatsAppRecipient;
			try {
				updated = await dal.proWhatsAppRecipients.verify(
					id,
					proId,
					body.code,
					user?.id,
				);
			} catch (err) {
				mapDalError(err);
				return;
			}
			return success(c, { recipient: toPublic(updated) });
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// POST /api/pro/:proId/whatsapp-recipients/:id/resend-otp
whatsappRecipients.post(
	"/:proId/whatsapp-recipients/:id/resend-otp",
	requireProAccess,
	async (c) => {
		try {
			const dal = c.get("dal");
			const proId = c.get("proId");
			const user = c.get("user");
			const id = parseId(c.req.param("id"));
			let result: { recipient: ProWhatsAppRecipient; otpCode: string };
			try {
				result = await dal.proWhatsAppRecipients.regenerateOtp(
					id,
					proId,
					user?.id,
				);
			} catch (err) {
				mapDalError(err);
				return;
			}
			try {
				await sendWhatsAppOtp(c.env, result.recipient.number, result.otpCode);
			} catch (sendErr) {
				logger.error(
					"[whatsapp-recipients] resend OTP failed for recipient",
					result.recipient.id,
					sendErr,
				);
			}
			return success(c, {
				recipient: toPublic(result.recipient),
				cooldownSeconds: WHATSAPP_OTP_RESEND_COOLDOWN_SECONDS,
			});
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
export default whatsappRecipients;