SPB Git

Repository Public

templates.ts 17.0 KB 257 lines typescript

1// Studio de modèles de courriel : bibliothèque personnelle, versions, génération et retouche par IA, aperçu rendu.2// Routes de session (webmail et apps). L'accès par clé d'API (/api/v1/templates, envoi par modèle) s'appuie sur les fonctions exportées ici.3import type { FastifyInstance } from "fastify"4import { z } from "zod"5import { sql } from "./db.js"6import { requireUser } from "./session.js"7import { MAX_TEMPLATE_BYTES, sanitizeTemplateHtml } from "./template-sanitize.js"8import { AI_MODEL, VARIABLE_NAME, aiConfigured, generateTemplate, renderTemplate, variablesIn, type GeneratedTemplate } from "./templates-ai.js"9import { audit, bad, parse, rateLimit, zUuid } from "./util.js"1011const CATEGORIES = ["transactional", "notification", "newsletter", "announcement", "personal", "invitation", "receipt", "security", "other"] as const12const zVariable = z.object({ name: z.string().regex(VARIABLE_NAME), description: z.string().max(300).default(""), example: z.string().max(2000).default(""), required: z.boolean().default(false) })13const zBrand = z.object({14  name: z.string().max(80).optional(), accent: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(), logo_url: z.string().url().startsWith("https://").max(500).optional(),15  tone: z.string().max(200).optional(), footer: z.string().max(400).optional(), website: z.string().url().max(300).optional(),16}).default({})17const zContent = z.object({18  name: z.string().trim().min(1).max(100),19  category: z.enum(CATEGORIES).default("other"),20  subject: z.string().max(500).refine((s) => !/[\r\n]/.test(s), "no line breaks").default(""),21  preheader: z.string().max(300).default(""),22  html: z.string().min(1).max(MAX_TEMPLATE_BYTES),23  text: z.string().max(200_000).default(""),24  variables: z.array(zVariable).max(60).default([]),25  brand: zBrand,26})2728// Mise à jour partielle : aucun défaut (un champ absent n'est pas un champ vidé).29const zPatch = z.object({30  name: z.string().trim().min(1).max(100), category: z.enum(CATEGORIES),31  subject: z.string().max(500).refine((s) => !/[\r\n]/.test(s), "no line breaks"), preheader: z.string().max(300),32  html: z.string().min(1).max(MAX_TEMPLATE_BYTES), text: z.string().max(200_000), variables: z.array(zVariable).max(60),33  brand: zBrand.unwrap(), note: z.string().max(200),34}).partial()3536type Row = Record<string, any>37const present = (r: Row, full = true) => ({38  id: r.id, name: r.name, category: r.category, subject: r.subject, preheader: r.preheader, variables: r.variables, brand: r.brand, source: r.source,39  ai_model: r.ai_model, design_notes: r.design_notes, version: r.version, created_at: r.created_at, updated_at: r.updated_at, size_bytes: r.size_bytes ?? Buffer.byteLength(r.html ?? ""),40  ...(full ? { html: r.html, text: r.text_body, ai_brief: r.ai_brief } : {}),41})4243/** Les variables déclarées sont alignées sur celles réellement utilisées : aucune variable fantôme, aucune non déclarée. */44function reconcileVariables(declared: z.infer<typeof zVariable>[], ...texts: string[]) {45  const used = variablesIn(...texts)46  const byName = new Map(declared.map((v) => [v.name, v]))47  return used.map((name) => byName.get(name) ?? { name, description: "", example: "", required: false })48}4950export async function getTemplate(userId: string, id: string): Promise<Row> {51  const [r] = await sql`select * from templates where id = ${id} and user_id = ${userId} and archived_at is null`52  if (!r) throw bad("not_found", 404)53  return r54}5556export const zTemplateContent = zContent57export async function saveNew(userId: string, c: z.infer<typeof zContent>, extra: { source: "manual" | "ai"; ai_model?: string; ai_brief?: string; design_notes?: string }) {58  const html = sanitizeTemplateHtml(c.html)59  const variables = reconcileVariables(c.variables, c.subject, c.preheader, html, c.text)60  const [r] = await sql`insert into templates (user_id, name, category, subject, preheader, html, text_body, variables, brand, source, ai_model, ai_brief, design_notes)61    values (${userId}, ${c.name}, ${c.category}, ${c.subject}, ${c.preheader}, ${html}, ${c.text}, ${sql.json(variables as never)}, ${sql.json(c.brand as never)},62            ${extra.source}, ${extra.ai_model ?? null}, ${extra.ai_brief ?? null}, ${extra.design_notes ?? ""}) returning *`63  return r64}6566async function saveRevision(userId: string, id: string, c: Partial<z.infer<typeof zContent>>, note: string, extra: { design_notes?: string } = {}) {67  return sql.begin(async (tx) => {68    const [cur] = await tx`select * from templates where id = ${id} and user_id = ${userId} and archived_at is null for update`69    if (!cur) throw bad("not_found", 404)70    const html = c.html !== undefined ? sanitizeTemplateHtml(c.html) : cur.html71    const subject = c.subject ?? cur.subject, preheader = c.preheader ?? cur.preheader, text = c.text ?? cur.text_body72    const variables = reconcileVariables((c.variables ?? cur.variables) as z.infer<typeof zVariable>[], subject, preheader, html, text)73    const contentChanged = html !== cur.html || subject !== cur.subject || preheader !== cur.preheader || text !== cur.text_body || JSON.stringify(variables) !== JSON.stringify(cur.variables)74    if (contentChanged)75      await tx`insert into template_versions (template_id, version, subject, preheader, html, text_body, variables, note)76               values (${id}, ${cur.version}, ${cur.subject}, ${cur.preheader}, ${cur.html}, ${cur.text_body}, ${tx.json(cur.variables)}, ${note})`77    const [r] = await tx`update templates set name = ${c.name ?? cur.name}, category = ${c.category ?? cur.category}, subject = ${subject}, preheader = ${preheader},78        html = ${html}, text_body = ${text}, variables = ${tx.json(variables as never)}, brand = ${tx.json((c.brand ?? cur.brand) as never)},79        design_notes = ${extra.design_notes ?? cur.design_notes}, version = ${contentChanged ? cur.version + 1 : cur.version}, updated_at = now()80      where id = ${id} returning *`81    // on garde les 50 dernières versions82    await tx`delete from template_versions where template_id = ${id} and version <= ${r.version - 50}`83    return r84  })85}8687/** Rendu d'un modèle avec des valeurs ; les variables absentes prennent leur exemple si `examples` est vrai. */88export function renderRow(r: Row, values: Record<string, string>, examples: boolean) {89  const vars = r.variables as z.infer<typeof zVariable>[]90  const merged: Record<string, string> = {}91  if (examples) for (const v of vars) merged[v.name] = v.example92  for (const [k, v] of Object.entries(values)) if (VARIABLE_NAME.test(k)) merged[k] = String(v).slice(0, 20_000)93  const missing = vars.filter((v) => v.required && !(values[v.name] ?? "").trim() && !(examples && v.example)).map((v) => v.name)94  const out = renderTemplate({ subject: r.subject, html: r.html, text: r.text_body }, merged)95  const preheader = renderTemplate({ subject: r.preheader, html: "", text: "" }, merged).subject96  return { ...out, preheader, missing }97}9899export function templateRoutes(app: FastifyInstance) {100  app.get("/api/templates", async (req) => {101    const a = await requireUser(req)102    const rows = await sql`select id, name, category, subject, preheader, variables, brand, source, ai_model, design_notes, version, created_at, updated_at, octet_length(html) as size_bytes103      from templates where user_id = ${a.userId} and archived_at is null order by updated_at desc limit 500`104    return { templates: rows.map((r) => present(r, false)), ai: { configured: aiConfigured(), model: AI_MODEL }, categories: CATEGORIES }105  })106107  app.post("/api/templates", { bodyLimit: 1024 * 1024 }, async (req) => {108    const a = await requireUser(req)109    const r = await saveNew(a.userId, parse(zContent, req.body), { source: "manual" })110    await audit(req, a.userId, "template.create", r.id)111    return present(r)112  })113114  app.get("/api/templates/:id", async (req) => {115    const a = await requireUser(req)116    return present(await getTemplate(a.userId, parse(z.object({ id: zUuid }), req.params).id))117  })118119  app.put("/api/templates/:id", { bodyLimit: 1024 * 1024 }, async (req) => {120    const a = await requireUser(req)121    const { id } = parse(z.object({ id: zUuid }), req.params)122    const body = parse(zPatch, req.body)123    return present(await saveRevision(a.userId, id, body, body.note ?? "modification manuelle"))124  })125126  app.delete("/api/templates/:id", async (req) => {127    const a = await requireUser(req)128    const { id } = parse(z.object({ id: zUuid }), req.params)129    const r = await sql`update templates set archived_at = now() where id = ${id} and user_id = ${a.userId} and archived_at is null returning 1`130    if (!r.length) throw bad("not_found", 404)131    await audit(req, a.userId, "template.archive", id)132    return { ok: true }133  })134135  // Annule un archivage (corbeille des modèles : 30 jours).136  app.post("/api/templates/:id/unarchive", async (req) => {137    const a = await requireUser(req)138    const { id } = parse(z.object({ id: zUuid }), req.params)139    const [r] = await sql`update templates set archived_at = null where id = ${id} and user_id = ${a.userId} and archived_at > now() - interval '30 days' returning *`140    if (!r) throw bad("not_found", 404)141    await audit(req, a.userId, "template.unarchive", id)142    return present(r)143  })144145  app.post("/api/templates/:id/duplicate", async (req) => {146    const a = await requireUser(req)147    const cur = await getTemplate(a.userId, parse(z.object({ id: zUuid }), req.params).id)148    const r = await saveNew(a.userId, { name: `${cur.name} (copie)`.slice(0, 100), category: cur.category, subject: cur.subject, preheader: cur.preheader, html: cur.html, text: cur.text_body, variables: cur.variables, brand: cur.brand },149      { source: cur.source, ai_model: cur.ai_model ?? undefined, design_notes: cur.design_notes })150    return present(r)151  })152153  app.get("/api/templates/:id/versions", async (req) => {154    const a = await requireUser(req)155    const { id } = parse(z.object({ id: zUuid }), req.params)156    await getTemplate(a.userId, id)157    return sql`select version, subject, note, created_at, octet_length(html) as size_bytes from template_versions where template_id = ${id} order by version desc`158  })159160  app.get("/api/templates/:id/versions/:version", async (req) => {161    const a = await requireUser(req)162    const p = parse(z.object({ id: zUuid, version: z.coerce.number().int().positive() }), req.params)163    await getTemplate(a.userId, p.id)164    const [v] = await sql`select version, subject, preheader, html, text_body as text, variables, note, created_at from template_versions where template_id = ${p.id} and version = ${p.version}`165    if (!v) throw bad("not_found", 404)166    return v167  })168169  app.post("/api/templates/:id/versions/:version/restore", async (req) => {170    const a = await requireUser(req)171    const p = parse(z.object({ id: zUuid, version: z.coerce.number().int().positive() }), req.params)172    const [v] = await sql`select v.* from template_versions v join templates t on t.id = v.template_id where v.template_id = ${p.id} and v.version = ${p.version} and t.user_id = ${a.userId}`173    if (!v) throw bad("not_found", 404)174    return present(await saveRevision(a.userId, p.id, { subject: v.subject, preheader: v.preheader, html: v.html, text: v.text_body, variables: v.variables }, `restauration de la version ${p.version}`))175  })176177  // Aperçu : rendu avec les valeurs fournies (les exemples comblent le reste). Le HTML rendu est destiné à un cadre isolé sans scripts.178  app.post("/api/templates/:id/render", async (req) => {179    const a = await requireUser(req)180    const { id } = parse(z.object({ id: zUuid }), req.params)181    const b = parse(z.object({ values: z.record(z.string(), z.string()).default({}), use_examples: z.boolean().default(true) }), req.body ?? {})182    return renderRow(await getTemplate(a.userId, id), b.values, b.use_examples)183  })184185  // Aperçu d'un brouillon non enregistré (éditeur) : assaini et rendu sans rien stocker.186  app.post("/api/templates/preview", { bodyLimit: 1024 * 1024 }, async (req) => {187    await requireUser(req)188    const b = parse(z.object({ subject: z.string().max(500).default(""), preheader: z.string().max(300).default(""), html: z.string().max(MAX_TEMPLATE_BYTES), text: z.string().max(200_000).default(""),189      variables: z.array(zVariable).max(60).default([]), values: z.record(z.string(), z.string()).default({}) }), req.body)190    const html = sanitizeTemplateHtml(b.html)191    const variables = reconcileVariables(b.variables, b.subject, b.preheader, html, b.text)192    return { ...renderRow({ subject: b.subject, preheader: b.preheader, html, text_body: b.text, variables }, b.values, true), variables, sanitized_html: html }193  })194195  // Génération ou retouche par IA, en flux (text/event-stream) : `progress` pendant l'écriture, puis `done` (modèle enregistré) ou `error`.196  // Seuls le brief, la marque et — pour une retouche — le modèle de base partent vers l'API d'Anthropic ; jamais de courrier.197  app.post("/api/templates/generate", { bodyLimit: 64 * 1024 }, async (req, reply) => {198    const a = await requireUser(req)199    const b = parse(z.object({200      brief: z.string().trim().min(8).max(6000), language: z.enum(["fr", "en"]).default("fr"), category: z.enum(CATEGORIES).optional(), brand: zBrand,201      base_template_id: zUuid.optional(),202    }), req.body)203    if (!aiConfigured()) throw bad("ai_not_configured", 503, "No Anthropic credential is configured on this server")204    rateLimit(`ai:${a.userId}`, 30, 3600_000)205    const base = b.base_template_id ? await getTemplate(a.userId, b.base_template_id) : null206207    const ctrl = new AbortController()208    req.raw.on("close", () => { if (!reply.raw.writableEnded) ctrl.abort() })209    reply.raw.writeHead(200, { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-store", "x-accel-buffering": "no", connection: "keep-alive" })210    reply.hijack()211    const send = (event: string, data: unknown) => { if (!reply.raw.writableEnded) reply.raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`) }212    send("start", { model: AI_MODEL, revising: !!base })213    const beat = setInterval(() => { if (!reply.raw.writableEnded) reply.raw.write(": ping\n\n") }, 15_000)214    const t0 = Date.now()215    let last = 0216    try {217      const { template, usage } = await generateTemplate(218        { brief: b.brief, language: b.language, category: b.category, brand: b.brand,219          base: base ? { subject: base.subject, html: base.html, variables: (base.variables as { name: string }[]).map((v) => v.name) } : undefined },220        (chars) => { if (chars - last >= 400) { last = chars; send("progress", { chars }) } },221        ctrl.signal,222      )223      const content = fromGenerated(template, b.brand)224      const row = base225        ? await saveRevision(a.userId, base.id, { subject: content.subject, preheader: content.preheader, html: content.html, text: content.text, variables: content.variables }, `retouche par IA : ${b.brief.slice(0, 140)}`, { design_notes: template.design_notes })226        : await saveNew(a.userId, content, { source: "ai", ai_model: usage.model, ai_brief: b.brief, design_notes: template.design_notes })227      await sql`insert into ai_generations (user_id, template_id, kind, model, input_tokens, output_tokens, duration_ms, status)228                values (${a.userId}, ${row.id}, ${base ? "revise" : "create"}, ${usage.model}, ${usage.input_tokens}, ${usage.output_tokens}, ${Date.now() - t0}, 'ok')`229      send("done", { template: present(row), usage: { input_tokens: usage.input_tokens, output_tokens: usage.output_tokens, model: usage.model, seconds: Math.round((Date.now() - t0) / 1000) } })230    } catch (e) {231      const err = e as { code?: string; status?: number; message?: string; name?: string }232      const code = ctrl.signal.aborted ? "cancelled" : (err.code ?? "ai_error")233      await sql`insert into ai_generations (user_id, kind, model, duration_ms, status) values (${a.userId}, ${base ? "revise" : "create"}, ${AI_MODEL}, ${Date.now() - t0}, ${code})`.catch(() => {})234      if (!ctrl.signal.aborted) req.log.warn({ code }, "template generation failed")235      send("error", { code, message: code === "ai_error" ? "Generation failed" : (err.message ?? code) })236    } finally {237      clearInterval(beat)238      reply.raw.end()239    }240  })241242  app.get("/api/templates/ai/usage", async (req) => {243    const a = await requireUser(req)244    const [t] = await sql`select count(*)::int as generations, coalesce(sum(input_tokens),0)::int as input_tokens, coalesce(sum(output_tokens),0)::int as output_tokens245      from ai_generations where user_id = ${a.userId} and status = 'ok' and at > now() - interval '30 days'`246    return { last_30_days: t, model: AI_MODEL, configured: aiConfigured() }247  })248}249250function fromGenerated(t: GeneratedTemplate, brand: z.infer<typeof zBrand>): z.infer<typeof zContent> {251  return {252    name: t.name.trim().slice(0, 100) || "Modèle", category: t.category, subject: t.subject.replace(/[\r\n]+/g, " ").slice(0, 500), preheader: t.preheader.slice(0, 300),253    html: t.html.slice(0, MAX_TEMPLATE_BYTES), text: t.text.slice(0, 200_000), brand,254    variables: t.variables.filter((v) => VARIABLE_NAME.test(v.name)).slice(0, 60).map((v) => ({ name: v.name, description: v.description.slice(0, 300), example: v.example.slice(0, 2000), required: v.required })),255  }256}257
Files main
Menu

Theme