All files / lib/communication gateway.ts

100% Statements 65/65
100% Branches 52/52
100% Functions 13/13
100% Lines 61/61

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                        14x 14x       9x 8x                       10x   10x   10x   11x   11x 8x 8x 1x       11x   11x                                         11x 2x         2x 2x         2x     11x 3x 3x     11x       11x     10x 9x     9x   1x       11x   10x 7x   8x   7x 7x                               8x         9x       8x   8x 3x     5x           5x   5x 4x     1x       11x 7x 7x           4x 1x 1x         3x 3x                 3x 1x     2x 1x   3x 2x     3x 1x     1x    
import type { Dal } from "../../dal";
import type { NewNotificationDeliveryLogEntry } from "../../db/schema";
import type {
	CommunicationQueueMessage,
	CommunicationRequest,
	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: NewNotificationDeliveryLogEntry;
			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;
 
				if (!req.transactional) {
					const skip = await this.checkPreference(req);
					if (skip) {
						skipped = true;
					}
				}
 
				const contentSummary = this.buildContentSummary(req);
 
				const entry: NewNotificationDeliveryLogEntry = {
					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 */
				};
 
				if (storeInlineEmailPreview && req.channel === "email") {
					const content = req.content as EmailContent;
					// Loaded lazily: ../email pulls @react-email/render (prettier,
					// html-to-text, entities, react). This branch is a local-dev-only
					// inline preview, so the whole renderer stayed out of every cold
					// isolate for the sake of one debugging convenience.
					const { renderEmailTemplate } = await import("../email");
					const preview = await renderEmailTemplate({
						template: content.template,
						props: content.props,
						recipientName: content.recipientName,
					});
					entry.previewHtml = preview.html;
				}
 
				if (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.notificationDeliveryLog.insert(
				entries[0],
			);
			insertedEntries = [inserted];
		} else {
			insertedEntries =
				await this.dal.notificationDeliveryLog.batchInsert(entries);
		}
 
		const logIds = insertedEntries.map((e) => e.id);
 
		if (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;
 
		if (!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 {
		if (req.channel === "email") {
			const content = req.content as EmailContent;
			return JSON.stringify({
				template: content.template,
				subject: content.subject,
			});
		}
 
		if (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 {
	if (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}`;
}