All files / lib internal-notifications.ts

100% Statements 44/44
95% Branches 38/40
100% Functions 7/7
100% Lines 44/44

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                                      2x               2x                                                                                                 4x 4x 4x 4x               1x                         3x 3x 3x   2x 1x                   21x 21x               21x     21x       21x   56x     56x 56x         47x   9x 9x   9x             56x 56x                             6x                           86x             21x   7x 7x                   7x     5x 5x 5x                 5x     2x 2x 2x                       2x     7x 7x 7x                 7x        
// Internal leadership notifications — per-event emails to a hardcoded list of
// Interioring leadership inboxes when a new lead, pro, or homeowner is created.
//
// Bypasses CommunicationGateway/queue on purpose: the gateway is template-based
// and tied to per-user preferences (leadership has no user rows here). This
// helper writes directly to the email provider + communication_log so the
// E2E suite can assert delivery via DB query against the same source of truth
// the gateway uses.
//
// Errors NEVER throw — emails are best-effort and must not block the
// originating request (inquiry POST, pro create, homeowner signup).
 
import type { Context } from "hono";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import type { Dal } from "../dal";
import type * as schema from "../db/schema";
import { createEmailProvider } from "./email/email-provider.factory";
import { escapeHtml } from "./html-escape";
 
export const INTERNAL_NOTIFICATION_RECIPIENTS = [
	"srini@interioring.com",
	"arpna@interioring.com",
	"surendra@interioring.com",
] as const;
 
// Landing-page leads go to support (who does the manual matching), not the
// leadership digest list.
export const LANDING_LEAD_RECIPIENTS = ["support@interioring.com"] as const;
 
export type InternalEventPayload =
	| {
			event: "new_lead_internal";
			proName: string | null;
			customerName: string;
			customerPhone: string;
			message?: string | null;
			inquiryId: string | number;
	  }
	| {
			event: "new_pro_internal";
			proId: string;
			businessName: string | null;
			slug: string | null;
			userId?: string | null;
	  }
	| {
			event: "new_homeowner_internal";
			userId: string;
			name: string;
			email: string | null;
			phone: string | null;
	  }
	| {
			event: "landing_lead_internal";
			leadId: string | number;
			name: string;
			phone: string | null;
			email: string | null;
			locality: string | null;
			notes: string | null;
			source: string;
	  };
 
// Better Auth `databaseHooks.user.create.after` handler for homeowner signup.
// Extracted so the closure inside `createHomeownerAuth` stays tiny and the
// handler is unit-testable without spinning up Better Auth.
export async function handleHomeownerCreated(
	env: CloudflareBindings,
	db: DrizzleD1Database<typeof schema>,
	user: {
		id: string;
		name: string;
		email?: string | null;
		phoneNumber?: string | null;
	},
): Promise<void> {
	try {
		const { createDal } = await import("../dal");
		const dal = createDal(db);
		await notifyInternalLeadership(env, dal, {
			event: "new_homeowner_internal",
			userId: user.id,
			name: user.name,
			email: user.email ?? null,
			phone: user.phoneNumber ?? null,
		});
	} catch (err) {
		console.error("[HO-AUTH] internal leadership notify failed:", err);
	}
}
 
// Convenience for route handlers — uses c.executionCtx.waitUntil when
// available (production / properly-mocked tests), otherwise falls back to
// a floating promise. Hono throws when executionCtx is unset (e.g. tests
// that don't pass the 4th arg to app.request), so the guard matters.
export function fireInternalNotification(
	c: Context,
	dal: Dal,
	payload: InternalEventPayload,
): void {
	const promise = notifyInternalLeadership(c.env as CloudflareBindings, dal, payload);
	try {
		c.executionCtx.waitUntil(promise);
	} catch {
		void promise.catch((err) =>
			console.error("[INTERNAL-NOTIFY] floating promise rejected", err),
		);
	}
}
 
