/** * Welcome mail for a newly added team member. * * An admin adding a person should not have to copy a link out of the admin * screen: the account, its username and a one-time sign-in link go straight to * the person's inbox. Delivery failures are reported back to the admin (who can * still copy the link), never swallowed. */ import { getEmailTransportSettings } from "@/db/settings"; import { resolveEmailTransport } from "@/lib/email"; export interface WelcomeUser { id: string; email: string; username: string; firstName: string; displayName?: string | null; } export interface WelcomeResult { delivered: boolean; transport: string | null; } function escapeHtml(value: string): string { return value .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """) .replaceAll("'", "'"); } /** Send the sign-in details. Never throws; the caller reports the outcome. */ export async function sendWelcomeEmail( user: WelcomeUser, url: string, ): Promise { try { const transport = resolveEmailTransport(await getEmailTransportSettings()); const name = escapeHtml(user.firstName || user.displayName || user.email); const login = escapeHtml(user.username || user.email); const email = escapeHtml(user.email); const link = escapeHtml(url); await transport.send({ to: user.email, subject: "Your Media Team Hub sign-in details", html: `

Welcome, ${name}

An account has been created for you on Media Team Hub, the team's scheduling and training site.

Sign in: ${email}
Username: ${login}

Sign in

The link expires in 7 days and works once. If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.

Media Team Hub · Glenloch

`, text: [ `Welcome, ${user.firstName || user.displayName || user.email}`, "", "An account has been created for you on Media Team Hub, the team's scheduling and training site.", "", `Sign in: ${user.email}`, `Username: ${user.username || user.email}`, "", `Open this link to sign in (expires in 7 days, single use):`, url, "", "If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.", "", "Media Team Hub · Glenloch", ].join("\n"), templateKey: "user.welcome", dedupeKey: `user.welcome:${user.id}:${Date.now()}`, }); return { delivered: true, transport: transport.name }; } catch (error) { console.error( `[welcome] delivery failed for ${user.email}:`, error instanceof Error ? error.message : error, ); return { delivered: false, transport: null }; } }