SPB Git

Repository Public

actions.ts 17.5 KB 327 lines typescript

1"use server";23import { revalidatePath } from "next/cache";4import { redirect } from "next/navigation";5import QRCode from "qrcode";6import { requireAdmin, requestMeta, setSessionCookie } from "@/server/session";7import { audit, beginTotpSetup, changePassword, confirmTotp, deleteClient, disableTotp, pendingTotpSecret, userById } from "@/server/auth";8import { getDb } from "@/server/db";9import { randomToken, sha256 } from "@/server/crypto";10import { deleteMedia, updateAlt } from "@/server/media";11import { SlotUnavailableError, anonymize, appointmentById, reschedule, saveBookingSettings, setStatus } from "@/server/booking/service";12import { localToUtc } from "@/server/booking/tz";13import { saveNotificationSettings, sendBookingEmails, sendWeeklyDigestIfDue } from "@/server/notify";14import { mailTransport, renderEmail, sendEmail } from "@/server/mail";15import type { FormState } from "@/components/admin/ActionForm";1617/** Toutes les actions ci-dessous exigent une session administrateur valide (vérifiée côté serveur). */18const str = (d: FormData, k: string, max = 500) => String(d.get(k) ?? "").trim().slice(0, max);19const int = (d: FormData, k: string, min: number, max: number, def: number) => {20  const n = Math.round(Number(d.get(k)));21  return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : def;22};23const refresh = () => revalidatePath("/admin", "layout");2425/* ---------- Messages ---------- */26export async function messageStatusAction(_p: FormState, d: FormData): Promise<FormState> {27  const { user } = await requireAdmin();28  const status = str(d, "status");29  if (!["new", "read", "archived"].includes(status)) return { error: "Statut invalide." };30  getDb().prepare("UPDATE contact_messages SET status = ? WHERE id = ?").run(status, int(d, "id", 1, 1e12, 0));31  audit("message.status", { userId: user.id, target: `message:${d.get("id")}`, detail: status });32  refresh();33  return { ok: "Mis à jour." };34}35export async function messageDeleteAction(_p: FormState, d: FormData): Promise<FormState> {36  const { user } = await requireAdmin();37  getDb().prepare("DELETE FROM contact_messages WHERE id = ?").run(int(d, "id", 1, 1e12, 0));38  audit("message.deleted", { userId: user.id, target: `message:${d.get("id")}` });39  redirect("/admin/messages");40}4142/* ---------- Clients ---------- */43export async function clientToggleAction(_p: FormState, d: FormData): Promise<FormState> {44  const { user } = await requireAdmin();45  const id = int(d, "id", 1, 1e12, 0);46  const db = getDb();47  db.prepare("UPDATE users SET disabled = 1 - disabled WHERE id = ? AND role = 'client'").run(id);48  db.prepare("DELETE FROM sessions WHERE user_id = ? AND (SELECT disabled FROM users WHERE id = ?) = 1").run(id, id);49  audit("client.toggled", { userId: user.id, target: `user:${id}` });50  refresh();51  return { ok: "Mis à jour." };52}53export async function clientDeleteAction(_p: FormState, d: FormData): Promise<FormState> {54  const { user } = await requireAdmin();55  const id = int(d, "id", 1, 1e12, 0);56  if (!deleteClient(id)) return { error: "Suppression impossible." };57  audit("client.deleted_by_admin", { userId: user.id, target: `user:${id}` });58  refresh();59  return { ok: "Compte supprimé." };60}6162/* ---------- Médias ---------- */63export async function mediaAltAction(_p: FormState, d: FormData): Promise<FormState> {64  await requireAdmin();65  const id = str(d, "id", 12);66  if (!/^[a-f0-9]{12}$/.test(id)) return { error: "Image inconnue." };67  updateAlt(id, str(d, "alt", 300));68  refresh();69  return { ok: "Texte alternatif enregistré." };70}71export async function mediaDeleteAction(_p: FormState, d: FormData): Promise<FormState> {72  const { user } = await requireAdmin();73  const id = str(d, "id", 12);74  if (!/^[a-f0-9]{12}$/.test(id)) return { error: "Image inconnue." };75  const r = deleteMedia(id);76  if (!r.ok) return { error: `Image utilisée dans : ${r.usedBy.join(", ")}. Retirez-la d’abord de ces contenus.` };77  audit("media.deleted", { userId: user.id, target: id });78  refresh();79  return { ok: "Image supprimée." };80}8182/* ---------- Rendez-vous : types ---------- */83export async function typeSaveAction(_p: FormState, d: FormData): Promise<FormState> {84  const { user } = await requireAdmin();85  const id = int(d, "id", 0, 1e12, 0);86  const title = str(d, "title", 120);87  const slug = (str(d, "slug", 80) || title)88    .toLowerCase()89    .normalize("NFD")90    .replace(/[̀-ͯ]/g, "")91    .replace(/[^a-z0-9]+/g, "-")92    .replace(/^-|-$/g, "");93  if (title.length < 2 || !slug) return { error: "Le titre est requis." };94  const kind = str(d, "location_kind");95  if (!["visio", "telephone", "presentiel"].includes(kind)) return { error: "Modalité invalide." };96  const vals = [slug, title, str(d, "description", 600), int(d, "duration_min", 15, 480, 30), kind, str(d, "location_detail", 300), int(d, "min_notice_hours", 0, 720, 24), int(d, "buffer_min", 0, 120, 15), int(d, "max_days_ahead", 1, 365, 60), d.get("active") === "on" ? 1 : 0, int(d, "sort", 0, 999, 0)];97  if (Number(vals[3]) % 15 !== 0) return { error: "La durée doit être un multiple de 15 minutes." };98  const db = getDb();99  try {100    if (id) db.prepare("UPDATE appointment_types SET slug=?, title=?, description=?, duration_min=?, location_kind=?, location_detail=?, min_notice_hours=?, buffer_min=?, max_days_ahead=?, active=?, sort=? WHERE id=?").run(...vals, id);101    else db.prepare("INSERT INTO appointment_types (slug, title, description, duration_min, location_kind, location_detail, min_notice_hours, buffer_min, max_days_ahead, active, sort) VALUES (?,?,?,?,?,?,?,?,?,?,?)").run(...vals);102  } catch {103    return { error: "Un autre type utilise déjà cet identifiant." };104  }105  audit("booking.type_saved", { userId: user.id, target: slug });106  refresh();107  return { ok: "Type enregistré." };108}109export async function typeDeleteAction(_p: FormState, d: FormData): Promise<FormState> {110  const { user } = await requireAdmin();111  const id = int(d, "id", 1, 1e12, 0);112  const db = getDb();113  const used = (db.prepare("SELECT count(*) AS n FROM appointments WHERE type_id = ?").get(id) as { n: number }).n;114  if (used) {115    db.prepare("UPDATE appointment_types SET active = 0 WHERE id = ?").run(id);116    refresh();117    return { ok: "Ce type a déjà des rendez-vous : il a été désactivé plutôt que supprimé." };118  }119  db.prepare("DELETE FROM appointment_types WHERE id = ?").run(id);120  audit("booking.type_deleted", { userId: user.id, target: String(id) });121  refresh();122  return { ok: "Type supprimé." };123}124125/* ---------- Rendez-vous : disponibilités ---------- */126function parseRanges(text: string): [number, number][] | null {127  const out: [number, number][] = [];128  for (const part of text.split(/[,;]/).map((s) => s.trim()).filter(Boolean)) {129    const m = /^(\d{1,2})[:h](\d{2})?\s*[-–à]\s*(\d{1,2})[:h](\d{2})?$/i.exec(part.replace(/\s+/g, " "));130    if (!m) return null;131    const a = Number(m[1]) * 60 + Number(m[2] ?? 0);132    const b = Number(m[3]) * 60 + Number(m[4] ?? 0);133    if (a < 0 || b > 1440 || b <= a || a % 15 || b % 15) return null;134    out.push([a, b]);135  }136  return out;137}138export async function rulesSaveAction(_p: FormState, d: FormData): Promise<FormState> {139  const { user } = await requireAdmin();140  const all: [number, number, number][] = [];141  const names = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"];142  for (let wd = 1; wd <= 7; wd++) {143    const ranges = parseRanges(str(d, `wd${wd}`, 200));144    if (!ranges) return { error: `Plages invalides pour ${names[wd - 1]}. Format : 09:00-12:00, 13:00-17:00 (par tranches de 15 minutes).` };145    for (const [a, b] of ranges) all.push([wd, a, b]);146  }147  const db = getDb();148  db.exec("BEGIN IMMEDIATE");149  try {150    db.exec("DELETE FROM availability_rules");151    const ins = db.prepare("INSERT INTO availability_rules (weekday, start_min, end_min) VALUES (?,?,?)");152    for (const r of all) ins.run(...r);153    db.exec("COMMIT");154  } catch (e) {155    db.exec("ROLLBACK");156    throw e;157  }158  audit("booking.rules_saved", { userId: user.id });159  refresh();160  return { ok: "Heures de travail enregistrées." };161}162function localInput(v: string): number | null {163  const m = /^(\d{4}-\d{2}-\d{2})(?:T(\d{2}):(\d{2}))?$/.exec(v);164  if (!m) return null;165  return localToUtc(m[1], m[2] ? Number(m[2]) * 60 + Number(m[3]) : 0);166}167export async function exceptionAddAction(_p: FormState, d: FormData): Promise<FormState> {168  const { user } = await requireAdmin();169  const kind = str(d, "kind");170  if (kind !== "block" && kind !== "open") return { error: "Type invalide." };171  let start = localInput(str(d, "start"));172  let end = localInput(str(d, "end") || str(d, "start"));173  if (start === null || end === null) return { error: "Dates invalides (ou heure inexistante ce jour-là)." };174  if (d.get("allday") === "on" || !str(d, "start").includes("T")) {175    start = localInput(str(d, "start").slice(0, 10))!;176    const endDay = new Date(`${(str(d, "end") || str(d, "start")).slice(0, 10)}T00:00:00Z`);177    endDay.setUTCDate(endDay.getUTCDate() + 1);178    end = localInput(endDay.toISOString().slice(0, 10))!;179  }180  if (end <= start) return { error: "La fin doit être après le début." };181  getDb().prepare("INSERT INTO availability_exceptions (kind, start_utc, end_utc, note) VALUES (?,?,?,?)").run(kind, start, end, str(d, "note", 200));182  audit("booking.exception_added", { userId: user.id, detail: kind });183  refresh();184  return { ok: kind === "block" ? "Plage bloquée." : "Ouverture ajoutée." };185}186export async function exceptionDeleteAction(_p: FormState, d: FormData): Promise<FormState> {187  const { user } = await requireAdmin();188  getDb().prepare("DELETE FROM availability_exceptions WHERE id = ?").run(int(d, "id", 1, 1e12, 0));189  audit("booking.exception_deleted", { userId: user.id });190  refresh();191  return { ok: "Supprimé." };192}193export async function bookingSettingsAction(_p: FormState, d: FormData): Promise<FormState> {194  const { user } = await requireAdmin();195  saveBookingSettings({ autoConfirm: d.get("autoConfirm") === "on", reminderHours: int(d, "reminderHours", 0, 168, 24), retentionDays: int(d, "retentionDays", 0, 3650, 365) });196  audit("booking.settings_saved", { userId: user.id });197  refresh();198  return { ok: "Réglages enregistrés." };199}200export async function icsRotateAction(): Promise<FormState> {201  const { user } = await requireAdmin();202  saveBookingSettings({ icsToken: randomToken(24) });203  audit("booking.ics_rotated", { userId: user.id });204  refresh();205  return { ok: "Nouveau lien généré : l’ancien ne fonctionne plus." };206}207208/* ---------- Rendez-vous : gestion ---------- */209export async function appointmentAction(_p: FormState, d: FormData): Promise<FormState> {210  const { user } = await requireAdmin();211  const id = int(d, "id", 1, 1e12, 0);212  const op = str(d, "op");213  const a = appointmentById(id);214  if (!a) return { error: "Rendez-vous introuvable." };215  try {216    if (op === "confirm") {217      const u = setStatus(id, "confirmed")!;218      await sendBookingEmails(u, "confirmed", { actor: "admin" });219    } else if (op === "cancel") {220      const reason = str(d, "reason", 300);221      const u = setStatus(id, "cancelled", reason)!;222      await sendBookingEmails({ ...u, manage_token_enc: a.manage_token_enc }, "cancelled", { actor: "admin", reason });223    } else if (op === "complete") {224      setStatus(id, "completed");225    } else if (op === "reschedule") {226      const start = Number(d.get("start"));227      if (!Number.isFinite(start) || start <= 0) return { error: "Choisissez un nouveau créneau." };228      const u = reschedule(id, start, { byAdmin: true });229      await sendBookingEmails(u, "rescheduled", { actor: "admin" });230    } else if (op === "notes") {231      getDb().prepare("UPDATE appointments SET admin_notes = ?, updated_at = ? WHERE id = ?").run(str(d, "admin_notes", 2000), Date.now(), id);232    } else if (op === "anonymize") {233      setStatus(id, a.status === "completed" ? "completed" : "cancelled", "Données supprimées");234      anonymize(id);235    } else return { error: "Action inconnue." };236  } catch (e) {237    if (e instanceof SlotUnavailableError) return { error: "Ce créneau n’est pas disponible (conflit avec un autre rendez-vous ou hors disponibilités)." };238    throw e;239  }240  audit(`appointment.${op}`, { userId: user.id, target: `appointment:${id}` });241  refresh();242  const done: Record<string, string> = { confirm: "Rendez-vous confirmé ; le client est avisé.", cancel: "Rendez-vous annulé ; le client est avisé.", complete: "Marqué comme terminé.", reschedule: "Rendez-vous déplacé ; le client est avisé.", notes: "Notes enregistrées.", anonymize: "Renseignements personnels supprimés." };243  return { ok: done[op] };244}245246/* ---------- Notifications ---------- */247export async function notificationsSaveAction(_p: FormState, d: FormData): Promise<FormState> {248  const { user } = await requireAdmin();249  const email = str(d, "email", 254).toLowerCase();250  if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return { error: "Adresse courriel invalide." };251  saveNotificationSettings({ email, onBooking: d.get("onBooking") === "on", onContact: d.get("onContact") === "on", onClientSignup: d.get("onClientSignup") === "on", weeklyStats: d.get("weeklyStats") === "on" });252  audit("notifications.saved", { userId: user.id });253  refresh();254  return { ok: "Préférences enregistrées." };255}256export async function notificationsTestAction(): Promise<FormState> {257  await requireAdmin();258  const { notificationSettings } = await import("@/server/notify");259  const n = notificationSettings();260  if (!n.email) return { error: "Enregistrez d’abord une adresse de notification." };261  const body = renderEmail({ title: "Courriel de test", lines: ["Si vous lisez ce message, les notifications du site PHI Conseil arrivent bien à cette adresse."], footer: "Envoyé depuis Administration → Notifications." });262  const r = await sendEmail({ to: n.email, subject: "Test des notifications — PHI Conseil", ...body, kind: "test" });263  refresh();264  if (r.status === "sent") return { ok: `Courriel de test envoyé à ${n.email}.` };265  if (r.status === "logged") return { error: `Aucun envoi réel : le transport de courriel est « ${mailTransport()} » sur cet environnement.` };266  return { error: `Échec de l’envoi : ${r.error ?? "erreur inconnue"}` };267}268export async function digestNowAction(): Promise<FormState> {269  await requireAdmin();270  const r = await sendWeeklyDigestIfDue(Date.now(), true);271  refresh();272  if (!r) return { error: "Enregistrez d’abord une adresse de notification." };273  return r.status === "sent" ? { ok: "Sommaire envoyé." } : { error: r.status === "logged" ? "Aucun envoi réel sur cet environnement (transport « log »)." : `Échec : ${r.error}` };274}275276/* ---------- Sécurité ---------- */277export async function passwordChangeAction(_p: FormState, d: FormData): Promise<FormState> {278  const { user } = await requireAdmin();279  const next = String(d.get("next") ?? "");280  if (next !== String(d.get("confirm") ?? "")) return { error: "Les deux mots de passe ne correspondent pas." };281  const meta = await requestMeta();282  const r = changePassword({ userId: user.id, current: String(d.get("current") ?? ""), next, ipHash: meta.ipHash, userAgent: meta.userAgent });283  if (!r.ok) return { error: r.error };284  await setSessionCookie("admin", r.token);285  return { ok: "Mot de passe modifié. Toutes les autres sessions ont été fermées." };286}287export async function recoveryEmailAction(_p: FormState, d: FormData): Promise<FormState> {288  const { user } = await requireAdmin();289  const email = str(d, "email", 254).toLowerCase();290  if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return { error: "Adresse courriel invalide." };291  try {292    getDb().prepare("UPDATE users SET email = ?, updated_at = ? WHERE id = ?").run(email || null, Date.now(), user.id);293  } catch {294    return { error: "Cette adresse est déjà utilisée par un autre compte." };295  }296  audit("security.recovery_email", { userId: user.id });297  return { ok: email ? "Adresse de récupération enregistrée." : "Adresse de récupération retirée." };298}299export async function totpBeginAction(): Promise<FormState & { secret?: string; qr?: string }> {300  const { user } = await requireAdmin();301  if (userById(user.id)?.totp_enabled) return { error: "La vérification en deux étapes est déjà active." };302  const secret = beginTotpSetup(user.id);303  const uri = `otpauth://totp/${encodeURIComponent(`PHI Conseil:${user.username ?? "admin"}`)}?secret=${secret}&issuer=${encodeURIComponent("PHI Conseil")}&algorithm=SHA1&digits=6&period=30`;304  return { ok: "", secret, qr: await QRCode.toDataURL(uri, { margin: 1, width: 220 }) };305}306export async function totpConfirmAction(_p: FormState, d: FormData): Promise<FormState & { codes?: string[] }> {307  const { user } = await requireAdmin();308  if (!pendingTotpSecret(user.id)) return { error: "Recommencez l’activation." };309  const codes = confirmTotp(user.id, str(d, "code", 12));310  if (!codes) return { error: "Code invalide. Vérifiez l’heure de votre téléphone puis réessayez." };311  refresh();312  return { ok: "Vérification en deux étapes activée.", codes };313}314export async function totpDisableAction(_p: FormState, d: FormData): Promise<FormState> {315  const { user } = await requireAdmin();316  if (!disableTotp(user.id, String(d.get("password") ?? ""))) return { error: "Mot de passe incorrect." };317  refresh();318  return { ok: "Vérification en deux étapes désactivée." };319}320export async function revokeSessionsAction(): Promise<FormState> {321  const { user, token } = await requireAdmin();322  getDb().prepare("DELETE FROM sessions WHERE user_id = ? AND token_hash != ?").run(user.id, sha256(token));323  audit("security.sessions_revoked", { userId: user.id });324  refresh();325  return { ok: "Les autres sessions ont été fermées." };326}327
Files main
Menu

Theme