export async function notifyInternalLeadership(
	env: CloudflareBindings,
	dal: Dal,
	payload: InternalEventPayload,
): Promise<void> {
	const { subject, html } = buildContent(payload);
	const provider = createEmailProvider({
		mailtrapApiToken: env.MAILTRAP_API_TOKEN,
		mailtrapInboxId: env.MAILTRAP_INBOX_ID,
		resendApiKey: env.RESEND_API_KEY,
		mailpitHost: env.MAILPIT_HOST,
		fromEmail: env.RESEND_FROM_EMAIL || "onboarding@resend.dev",
	});
 
	const environment = env.ENVIRONMENT ?? "local";
 
	const recipients =
		payload.event === "landing_lead_internal"
			? LANDING_LEAD_RECIPIENTS
			: INTERNAL_NOTIFICATION_RECIPIENTS;
 
	await Promise.all(
		recipients.map(async (recipient) => {
			let status: "sent" | "failed" = "sent";
			let externalId: string | undefined;
			let errorMessage: string | undefined;
			try {
				const result = await provider.sendEmail({
					to: recipient,
					subject,
					html,
				});
				externalId = result?.id;
			} catch (err) {
				status = "failed";
				errorMessage =
					err instanceof Error ? err.message : "send failed";
				console.error("[INTERNAL-NOTIFY] send failed", {
					recipient,
					event: payload.event,
					err,
				});
			}
 
			try {
				await dal.communicationLog.insert({
					channel: "email",
					recipient,
					actualRecipient: recipient,
					eventType: payload.event,
					status,
					provider: "internal-notify",
					environment,
					subject,
					contentSummary: JSON.stringify({ event: payload.event }),
					transactional: true,
					externalId,
					errorMessage,
				});
			} catch (logErr) {
				console.error("[INTERNAL-NOTIFY] log failed", {
					recipient,
					event: payload.event,
					logErr,
				});
			}
		}),
	);
}
 
// Defensive string coercion — upstream callers may pass undefined/null for
// optional fields (e.g. message), and the inquiry test suite seeds pros
// without businessName. escapeHtml needs a real string.
function esc(value: unknown): string {
	return escapeHtml(String(value ?? ""));
}
 
function buildContent(payload: InternalEventPayload): {
	subject: string;
	html: string;
} {
	switch (payload.event) {
		case "new_lead_internal": {
			const subject = `[Interioring] New lead for ${payload.proName ?? "(unknown pro)"} — ${payload.customerName}`;
			const html = `
<h2>New marketplace lead</h2>
<ul>
  <li><strong>Pro:</strong> ${esc(payload.proName)}</li>
  <li><strong>Customer:</strong> ${esc(payload.customerName)}</li>
  <li><strong>Phone:</strong> ${esc(payload.customerPhone)}</li>
  <li><strong>Inquiry ID:</strong> ${esc(payload.inquiryId)}</li>
</ul>
${payload.message ? `<p><strong>Message:</strong> ${esc(payload.message)}</p>` : ""}
`.trim();
			return { subject, html };
		}
		case "new_pro_internal": {
			const name = payload.businessName || "(no name yet)";
			const subject = `[Interioring] New pro signup — ${name}`;
			const html = `
<h2>New pro signed up</h2>
<ul>
  <li><strong>Business:</strong> ${esc(name)}</li>
  <li><strong>Slug:</strong> ${esc(payload.slug)}</li>
  <li><strong>Pro ID:</strong> ${esc(payload.proId)}</li>
  ${payload.userId ? `<li><strong>User ID:</strong> ${esc(payload.userId)}</li>` : ""}
</ul>
`.trim();
			return { subject, html };
		}
		case "landing_lead_internal": {
			const contact = payload.phone || payload.email || "(no contact)";
			const subject = `[Interioring] New landing-page lead — ${payload.name} (${contact})`;
			const html = `
<h2>New landing-page lead</h2>
<ul>
  <li><strong>Name:</strong> ${esc(payload.name)}</li>
  <li><strong>Phone:</strong> ${esc(payload.phone || "—")}</li>
  <li><strong>Email:</strong> ${esc(payload.email || "—")}</li>
  <li><strong>Locality:</strong> ${esc(payload.locality || "—")}</li>
  <li><strong>Source:</strong> ${esc(payload.source)}</li>
  <li><strong>Lead ID:</strong> ${esc(payload.leadId)}</li>
</ul>
${payload.notes ? `<p><strong>Notes:</strong> ${esc(payload.notes)}</p>` : ""}
`.trim();
			return { subject, html };
		}
		case "new_homeowner_internal": {
			const contact = payload.email || payload.phone || "(no contact)";
			const subject = `[Interioring] New homeowner — ${payload.name} (${contact})`;
			const html = `
<h2>New homeowner signed up</h2>
<ul>
  <li><strong>Name:</strong> ${esc(payload.name)}</li>
  <li><strong>Email:</strong> ${esc(payload.email)}</li>
  <li><strong>Phone:</strong> ${esc(payload.phone)}</li>
  <li><strong>User ID:</strong> ${esc(payload.userId)}</li>
</ul>
`.trim();
			return { subject, html };
		}
	}
}