SPB Git

Repository Public

templates.ts 13.2 KB 322 lines typescript

1// Studio de modèles : appels de l'API de session (docs/templates-api.md), bibliothèque en mémoire, génération par IA en flux,2// envoi d'un modèle par /api/v1.3import { t } from "../i18n"4import { HttpError, NetworkError } from "../jmap/errors"5import { api, apiGet, apiPost, apiPut, request } from "../jmap/http"6import { v1, type Outbound } from "../mail/v1"7import type { SendPayload } from "../templates/send"8import { parseGenerationEvent, readSseStream, type GenerationErrorCode } from "../templates/sse"9import type { TemplateVariable } from "../templates/variables"10import { S, normalizeBrand, toast, type BrandKit } from "./app"11import { updatePrefs } from "./session"12import { createStore } from "./store"1314export type { BrandKit } from "./app"15export type { TemplateVariable } from "../templates/variables"1617export const CATEGORIES = ["transactional", "notification", "newsletter", "announcement", "personal", "invitation", "receipt", "security", "other"] as const18export type Category = (typeof CATEGORIES)[number]1920export interface TemplateSummary {21  id: string22  name: string23  category: Category24  subject: string25  preheader: string26  variables: TemplateVariable[]27  brand: BrandKit28  source: "manual" | "ai"29  ai_model: string | null30  design_notes: string31  version: number32  created_at: string33  updated_at: string34  size_bytes: number35}36export interface Template extends TemplateSummary {37  html: string38  text: string39  ai_brief: string | null40}41export interface Rendered {42  subject: string43  preheader: string44  html: string45  text: string46  missing: string[]47}48export interface PreviewResult extends Rendered {49  variables: TemplateVariable[]50  sanitized_html: string51}52export interface VersionSummary {53  version: number54  subject: string55  note: string56  created_at: string57  size_bytes: number58}59export interface VersionFull {60  version: number61  subject: string62  preheader: string63  html: string64  text: string65  variables: TemplateVariable[]66  note: string67  created_at: string68}69export interface AiUsage {70  last_30_days: { generations: number; input_tokens: number; output_tokens: number }71  model: string72  configured: boolean73}7475// ---------------------------------------------------------------- génération76export interface Generation {77  /** modèle retouché, ou null pour une création */78  baseId: string | null79  phase: "running" | "done" | "error" | "cancelled"80  startedAt: number81  /** le serveur a ouvert le flux (événement `start`) */82  started: boolean83  model: string84  chars: number85  error: GenerationErrorCode | null86  /** détail technique court donné par le serveur (jamais affiché seul) */87  errorDetail: string88  /** demande rejouable après un échec */89  request: GenerateRequest90  seconds: number | null91}92export interface GenerateRequest {93  brief: string94  language: "fr" | "en"95  category?: Category96  brand?: BrandKit97  base_template_id?: string98}99100export interface TemplatesState {101  status: "idle" | "loading" | "ready" | "error"102  templates: TemplateSummary[]103  ai: { configured: boolean; model: string }104  usage: AiUsage | null105  generation: Generation | null106}107export const T = createStore<TemplatesState>({ status: "idle", templates: [], ai: { configured: true, model: "" }, usage: null, generation: null })108109// ---------------------------------------------------------------- bibliothèque110export async function loadTemplates(): Promise<void> {111  if (T.get().status === "idle" || T.get().status === "error") T.set({ status: "loading" })112  try {113    const r = await apiGet<{ templates: TemplateSummary[]; ai: { configured: boolean; model: string } }>("/api/templates")114    T.set({ status: "ready", templates: r.templates.filter((x) => !archiving.has(x.id)), ai: r.ai })115  } catch {116    T.set((s) => ({ status: s.status === "ready" ? "ready" : "error" }))117  }118}119export async function loadUsage(): Promise<void> {120  try {121    T.set({ usage: await apiGet<AiUsage>("/api/templates/ai/usage") })122  } catch {123    /* pied de page facultatif */124  }125}126const summaryOf = (tpl: Template | TemplateSummary): TemplateSummary => {127  const { html: _h, text: _t, ai_brief: _b, ...rest } = tpl as Template128  return rest129}130/** Reporte un modèle créé ou modifié dans la liste en mémoire (en tête : la liste est triée par modification). */131export function upsertLocal(tpl: Template | TemplateSummary) {132  T.set((s) => ({ templates: [summaryOf(tpl), ...s.templates.filter((x) => x.id !== tpl.id)] }))133}134135export const getTemplate = (id: string, signal?: AbortSignal) => apiGet<Template>(`/api/templates/${id}`, signal)136export async function createTemplate(body: { name: string; html: string; category?: Category; subject?: string; preheader?: string; text?: string; variables?: TemplateVariable[]; brand?: BrandKit }): Promise<Template> {137  const tpl = await apiPost<Template>("/api/templates", body)138  upsertLocal(tpl)139  return tpl140}141export async function updateTemplate(id: string, patch: Partial<Pick<Template, "name" | "category" | "subject" | "preheader" | "html" | "text" | "variables">> & { note?: string }): Promise<Template> {142  const tpl = await apiPut<Template>(`/api/templates/${id}`, patch)143  upsertLocal(tpl)144  return tpl145}146export async function duplicateTemplate(id: string): Promise<Template> {147  const tpl = await apiPost<Template>(`/api/templates/${id}/duplicate`)148  upsertLocal(tpl)149  return tpl150}151export const renderTemplate = (id: string, values: Record<string, string> = {}, signal?: AbortSignal) => api<Rendered>(`/api/templates/${id}/render`, { method: "POST", json: { values, use_examples: true }, signal })152export const previewDraft = (draft: { html: string; subject: string; preheader: string; text: string; variables: TemplateVariable[]; values: Record<string, string> }, signal?: AbortSignal) =>153  api<PreviewResult>("/api/templates/preview", { method: "POST", json: draft, signal })154export const listVersions = (id: string) => apiGet<VersionSummary[]>(`/api/templates/${id}/versions`)155export const getVersion = (id: string, n: number) => apiGet<VersionFull>(`/api/templates/${id}/versions/${n}`)156export async function restoreVersion(id: string, n: number): Promise<Template> {157  const tpl = await apiPost<Template>(`/api/templates/${id}/versions/${n}/restore`)158  upsertLocal(tpl)159  return tpl160}161162// ---------------------------------------------------------------- suppression annulable163// La suppression archive le modèle tout de suite (DELETE) ; « Annuler » le désarchive (POST …/unarchive, possible 30 jours côté serveur).164/** Archivages en vol : une relecture de la liste arrivée avant la réponse du serveur ne fait pas réapparaître la carte. */165const archiving = new Set<string>()166167export async function deleteTemplateWithUndo(tpl: Pick<TemplateSummary, "id" | "name">): Promise<void> {168  if (archiving.has(tpl.id)) return169  archiving.add(tpl.id)170  T.set((s) => ({ templates: s.templates.filter((x) => x.id !== tpl.id) }))171  try {172    await api(`/api/templates/${tpl.id}`, { method: "DELETE" })173  } catch (e) {174    archiving.delete(tpl.id)175    // 404 : déjà archivé ou supprimé ailleurs — rien à annoncer176    if (!(e instanceof HttpError && e.status === 404)) {177      toast({ kind: "error", text: t("tpl.deleteFailed") })178      void loadTemplates()179    }180    return181  }182  archiving.delete(tpl.id)183  toast({184    kind: "info",185    text: t("tpl.deleted", { name: tpl.name }),186    actionLabel: t("tpl.undo"),187    action: () => void unarchiveTemplate(tpl.id),188  })189}190export async function unarchiveTemplate(id: string): Promise<Template | null> {191  try {192    const tpl = await apiPost<Template>(`/api/templates/${id}/unarchive`)193    upsertLocal(tpl)194    return tpl195  } catch {196    toast({ kind: "error", text: t("tpl.undoFailed") })197    return null198  }199}200201// ---------------------------------------------------------------- envoi par modèle (POST /api/v1/messages/send avec template_id)202/** L'API envoie le modèle ENREGISTRÉ. `idempotencyKey` : la même clé pour une même tentative (double clic, nouvel essai après coupure). */203export const sendTemplate = (payload: SendPayload, idempotencyKey: string, signal?: AbortSignal) =>204  v1<Outbound>("/messages/send", { method: "POST", json: payload, headers: { "idempotency-key": idempotencyKey }, signal })205export const cancelScheduledSend = (id: string) => v1<Outbound>(`/messages/scheduled/${encodeURIComponent(id)}`, { method: "DELETE" })206207// ---------------------------------------------------------------- marque208export function saveBrand(brand: BrandKit) {209  updatePrefs({ templateBrand: normalizeBrand(brand) })210}211export const currentBrand = (): BrandKit => S.get().prefs.templateBrand212213// ---------------------------------------------------------------- génération en flux214let controller: AbortController | null = null215216function httpErrorCode(e: unknown): GenerationErrorCode {217  if (e instanceof NetworkError) return "offline"218  if (e instanceof HttpError) {219    if (e.code === "ai_not_configured") return "ai_not_configured"220    if (e.status === 429) return "rate_limited"221    if (e.status === 401) return "unauthorized"222    if (e.status === 404) return "not_found"223    if (e.status === 400 || e.status === 413) return "invalid_request"224    if (e.status === 502 || e.status === 503 || e.status === 504) return "ai_unreachable"225  }226  return "ai_error"227}228229/**230 * Lance une génération (ou une retouche si `base_template_id` est donné). Résout avec le modèle créé ou mis à jour,231 * ou `null` si la génération a échoué ou a été annulée — l'état est alors dans `T.generation`.232 */233export async function startGeneration(req: GenerateRequest): Promise<Template | null> {234  if (T.get().generation?.phase === "running") return null235  const ctrl = new AbortController()236  controller = ctrl237  const base: Generation = { baseId: req.base_template_id ?? null, phase: "running", startedAt: Date.now(), started: false, model: "", chars: 0, error: null, errorDetail: "", request: req, seconds: null }238  T.set({ generation: base })239  const patch = (p: Partial<Generation>) => T.set((s) => (s.generation && s.generation.startedAt === base.startedAt ? { generation: { ...s.generation, ...p } } : {}))240  const fail = (code: GenerationErrorCode, detail = "") => patch({ phase: code === "cancelled" ? "cancelled" : "error", error: code, errorDetail: detail })241  let result: Template | null = null242  let settled = false243  try {244    const brand = req.brand && Object.keys(req.brand).length ? req.brand : undefined245    const r = await request("/api/templates/generate", { method: "POST", json: { ...req, brand }, headers: { accept: "text/event-stream" }, signal: ctrl.signal })246    if (!r.body || !(r.headers.get("content-type") ?? "").includes("text/event-stream")) {247      fail("ai_error")248      return null249    }250    await readSseStream(r.body, (raw) => {251      const e = parseGenerationEvent<Template>(raw)252      if (!e || settled) return253      if (e.type === "start") patch({ started: true, model: e.model })254      else if (e.type === "progress") patch({ started: true, chars: e.chars })255      else if (e.type === "done") {256        settled = true257        result = e.template258        patch({ phase: "done", seconds: e.usage.seconds, model: e.usage.model || base.model })259      } else {260        settled = true261        fail(e.code, e.message)262      }263    })264    // flux fermé sans `done` ni `error` : connexion coupée (mandataire, veille de l'appareil…)265    if (!settled) fail(ctrl.signal.aborted ? "cancelled" : "interrupted")266  } catch (e) {267    if (ctrl.signal.aborted || (e instanceof DOMException && e.name === "AbortError")) fail("cancelled")268    else if (!settled) fail(e instanceof TypeError ? "interrupted" : httpErrorCode(e), e instanceof HttpError ? e.message : "")269  } finally {270    if (controller === ctrl) controller = null271  }272  const tpl = result as Template | null273  if (tpl) {274    upsertLocal(tpl)275    void loadUsage()276  }277  return tpl278}279export function cancelGeneration() {280  controller?.abort()281}282export function clearGeneration() {283  if (T.get().generation?.phase !== "running") T.set({ generation: null })284}285export const isGenerating = () => T.get().generation?.phase === "running"286287/** Message destiné à la personne pour chaque code d'erreur du générateur. */288export function generationErrorText(code: GenerationErrorCode): string {289  switch (code) {290    case "ai_not_configured":291      return t("tpl.err.ai_not_configured")292    case "ai_refused":293      return t("tpl.err.ai_refused")294    case "ai_rate_limited":295      return t("tpl.err.ai_rate_limited")296    case "ai_output_truncated":297      return t("tpl.err.ai_output_truncated")298    case "ai_invalid_output":299      return t("tpl.err.ai_invalid_output")300    case "ai_unreachable":301      return t("tpl.err.ai_unreachable")302    case "cancelled":303      return t("tpl.err.cancelled")304    case "rate_limited":305      return t("tpl.err.rate_limited")306    case "invalid_request":307      return t("tpl.err.invalid_request")308    case "not_found":309      return t("tpl.err.not_found")310    case "offline":311      return t("tpl.err.offline")312    case "unauthorized":313      return t("tpl.err.unauthorized")314    case "interrupted":315      return t("tpl.err.interrupted")316    default:317      return t("tpl.err.ai_error")318  }319}320/** Réessayer a-t-il un sens tel quel ? (sans clé d'IA ou sans session, non). */321export const canRetry = (code: GenerationErrorCode | null) => code !== "ai_not_configured" && code !== "unauthorized" && code !== "not_found"322
Files main
Menu

Theme