All files / lib/communication gateway.ts

93.75% Statements 60/64
71.15% Branches 37/52
100% Functions 13/13
93.22% Lines 55/59

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                          12x         6x 6x                       12x 7x   6x   1x   8x 8x 8x 8x       9x   9x                                         9x 9x 9x         2x     2x 2x 2x     2x       9x     1x 1x 9x   8x     7x   7x 7x   8x   8x 8x                               2x         6x           6x 6x     6x           6x   1x 5x     5x       5x 5x 1x           9x 9x 7x         7x 7x                 1x 1x     1x 9x 1x             1x    
import type { Dal } from "../../dal";
import type { NewCommunicationLogEntry } from "../../db/schema";
import { renderEmailTemplate } from "../email";
import type {
	CommunicationRequest,
	CommunicationQueueMessage,
	EmailContent,
	SmsContent,
	WhatsAppContent,
} from "./types";
 
export class CommunicationGateway {
	constructor(
		private dal: Dal,
		private env: CloudflareBindings,
	) {}
 
	async send(request: CommunicationRequest): Promise<{ logId: number }> {
		const { logIds } = await this.sendMany([request]);
		return { logId: logIds[0] };
	}
 
	async sendMany(
		requests: CommunicationRequest[],
	): Promise<{ logIds: number[] }> {
		type EntryWithRequest = {
			entry: NewCommunicationLogEntry;
			request: CommunicationRequest;
			skipped: boolean;
		};
 
		const environment = this.env.ENVIRONMENT ?? "local";
		const storeInlineEmailPreview = !this.env.COMMUNICATION_QUEUE && environment !== "production";
 
		const entriesWithRequests: EntryWithRequest[] = await Promise.all(
			requests.map(async (req) => {
				let skipped = false;
 
				Eif (!req.transactional) {
					const skip = await this.checkPreference(req);
					Eif (skip) {
						skipped = true;
					}
				}
 
				const contentSummary = this.buildContentSummary(req);
 
				const entry: NewCommunicationLogEntry = {
					channel: req.channel,
					recipient: req.recipient,
					eventType: req.eventType,
					proId: req.proId ?? null,
					userId: req.userId ?? null,
					status: skipped ? "skipped" : "queued",
					environment,
					subject:
						req.channel === "email"
							? (req.content as EmailContent).subject
							: null,
					contentSummary,
					/* v8 ignore start -- V8 artifact: ?? false fallback */
					transactional: req.transactional ?? false,
					/* v8 ignore stop */
					/* v8 ignore start -- V8 artifact: ternary false branch */
					metadataJson: req.metadata ? JSON.stringify(req.metadata) : undefined,
					/* v8 ignore stop */
				};
 
				Eif (storeInlineEmailPreview && req.channel === "email") {
					const content = req.content as EmailContent;
					const preview = await renderEmailTemplate({
						template: content.template,
						props: content.props,
						recipientName: content.recipientName,
					});
					entry.previewHtml = preview.html;
				}
 
				Eif (req.channel === "whatsapp") {
					const content = req.content as WhatsAppContent;
					entry.previewText = buildWhatsAppPreviewText(content);
				}
 
				return { entry, request: req, skipped };
			}),
		);
 
		const entries = entriesWithRequests.map((e) => e.entry);
 
		let insertedEntries: { id: number }[];
		if (entries.length === 1) {
			const inserted = await this.dal.communicationLog.insert(entries[0]);
			insertedEntries = [inserted];
		} else {
			insertedEntries = await this.dal.communicationLog.batchInsert(entries);
		}
 
		const logIds = insertedEntries.map((e) => e.id);
 
		Eif (this.env.COMMUNICATION_QUEUE) {
			await Promise.all(
				entriesWithRequests.map(async ({ request: req, skipped }, index) => {
					if (skipped) return;
 
					const logId = logIds[index];
					const message: CommunicationQueueMessage = {
						logId,
						channel: req.channel,
						recipient: req.recipient,
						eventType: req.eventType,
						...(req.proId !== undefined && { proId: req.proId }),
						...(req.userId !== undefined && { userId: req.userId }),
						content: req.content,
						...(req.transactional !== undefined && {
							transactional: req.transactional,
						}),
						/* v8 ignore start -- V8 artifact: spread condition */
						...(req.metadata !== undefined && { metadata: req.metadata }),
						/* v8 ignore stop */
					};
 
					await this.env.COMMUNICATION_QUEUE?.send(message);
				}),
			);
		}
 
		return { logIds };
	}
 
	private async checkPreference(req: CommunicationRequest): Promise<boolean> {
		const { userId, proId, eventType, channel } = req;
 
		Eif (!userId || !proId) {
			return false;
		}
 
		const prefs = await this.dal.notificationPreferences.findByUserProEvent(
			userId,
			proId,
			eventType,
		);
 
		const channelPref = prefs.find((p) => p.channel === channel);
 
		if (!channelPref) {
			return false;
		}
 
		return !channelPref.enabled;
	}
 
	private buildContentSummary(req: CommunicationRequest): string {
		Eif (req.channel === "email") {
			const content = req.content as EmailContent;
			return JSON.stringify({
				template: content.template,
				subject: content.subject,
			});
		}
 
		Eif (req.channel === "sms") {
			const content = req.content as SmsContent;
			return JSON.stringify({
				codeLength: content.code.length,
			});
		}
 
		const content = req.content as WhatsAppContent;
		return JSON.stringify({
			templateName: content.templateName,
			languageCode: content.languageCode,
			hasTextBody: !!content.textBody,
		});
	}
}
 
function buildWhatsAppPreviewText(content: WhatsAppContent): string {
	Eif (content.textBody) {
		return content.textBody;
	}
 
	const bodyComponent = content.components?.find((component) => component.type === "body");
	const bodyParams = bodyComponent?.parameters
		?.map((param) => ("text" in param ? param.text : ""))
		.filter(Boolean);
 
	if (bodyParams && bodyParams.length > 0) {
		return `Template ${content.templateName}: ${bodyParams.join(" ")}`;
	}
 
	return `Template ${content.templateName}`;
}