Repository Public
1import { getDb, getSetting, setSetting } from "./db";2import { renderEmail, sendEmail, siteOrigin, type SendResult } from "./mail";3import { manageTokenOf, typeById, type Appointment } from "./booking/service";4import { LOCATION_LABEL } from "./booking/ics";5import { fmtDateTime, fmtShortDate } from "./booking/tz";6import { statsSummary } from "./stats";78/** Notifications à l'administrateur : adresse personnelle et préférences, réglables dans l'administration. */9export interface NotificationSettings {10 email: string;11 onBooking: boolean;12 onContact: boolean;13 onClientSignup: boolean;14 weeklyStats: boolean;15 lastDigestWeek: string;16}17const DEFAULTS: NotificationSettings = { email: "", onBooking: true, onContact: true, onClientSignup: false, weeklyStats: true, lastDigestWeek: "" };1819export function notificationSettings(): NotificationSettings {20 return { ...DEFAULTS, ...getSetting<Partial<NotificationSettings>>("notifications", {}) };21}22export function saveNotificationSettings(patch: Partial<NotificationSettings>) {23 setSetting("notifications", { ...notificationSettings(), ...patch });24}2526function replyToAddress(): string | undefined {27 return notificationSettings().email || undefined;28}2930export type BookingEvent = "created" | "confirmed" | "cancelled" | "rescheduled" | "reminder";3132function apptFacts(a: Appointment): [string, string][] {33 const t = typeById(a.type_id);34 const facts: [string, string][] = [35 ["Rencontre", t?.title ?? "Rendez-vous"],36 ["Date et heure", fmtDateTime(a.start_utc)],37 ["Durée", `${t?.duration_min ?? Math.round((a.end_utc - a.start_utc) / 60000)} minutes`],38 ];39 if (t) facts.push(["Modalité", [LOCATION_LABEL[t.location_kind], t.location_detail].filter(Boolean).join(" — ")]);40 return facts;41}4243/** Courriels transactionnels d'un rendez-vous (client + administrateur). Envoyés APRÈS la réussite de l'opération. */44export async function sendBookingEmails(a: Appointment, event: BookingEvent, opts: { reason?: string; actor?: "client" | "admin" } = {}): Promise<SendResult[]> {45 const out: SendResult[] = [];46 const token = manageTokenOf(a);47 const manageUrl = token ? `${siteOrigin()}/rendez-vous/gerer/${token}` : undefined;48 const icsUrl = token ? `${siteOrigin()}/api/booking/ics?token=${token}` : undefined;49 const facts = apptFacts(a);50 const pending = a.status === "requested";5152 const client: Record<BookingEvent, { subject: string; title: string; lines: string[] }> = {53 created: pending54 ? {55 subject: "Votre demande de rendez-vous est bien reçue",56 title: "Demande de rendez-vous reçue",57 lines: [`Bonjour ${a.name},`, "Nous avons bien reçu votre demande. Le créneau vous est réservé ; vous recevrez un courriel dès que le rendez-vous sera confirmé."],58 }59 : {60 subject: "Votre rendez-vous est confirmé",61 title: "Rendez-vous confirmé",62 lines: [`Bonjour ${a.name},`, "Votre rendez-vous avec PHI Conseil est confirmé."],63 },64 confirmed: { subject: "Votre rendez-vous est confirmé", title: "Rendez-vous confirmé", lines: [`Bonjour ${a.name},`, "Votre rendez-vous avec PHI Conseil est confirmé."] },65 cancelled: {66 subject: "Votre rendez-vous est annulé",67 title: "Rendez-vous annulé",68 lines: [`Bonjour ${a.name},`, opts.actor === "client" ? "Votre rendez-vous a bien été annulé, comme demandé." : "Votre rendez-vous a dû être annulé.", ...(opts.reason ? [`Motif : ${opts.reason}`] : []), "Vous pouvez réserver un nouveau créneau en tout temps sur notre site."],69 },70 rescheduled: {71 subject: pending ? "Votre demande de report est reçue" : "Votre rendez-vous est déplacé",72 title: pending ? "Demande de report reçue" : "Rendez-vous déplacé",73 lines: [`Bonjour ${a.name},`, pending ? "Votre nouveau créneau est réservé ; il sera confirmé sous peu." : "Voici la nouvelle date de votre rendez-vous."],74 },75 reminder: { subject: "Rappel : votre rendez-vous avec PHI Conseil", title: "Rappel de rendez-vous", lines: [`Bonjour ${a.name},`, "Petit rappel de votre rendez-vous à venir."] },76 };77 const c = client[event];78 if (a.email) {79 const body = renderEmail({80 title: c.title,81 lines: c.lines,82 facts,83 button: event !== "cancelled" && manageUrl ? { label: "Gérer mon rendez-vous", url: manageUrl } : event === "cancelled" ? { label: "Réserver un nouveau créneau", url: `${siteOrigin()}/rendez-vous` } : undefined,84 secondary: event !== "cancelled" && icsUrl && !pending ? { label: "Ajouter à mon agenda (.ics)", url: icsUrl } : undefined,85 footer: "PHI Conseil — www.phiconseil.ca · Les heures sont indiquées à l’heure du Québec (heure de l’Est).",86 });87 out.push(await sendEmail({ to: a.email, subject: c.subject, ...body, kind: event === "reminder" ? "booking_reminder" : event === "created" ? "booking_client" : "booking_update", replyTo: replyToAddress(), appointmentId: a.id }));88 }8990 const n = notificationSettings();91 if (n.email && n.onBooking && event !== "reminder" && !(opts.actor === "admin")) {92 const titles: Record<string, string> = {93 created: pending ? "Nouvelle demande de rendez-vous à valider" : "Nouveau rendez-vous confirmé",94 cancelled: "Rendez-vous annulé par le client",95 rescheduled: "Rendez-vous déplacé par le client",96 confirmed: "Rendez-vous confirmé",97 };98 const body = renderEmail({99 title: titles[event],100 lines: [],101 facts: [["Client", a.name], ["Courriel", a.email], ...(a.phone ? ([["Téléphone", a.phone]] as [string, string][]) : []), ...(a.organization ? ([["Organisation", a.organization]] as [string, string][]) : []), ...facts, ...(a.reason ? ([["Motif", a.reason]] as [string, string][]) : []), ...(a.notes ? ([["Notes", a.notes]] as [string, string][]) : [])],102 button: { label: "Ouvrir dans l’administration", url: `${siteOrigin()}/admin/appointments/${a.id}` },103 footer: "Notification automatique du site PHI Conseil. Réglages : Administration → Paramètres → Notifications.",104 });105 out.push(await sendEmail({ to: n.email, subject: `${titles[event]} — ${a.name} (${fmtShortDate(a.start_utc)})`, ...body, kind: "booking_admin", replyTo: a.email || undefined, appointmentId: a.id }));106 }107 return out;108}109110export async function notifyContactMessage(m: { id: number; name: string; email: string; organization: string; subject: string; message: string }) {111 const n = notificationSettings();112 if (!n.email || !n.onContact) return null;113 const body = renderEmail({114 title: "Nouveau message depuis le site",115 lines: [],116 facts: [["Nom", m.name], ["Courriel", m.email], ...(m.organization ? ([["Organisation", m.organization]] as [string, string][]) : []), ["Sujet", m.subject], ["Message", m.message]],117 button: { label: "Ouvrir dans l’administration", url: `${siteOrigin()}/admin/messages/${m.id}` },118 footer: "Notification automatique du site PHI Conseil. Répondez directement à ce courriel pour écrire à l’expéditeur.",119 });120 return sendEmail({ to: n.email, subject: `[Site PHI Conseil] ${m.subject}`, ...body, kind: "contact_notification", replyTo: m.email });121}122123export async function notifyClientSignup(u: { name: string; email: string }) {124 const n = notificationSettings();125 if (!n.email || !n.onClientSignup) return null;126 const body = renderEmail({ title: "Nouveau compte client", lines: ["Un nouveau compte vient d’être créé dans l’espace client."], facts: [["Nom", u.name], ["Courriel", u.email]], button: { label: "Voir les clients", url: `${siteOrigin()}/admin/clients` } });127 return sendEmail({ to: n.email, subject: `Nouveau compte client — ${u.name}`, ...body, kind: "contact_notification" });128}129130/** Identifiant de semaine ISO approximatif (lundi) pour n'envoyer qu'un sommaire par semaine. */131function weekKey(now: number): string {132 const d = new Date(now);133 const monday = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - ((d.getUTCDay() + 6) % 7)));134 return monday.toISOString().slice(0, 10);135}136137/** Sommaire hebdomadaire (fréquentation, messages, rendez-vous), envoyé le lundi si l'option est active. */138export async function sendWeeklyDigestIfDue(now = Date.now(), force = false): Promise<SendResult | null> {139 const n = notificationSettings();140 if (!n.email || (!n.weeklyStats && !force)) return null;141 const wk = weekKey(now);142 if (!force && (n.lastDigestWeek === wk || new Date(now).getUTCDay() !== 1 || new Date(now).getUTCHours() < 12)) return null;143 const s = statsSummary(7, now);144 const db = getDb();145 const since = now - 7 * 24 * 3600_000;146 const messages = (db.prepare("SELECT count(*) AS n FROM contact_messages WHERE created_at >= ?").get(since) as { n: number }).n;147 const bookings = (db.prepare("SELECT count(*) AS n FROM appointments WHERE created_at >= ?").get(since) as { n: number }).n;148 const upcoming = (db.prepare("SELECT count(*) AS n FROM appointments WHERE start_utc >= ? AND start_utc < ? AND status IN ('requested','confirmed')").get(now, now + 7 * 24 * 3600_000) as { n: number }).n;149 const pending = (db.prepare("SELECT count(*) AS n FROM appointments WHERE status = 'requested' AND start_utc >= ?").get(now) as { n: number }).n;150 const body = renderEmail({151 title: "Votre semaine sur phiconseil.ca",152 lines: ["Voici le sommaire des sept derniers jours."],153 facts: [154 ["Pages vues", String(s.totals.views)],155 ["Visiteurs (par jour, cumulés)", String(s.totals.visitors)],156 ["Pages les plus consultées", s.top.slice(0, 5).map((t) => `${t.path} (${t.views})`).join("\n") || "—"],157 ["Nouveaux messages", String(messages)],158 ["Rendez-vous réservés", String(bookings)],159 ["Rendez-vous à venir (7 jours)", String(upcoming)],160 ["Demandes à valider", String(pending)],161 ],162 button: { label: "Ouvrir le tableau de bord", url: `${siteOrigin()}/admin` },163 footer: "Statistiques internes, agrégées et sans témoin. Pour ne plus recevoir ce sommaire : Administration → Paramètres → Notifications.",164 });165 const r = await sendEmail({ to: n.email, subject: "Sommaire hebdomadaire — PHI Conseil", ...body, kind: "contact_notification" });166 if (!force) saveNotificationSettings({ lastDigestWeek: wk });167 return r;168}169