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 | 3x 3x 9x 9x 9x 1x 1x 8x 8x 8x 8x 8x 2x 8x 4x 4x 1x 5x 4x 5x 5x 2x 1x 33x 33x 33x 33x 33x 55x 55x 55x 48x 7x 7x 7x 55x 55x 4x 55x 52x 152x 33x 7x 7x 7x 5x 5x 5x 5x 4x 4x 4x 4x 2x 2x 2x 3x 3x 3x 3x 3x 3x 12x 12x 12x 12x | // 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 { DrizzleD1Database } from "drizzle-orm/d1";
import type { Context } from "hono";
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",
"surendra@interioring.com",
] as const;
// Landing-page leads and new WhatsApp chats 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;
entryType?: string | null;
utmSource?: string | null;
utmMedium?: string | null;
utmCampaign?: string | null;
}
| {
event: "consultation_lead_internal";
bookingId: string | number;
reference: string;
phone: string;
details: string | null;
sourcePage: string | null;
}
| {
event: "whatsapp_chat_internal";
conversationId: number;
name: string | null;
phone: string;
contactType: "customer" | "unknown";
inquiryId: number | null;
firstMessage: string;
inboxUrl: 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> {
// DAL construction is inside its own guard — signup must never fail because
// of a notification/consent side effect.
let dal: Dal;
try {
const { createDal } = await import("../dal");
dal = createDal(db);
} catch (err) {
console.error("[HO-AUTH] dal init failed:", err);
return;
}
try {
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);
}
// Communication-logging consent (spec: communication_history_log). The
// signup form requires the consent checkbox before submitting, so account
// creation implies consent — record it with a hash of the exact copy shown.
// Separate try: a consent-write failure must never break signup.
try {
const { communicationConsentTextHash } = await import("./consent");
await dal.consentRecords.record({
userId: user.id,
userType: "homeowner",
consentType: "communication_logging",
consentTextHash: await communicationConsentTextHash(),
});
} catch (err) {
console.error("[HO-AUTH] consent record write failed:", err);
}
// Attach any /book-consultation requests made anonymously (before this
// account existed) with the same phone. Both sides store E.164 — the
// consultation route via parseIndianPhone, phone-OTP signup via the exact
// string PhoneOtpForm sent to better-auth — so this is a direct match, no
// normalization needed. Separate try: never break signup.
if (user.phoneNumber) {
try {
await dal.consultationBookings.linkToHomeowner(user.phoneNumber, user.id);
} catch (err) {
console.error("[HO-AUTH] consultation booking link 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.
//
// `onSent` runs only when every email went out. Callers that record "support
// has been told" do it there, so a failed send (e.g. a provider 429) leaves
// the record unset and the next contact tries again (#1085 QA defect 2).
export function fireInternalNotification(
c: Context,
dal: Dal,
payload: InternalEventPayload,
onSent?: () => Promise<void>,
): void {
const promise = notifyInternalLeadership(
c.env as CloudflareBindings,
dal,
payload,
).then(async (allSent) => {
if (allSent && onSent) await onSent();
});
try {
c.executionCtx.waitUntil(promise);
} catch {
void promise.catch((err) =>
console.error("[INTERNAL-NOTIFY] floating promise rejected", err),
);
}
}
/** Sends the event's emails and logs each one. Resolves true when all sent. */
export async function notifyInternalLeadership(
env: CloudflareBindings,
dal: Dal,
payload: InternalEventPayload,
): Promise<boolean> {
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" ||
payload.event === "consultation_lead_internal" ||
payload.event === "whatsapp_chat_internal"
? LANDING_LEAD_RECIPIENTS
: INTERNAL_NOTIFICATION_RECIPIENTS;
const statuses = 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.notificationDeliveryLog.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,
});
}
return status;
}),
);
return statuses.every((status) => status === "sent");
}
// 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>Entry:</strong> ${esc(payload.entryType || "—")}</li>
<li><strong>Campaign:</strong> ${esc(
[payload.utmSource, payload.utmMedium, payload.utmCampaign]
.filter(Boolean)
.join(" / ") || "—",
)}</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 "consultation_lead_internal": {
const subject = `[Interioring] New consultation booking — ${payload.phone} (${payload.reference})`;
const html = `
<h2>New free-consultation booking</h2>
<ul>
<li><strong>Reference:</strong> ${esc(payload.reference)}</li>
<li><strong>Phone:</strong> ${esc(payload.phone)}</li>
<li><strong>Source:</strong> ${esc(payload.sourcePage || "—")}</li>
<li><strong>Booking ID:</strong> ${esc(payload.bookingId)}</li>
</ul>
${payload.details ? `<p><strong>Details:</strong> ${esc(payload.details)}</p>` : ""}
`.trim();
return { subject, html };
}
case "whatsapp_chat_internal": {
const phone = `+${payload.phone}`;
const subject = `[Interioring] New WhatsApp chat — ${payload.name || phone}`;
// By code point, so an emoji is never cut in half.
const chars = Array.from(payload.firstMessage);
const text =
chars.length > 500
? `${chars.slice(0, 500).join("")}…`
: payload.firstMessage;
const html = `
<h2>New WhatsApp chat</h2>
<ul>
<li><strong>Name:</strong> ${esc(payload.name || "—")}</li>
<li><strong>Phone:</strong> ${esc(phone)}</li>
<li><strong>Contact type:</strong> ${esc(payload.contactType)}</li>
${payload.inquiryId ? `<li><strong>Inquiry ID:</strong> ${esc(payload.inquiryId)}</li>` : ""}
</ul>
<p><strong>First message:</strong> ${esc(text)}</p>
<p><a href="${esc(payload.inboxUrl)}">Open the chat in the inbox</a> to reply.</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 };
}
}
}
|