SPB Git

Repository Public

mail.ts 7.7 KB 179 lines typescript

1import nodemailer from "nodemailer";2import { getDb } from "./db";34/**5 * Courriels transactionnels. Transport : Resend (API HTTPS), SMTP, ou « log » (aucun envoi).6 * Chaque message est consigné dans la table `outbox` avec son statut RÉEL7 * (sent / failed / logged) : un courriel non envoyé n'est jamais présenté comme livré.8 */9export type MailKind =10  | "contact_notification"11  | "booking_client"12  | "booking_admin"13  | "booking_reminder"14  | "booking_update"15  | "account_verify"16  | "account_reset"17  | "test";1819export interface OutgoingMail {20  to: string;21  subject: string;22  text: string;23  html: string;24  kind: MailKind;25  replyTo?: string;26  appointmentId?: number;27}2829export type Transport = "resend" | "smtp" | "log";30export type SendResult = { status: "sent" | "failed" | "logged"; id?: string; error?: string };31export type Sender = (mail: OutgoingMail) => Promise<SendResult>;3233export function mailTransport(): Transport {34  const forced = process.env.MAIL_TRANSPORT;35  if (forced === "resend" || forced === "smtp" || forced === "log") return forced;36  if (process.env.RESEND_API_KEY) return "resend";37  if (process.env.SMTP_HOST) return "smtp";38  return "log";39}4041export function mailFrom(): string {42  return process.env.MAIL_FROM || "PHI Conseil <no-reply@phiconseil.ca>";43}4445const resendSender: Sender = async (mail) => {46  try {47    const res = await fetch("https://api.resend.com/emails", {48      method: "POST",49      headers: { Authorization: `Bearer ${process.env.RESEND_API_KEY}`, "Content-Type": "application/json" },50      body: JSON.stringify({51        from: mailFrom(),52        to: [mail.to],53        subject: mail.subject,54        text: mail.text,55        html: mail.html,56        ...(mail.replyTo ? { reply_to: mail.replyTo } : {}),57      }),58      signal: AbortSignal.timeout(15_000),59    });60    const body = (await res.json().catch(() => ({}))) as { id?: string; message?: string; name?: string };61    if (!res.ok) return { status: "failed", error: `Resend ${res.status} ${body.name ?? ""} ${body.message ?? ""}`.trim().slice(0, 300) };62    return { status: "sent", id: body.id };63  } catch (e) {64    return { status: "failed", error: e instanceof Error ? e.message.slice(0, 300) : "erreur réseau" };65  }66};6768const smtpSender: Sender = async (mail) => {69  try {70    const t = nodemailer.createTransport({71      host: process.env.SMTP_HOST,72      port: Number(process.env.SMTP_PORT ?? 587),73      secure: process.env.SMTP_SECURE === "true",74      auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS } : undefined,75    });76    const info = await t.sendMail({ from: mailFrom(), to: mail.to, replyTo: mail.replyTo, subject: mail.subject, text: mail.text, html: mail.html });77    return { status: "sent", id: info.messageId };78  } catch (e) {79    return { status: "failed", error: e instanceof Error ? e.message.slice(0, 300) : "erreur SMTP" };80  }81};8283const logSender: Sender = async () => ({ status: "logged" });8485let override: Sender | null = null;86/** Pour les tests : remplace le transport. */87export function setSenderForTests(s: Sender | null) {88  override = s;89}9091export async function sendEmail(mail: OutgoingMail): Promise<SendResult> {92  const transport = mailTransport();93  const sender = override ?? (transport === "resend" ? resendSender : transport === "smtp" ? smtpSender : logSender);94  let result: SendResult;95  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(mail.to)) result = { status: "failed", error: "Aucun destinataire valide configuré." };96  else result = await sender(mail);97  try {98    getDb()99      .prepare(100        "INSERT INTO outbox (created_at, kind, to_email, subject, body_text, status, transport, provider_id, error, appointment_id) VALUES (?,?,?,?,?,?,?,?,?,?)",101      )102      .run(103        Date.now(),104        mail.kind,105        mail.to,106        mail.subject,107        mail.text,108        result.status,109        override ? "test" : transport,110        result.id ?? "",111        result.error ?? "",112        mail.appointmentId ?? null,113      );114  } catch (e) {115    console.error("[mail] journalisation impossible", e instanceof Error ? e.message : e);116  }117  if (result.status === "failed") console.error(`[mail] échec (${mail.kind}) : ${result.error}`);118  return result;119}120121/* ---------------- Gabarit ---------------- */122export function escapeHtml(s: string) {123  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");124}125126export interface EmailContent {127  title: string;128  lines: string[];129  /** Tableau « étiquette : valeur ». */130  facts?: [string, string][];131  button?: { label: string; url: string };132  secondary?: { label: string; url: string };133  footer?: string;134}135136/** Courriel sobre aux couleurs de la marque, en texte et en HTML (toutes les valeurs sont échappées). */137export function renderEmail(c: EmailContent): { text: string; html: string } {138  const text = [139    c.title,140    "",141    ...c.lines,142    ...(c.facts?.length ? ["", ...c.facts.map(([k, v]) => `${k} : ${v}`)] : []),143    ...(c.button ? ["", `${c.button.label} : ${c.button.url}`] : []),144    ...(c.secondary ? [`${c.secondary.label} : ${c.secondary.url}`] : []),145    "",146    c.footer ?? "PHI Conseil — www.phiconseil.ca",147  ].join("\n");148  const facts = c.facts?.length149    ? `<table role="presentation" cellpadding="0" cellspacing="0" style="margin:20px 0;width:100%;border-top:1px solid #e3cfae">${c.facts150        .map(151          ([k, v]) =>152            `<tr><td style="padding:10px 12px 10px 0;border-bottom:1px solid #f0e4d2;color:#5b6771;font-size:14px;white-space:nowrap;vertical-align:top">${escapeHtml(k)}</td><td style="padding:10px 0;border-bottom:1px solid #f0e4d2;color:#1f2a33;font-size:15px">${escapeHtml(v).replace(/\n/g, "<br>")}</td></tr>`,153        )154        .join("")}</table>`155    : "";156  const button = c.button157    ? `<p style="margin:28px 0 8px"><a href="${escapeHtml(c.button.url)}" style="display:inline-block;background:#597992;color:#ffffff;text-decoration:none;padding:13px 26px;border-radius:999px;font-size:15px;font-weight:600">${escapeHtml(c.button.label)}</a></p>`158    : "";159  const secondary = c.secondary160    ? `<p style="margin:8px 0;font-size:14px"><a href="${escapeHtml(c.secondary.url)}" style="color:#233a52">${escapeHtml(c.secondary.label)}</a></p>`161    : "";162  const html = `<!doctype html><html lang="fr-CA"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head><body style="margin:0;background:#f5eee4;font-family:-apple-system,'Segoe UI',Helvetica,Arial,sans-serif;color:#3a4652">163<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f5eee4;padding:28px 12px"><tr><td align="center">164<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;background:#ffffff;border-radius:18px;overflow:hidden">165<tr><td style="padding:22px 28px;border-bottom:2px solid #c7a075"><span style="font-family:Georgia,'Times New Roman',serif;font-size:22px;color:#1d3047"><span style="color:#c7a075">Φ</span>&nbsp; PHI Conseil</span></td></tr>166<tr><td style="padding:28px">167<h1 style="margin:0 0 16px;font-family:Georgia,'Times New Roman',serif;font-weight:500;font-size:24px;line-height:1.25;color:#1d3047">${escapeHtml(c.title)}</h1>168${c.lines.map((l) => `<p style="margin:0 0 12px;font-size:15px;line-height:1.6">${escapeHtml(l)}</p>`).join("")}169${facts}${button}${secondary}170</td></tr>171<tr><td style="padding:18px 28px;background:#faf7f1;color:#5b6771;font-size:12px;line-height:1.5">${escapeHtml(c.footer ?? "PHI Conseil — www.phiconseil.ca")}</td></tr>172</table></td></tr></table></body></html>`;173  return { text, html };174}175176export function siteOrigin(): string {177  return (process.env.SITE_URL || process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000").replace(/\/$/, "");178}179
Files main
Menu

Theme