Repository Public
1// SP Mail Next — règles après livraison (/api/next/rules) : formes du serveur, modèle de formulaire ⇄ règle, validation, résumé en mots, réordonnancement.2import { getLang, t } from "../i18n"3import { nx } from "./api"4import type { MessageSummary } from "./types"56// ---------------------------------------------------------------- formes du serveur (server/src/next/rules.ts fait foi)7export const FIELDS = ["from", "to", "subject", "list", "has_attachment", "is_newsletter", "ai_category", "size"] as const8export type Field = (typeof FIELDS)[number]9export type Op = "contains" | "equals" | "matches_domain" | "is" | "gt"10export const FIELD_OPS: Record<Field, Op[]> = {11 from: ["contains", "equals", "matches_domain"],12 to: ["contains", "equals", "matches_domain"],13 subject: ["contains", "equals"],14 list: ["contains", "equals"],15 has_attachment: ["is"],16 is_newsletter: ["is"],17 ai_category: ["is"],18 size: ["gt"],19}20export const CATEGORIES = ["personal", "work", "newsletter", "notification", "transaction", "social", "other"] as const21export type Category = (typeof CATEGORIES)[number]22export const TONES = ["concise", "professional", "detailed"] as const23export type Tone = (typeof TONES)[number]24export const ACTION_TYPES = ["label", "star", "mark_read", "pin", "snooze", "remind", "event", "notify_app", "draft_reply", "extract"] as const25export type ActionType = (typeof ACTION_TYPES)[number]26export const EXTRACT_TYPES = ["string", "number", "boolean", "date"] as const27export type ExtractType = (typeof EXTRACT_TYPES)[number]2829export interface Condition {30 field: Field31 op: Op32 value: string | number | boolean33}34export interface ExtractField {35 name: string36 type: ExtractType37 description: string38}39export type Action =40 | { type: "label"; label_id: string }41 | { type: "star" }42 | { type: "mark_read" }43 | { type: "pin" }44 | { type: "snooze"; until_rule: string }45 | { type: "remind"; after_hours: number }46 | { type: "event"; name: string }47 | { type: "notify_app"; app: string }48 | { type: "draft_reply"; snippet_id?: string; ai_tone?: Tone }49 | { type: "extract"; schema: { fields: ExtractField[] } }50export interface RuleInput {51 name: string52 enabled: boolean53 mailbox_ids: string[] | null54 match: "all" | "any"55 conditions: Condition[]56 actions: Action[]57 stop: boolean58}59export interface Rule extends RuleInput {60 id: string61 position: number62 created_at: string63 updated_at: string64}65export interface RuleRunAction {66 type: ActionType67 status: "ok" | "skipped" | "error"68 detail?: string69 [k: string]: unknown70}71export interface RuleRun {72 id: string | number73 mailbox_id: string74 email_id: string75 status: "running" | "ok" | "partial" | "error" | "interrupted"76 actions: RuleRunAction[]77 error: string | null78 at: string79 finished_at: string | null80}81export interface RuleTestResult {82 matched: boolean83 dry_run: true84 conditions: (Condition & { result: boolean })[]85 actions: { type: ActionType; would: string }[]86 facts: { has_attachment: boolean; is_newsletter: boolean; size: number; list: string; ai_category: string | null }87}88export interface LabelRef {89 id: string90 name: string91 color: string92 keyword: string93}94export interface SnippetRef {95 id: string96 name: string97}9899/** Conditions et actions qui demandent la couche d'intelligence (sans elle : condition jamais vraie, action ignorée). */100export const conditionNeedsAi = (field: Field): boolean => field === "ai_category"101export const actionNeedsAi = (a: { type: ActionType; source?: "snippet" | "ai" }): boolean => a.type === "extract" || (a.type === "draft_reply" && a.source === "ai")102export const ruleNeedsAi = (r: Pick<RuleInput, "conditions" | "actions">): boolean =>103 r.conditions.some((c) => conditionNeedsAi(c.field)) || r.actions.some((a) => a.type === "extract" || (a.type === "draft_reply" && !!a.ai_tone))104105// ---------------------------------------------------------------- modèle de formulaire106export type SizeUnit = "kb" | "mb"107export interface CondForm {108 key: string109 field: Field110 op: Op111 /** from, to, subject, list : texte ; ai_category : catégorie */112 text: string113 /** has_attachment, is_newsletter */114 flag: boolean115 /** size : quantité dans `unit` */116 amount: string117 unit: SizeUnit118}119export const UNTIL_PRESETS = ["later_today", "tomorrow", "weekend", "next_week"] as const120export type UntilKind = (typeof UNTIL_PRESETS)[number] | "hours" | "days"121export interface ActionForm {122 key: string123 type: ActionType124 labelId: string125 untilKind: UntilKind126 untilN: string127 remindN: string128 remindUnit: "hours" | "days"129 /** event : nom ; notify_app : application */130 name: string131 source: "snippet" | "ai"132 snippetId: string133 tone: Tone134 fields: ExtractField[]135}136export interface RuleForm {137 name: string138 enabled: boolean139 /** vide = toutes les boîtes */140 mailboxIds: string[]141 match: "all" | "any"142 conditions: CondForm[]143 actions: ActionForm[]144 stop: boolean145}146147let keySeq = 0148const nextKey = () => `k${++keySeq}`149export const newCondition = (field: Field = "from"): CondForm => ({ key: nextKey(), field, op: FIELD_OPS[field][0], text: field === "ai_category" ? "work" : "", flag: true, amount: "", unit: "mb" })150export const newAction = (type: ActionType = "label"): ActionForm => ({151 key: nextKey(), type, labelId: "", untilKind: "tomorrow", untilN: "3", remindN: "2", remindUnit: "days", name: "", source: "snippet", snippetId: "", tone: "concise",152 fields: [{ name: "", type: "string", description: "" }],153})154export const emptyRuleForm = (): RuleForm => ({ name: "", enabled: true, mailboxIds: [], match: "all", conditions: [newCondition()], actions: [newAction("label")], stop: false })155156/** Changer de champ remet un opérateur valide pour lui (le serveur refuse les autres combinaisons). */157export function setConditionField(c: CondForm, field: Field): CondForm {158 const op = FIELD_OPS[field].includes(c.op) ? c.op : FIELD_OPS[field][0]159 return { ...c, field, op, text: field === "ai_category" ? ((CATEGORIES as readonly string[]).includes(c.text) ? c.text : "work") : c.field === "ai_category" ? "" : c.text }160}161162const MB = 1024 * 1024163function conditionToForm(c: Condition): CondForm {164 const base = newCondition(c.field)165 // « equals » est accepté par le serveur pour ai_category ; l'interface n'écrit que « is »166 const op = FIELD_OPS[c.field].includes(c.op) ? c.op : FIELD_OPS[c.field][0]167 if (c.field === "size") {168 const n = Number(c.value) || 0169 // en Mo quand la valeur s'y écrit avec deux décimales au plus (2,5 Mo), sinon en Ko170 const mb = n >= MB && Number.isInteger((n * 100) / MB)171 return { ...base, op, amount: String(mb ? n / MB : Math.round((n / 1024) * 100) / 100), unit: mb ? "mb" : "kb" }172 }173 if (c.field === "has_attachment" || c.field === "is_newsletter") return { ...base, op, flag: c.value === true }174 return { ...base, op, text: String(c.value) }175}176function actionToForm(a: Action): ActionForm {177 const f = newAction(a.type)178 switch (a.type) {179 case "label":180 return { ...f, labelId: a.label_id }181 case "snooze": {182 const m = /^(\d+)([hd])$/.exec(a.until_rule)183 if (m) return { ...f, untilKind: m[2] === "h" ? "hours" : "days", untilN: m[1] }184 return { ...f, untilKind: (UNTIL_PRESETS as readonly string[]).includes(a.until_rule) ? (a.until_rule as UntilKind) : "tomorrow" }185 }186 case "remind": {187 const days = a.after_hours >= 24 && a.after_hours % 24 === 0188 return { ...f, remindN: String(days ? a.after_hours / 24 : a.after_hours), remindUnit: days ? "days" : "hours" }189 }190 case "event":191 return { ...f, name: a.name }192 case "notify_app":193 return { ...f, name: a.app }194 case "draft_reply":195 return a.ai_tone ? { ...f, source: "ai", tone: a.ai_tone } : { ...f, source: "snippet", snippetId: a.snippet_id ?? "" }196 case "extract":197 return { ...f, fields: a.schema.fields.map((x) => ({ name: x.name, type: x.type ?? "string", description: x.description ?? "" })) }198 default:199 return f200 }201}202export function ruleToForm(r: RuleInput): RuleForm {203 return { name: r.name, enabled: r.enabled, mailboxIds: r.mailbox_ids ?? [], match: r.match, conditions: r.conditions.map(conditionToForm), actions: r.actions.map(actionToForm), stop: r.stop }204}205206// ---------------------------------------------------------------- validation (mêmes bornes que les schémas zod du serveur)207const NAME_RE = /^[a-z0-9][a-z0-9_.-]{0,63}$/208const EXTRACT_NAME_RE = /^[a-z][a-z0-9_]{0,39}$/209const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i210export type FormIssueCode =211 | "name" | "noAction" | "tooManyConditions" | "tooManyActions" | "condText" | "condSize" | "condCategory" | "label" | "untilHours" | "untilDays" | "remind" | "eventName" | "appName"212 | "snippet" | "extractEmpty" | "extractName" | "extractDup" | "extractDesc" | "duplicateAction"213export interface FormIssue {214 code: FormIssueCode215 /** `c:<clé>` ou `a:<clé>` : la ligne fautive ; absent : la règle elle-même */216 at?: string217 /** rang (à partir de 1) de la ligne, pour le message */218 n?: number219}220const num = (s: string): number => (/^\d+([.,]\d+)?$/.test(s.trim()) ? Number(s.trim().replace(",", ".")) : NaN)221const int = (s: string): number => (/^\d+$/.test(s.trim()) ? Number(s.trim()) : NaN)222223function conditionOf(c: CondForm): Condition | FormIssueCode {224 switch (c.field) {225 case "has_attachment":226 case "is_newsletter":227 return { field: c.field, op: "is", value: c.flag }228 case "size": {229 const n = num(c.amount)230 if (!Number.isFinite(n) || n < 0) return "condSize"231 return { field: "size", op: "gt", value: Math.round(n * (c.unit === "mb" ? MB : 1024)) }232 }233 case "ai_category":234 return (CATEGORIES as readonly string[]).includes(c.text) ? { field: "ai_category", op: "is", value: c.text } : "condCategory"235 default: {236 const text = c.text.trim()237 if (!text || text.length > 300) return "condText"238 return { field: c.field, op: FIELD_OPS[c.field].includes(c.op) ? c.op : FIELD_OPS[c.field][0], value: text }239 }240 }241}242function actionOf(a: ActionForm): Action | FormIssueCode {243 switch (a.type) {244 case "star":245 case "mark_read":246 case "pin":247 return { type: a.type }248 case "label":249 return UUID_RE.test(a.labelId) ? { type: "label", label_id: a.labelId } : "label"250 case "snooze": {251 if (a.untilKind !== "hours" && a.untilKind !== "days") return { type: "snooze", until_rule: a.untilKind }252 const n = int(a.untilN)253 // bornes de UNTIL_RULE : 1–999 h, 1–99 j254 if (a.untilKind === "hours") return n >= 1 && n <= 999 ? { type: "snooze", until_rule: `${n}h` } : "untilHours"255 return n >= 1 && n <= 99 ? { type: "snooze", until_rule: `${n}d` } : "untilDays"256 }257 case "remind": {258 const n = num(a.remindN)259 const hours = a.remindUnit === "days" ? n * 24 : n260 return Number.isFinite(hours) && hours > 0 && hours <= 24 * 365 ? { type: "remind", after_hours: hours } : "remind"261 }262 case "event":263 return NAME_RE.test(a.name.trim()) ? { type: "event", name: a.name.trim() } : "eventName"264 case "notify_app":265 return NAME_RE.test(a.name.trim()) ? { type: "notify_app", app: a.name.trim() } : "appName"266 case "draft_reply":267 if (a.source === "ai") return { type: "draft_reply", ai_tone: a.tone }268 return UUID_RE.test(a.snippetId) ? { type: "draft_reply", snippet_id: a.snippetId } : "snippet"269 case "extract": {270 const fields = a.fields.map((f) => ({ name: f.name.trim(), type: f.type, description: f.description.trim() })).filter((f) => f.name || f.description)271 if (!fields.length || fields.length > 12) return "extractEmpty"272 if (fields.some((f) => !EXTRACT_NAME_RE.test(f.name))) return "extractName"273 if (new Set(fields.map((f) => f.name)).size !== fields.length) return "extractDup"274 if (fields.some((f) => f.description.length > 200)) return "extractDesc"275 return { type: "extract", schema: { fields } }276 }277 }278}279280/** Formulaire → corps de POST/PATCH. Rend la liste des défauts (jamais une règle à moitié valide). */281export function formToRule(f: RuleForm): { ok: true; rule: RuleInput } | { ok: false; issues: FormIssue[] } {282 const issues: FormIssue[] = []283 const name = f.name.trim()284 if (!name || name.length > 80) issues.push({ code: "name" })285 if (f.conditions.length > 20) issues.push({ code: "tooManyConditions" })286 if (!f.actions.length) issues.push({ code: "noAction" })287 if (f.actions.length > 10) issues.push({ code: "tooManyActions" })288 const conditions: Condition[] = []289 f.conditions.forEach((c, i) => {290 const r = conditionOf(c)291 if (typeof r === "string") issues.push({ code: r, at: `c:${c.key}`, n: i + 1 })292 else conditions.push(r)293 })294 const actions: Action[] = []295 const once = new Set<string>()296 f.actions.forEach((a, i) => {297 const r = actionOf(a)298 if (typeof r === "string") return void issues.push({ code: r, at: `a:${a.key}`, n: i + 1 })299 // deux fois la même action simple n'a pas de sens (le serveur l'accepterait, mais ce serait une erreur de saisie)300 const sig = r.type === "label" ? `label:${r.label_id}` : r.type === "event" ? `event:${r.name}` : r.type === "notify_app" ? `app:${r.app}` : r.type301 if (once.has(sig)) return void issues.push({ code: "duplicateAction", at: `a:${a.key}`, n: i + 1 })302 once.add(sig)303 actions.push(r)304 })305 if (issues.length) return { ok: false, issues }306 return { ok: true, rule: { name, enabled: f.enabled, mailbox_ids: f.mailboxIds.length ? [...f.mailboxIds] : null, match: f.match, conditions, actions, stop: f.stop } }307}308309export function issueText(i: FormIssue): string {310 const n = i.n ?? 0311 switch (i.code) {312 case "name": return t("nx.settings.rules.err.name")313 case "noAction": return t("nx.settings.rules.err.noAction")314 case "tooManyConditions": return t("nx.settings.rules.err.tooManyConditions")315 case "tooManyActions": return t("nx.settings.rules.err.tooManyActions")316 case "condText": return t("nx.settings.rules.err.condText", { n })317 case "condSize": return t("nx.settings.rules.err.condSize", { n })318 case "condCategory": return t("nx.settings.rules.err.condCategory", { n })319 case "label": return t("nx.settings.rules.err.label", { n })320 case "untilHours": return t("nx.settings.rules.err.untilHours", { n })321 case "untilDays": return t("nx.settings.rules.err.untilDays", { n })322 case "remind": return t("nx.settings.rules.err.remind", { n })323 case "eventName": return t("nx.settings.rules.err.eventName", { n })324 case "appName": return t("nx.settings.rules.err.appName", { n })325 case "snippet": return t("nx.settings.rules.err.snippet", { n })326 case "extractEmpty": return t("nx.settings.rules.err.extractEmpty", { n })327 case "extractName": return t("nx.settings.rules.err.extractName", { n })328 case "extractDup": return t("nx.settings.rules.err.extractDup", { n })329 case "extractDesc": return t("nx.settings.rules.err.extractDesc", { n })330 case "duplicateAction": return t("nx.settings.rules.err.duplicateAction", { n })331 }332}333334// ---------------------------------------------------------------- résumé en mots335export interface SummaryContext {336 labels: LabelRef[]337 snippets: SnippetRef[]338 /** adresse d'une boîte d'après son identifiant */339 mailbox: (id: string) => string340}341export const fieldLabel = (f: Field): string => t(`nx.settings.rules.field.${f}`)342export const opLabel = (o: Op): string => t(`nx.settings.rules.op.${o}`)343export const categoryLabel = (c: string): string => ((CATEGORIES as readonly string[]).includes(c) ? t(`nx.settings.rules.cat.${c as Category}`) : c)344export const toneLabel = (x: Tone): string => t(`nx.settings.rules.tone.${x}`)345export const actionLabel = (x: ActionType): string => t(`nx.settings.rules.act.${x}`)346347export function sizeText(bytes: number): string {348 const fmt = (v: number) => (Math.round(v * 10) / 10).toLocaleString(getLang() === "fr" ? "fr-CA" : "en-CA", { maximumFractionDigits: 1 })349 if (bytes >= MB) return t("nx.settings.rules.sizeMb", { n: fmt(bytes / MB) })350 return t("nx.settings.rules.sizeKb", { n: fmt(bytes / 1024) })351}352export function untilText(rule: string): string {353 const m = /^(\d+)([hd])$/.exec(rule)354 if (m) return m[2] === "h" ? t("nx.settings.rules.until.hoursN", { n: Number(m[1]) }) : t("nx.settings.rules.until.daysN", { n: Number(m[1]) })355 return (UNTIL_PRESETS as readonly string[]).includes(rule) ? t(`nx.settings.rules.until.${rule as (typeof UNTIL_PRESETS)[number]}`) : rule356}357export function hoursText(hours: number): string {358 return hours >= 24 && hours % 24 === 0 ? t("nx.settings.rules.until.daysN", { n: hours / 24 }) : t("nx.settings.rules.until.hoursN", { n: hours })359}360361/** Valeur citée selon la langue : « x » en français, “x” en anglais. */362const quoted = (v: string): string => (getLang() === "fr" ? `« ${v} »` : `“${v}”`)363export function conditionSummary(c: Condition): string {364 switch (c.field) {365 case "has_attachment": return c.value ? t("nx.settings.rules.sum.hasAttachment") : t("nx.settings.rules.sum.noAttachment")366 case "is_newsletter": return c.value ? t("nx.settings.rules.sum.newsletter") : t("nx.settings.rules.sum.notNewsletter")367 case "size": return t("nx.settings.rules.sum.size", { size: sizeText(Number(c.value)) })368 case "ai_category": return t("nx.settings.rules.sum.category", { category: categoryLabel(String(c.value)) })369 default: return `${fieldLabel(c.field)} ${opLabel(c.op)} ${quoted(String(c.value))}`370 }371}372export function actionSummary(a: Action, ctx: SummaryContext): string {373 switch (a.type) {374 case "label": return t("nx.settings.rules.sum.label", { name: ctx.labels.find((l) => l.id === a.label_id)?.name ?? t("nx.settings.rules.sum.gone") })375 case "star": return t("nx.settings.rules.sum.star")376 case "mark_read": return t("nx.settings.rules.sum.markRead")377 case "pin": return t("nx.settings.rules.sum.pin")378 case "snooze": return t("nx.settings.rules.sum.snooze", { until: untilText(a.until_rule) })379 case "remind": return t("nx.settings.rules.sum.remind", { delay: hoursText(a.after_hours) })380 case "event": return t("nx.settings.rules.sum.event", { name: a.name })381 case "notify_app": return t("nx.settings.rules.sum.notifyApp", { name: a.app })382 case "draft_reply":383 return a.ai_tone ? t("nx.settings.rules.sum.draftAi", { tone: toneLabel(a.ai_tone) }) : t("nx.settings.rules.sum.draftSnippet", { name: ctx.snippets.find((s) => s.id === a.snippet_id)?.name ?? t("nx.settings.rules.sum.gone") })384 case "extract": return t("nx.settings.rules.sum.extract", { fields: a.schema.fields.map((f) => f.name).join(", ") })385 }386}387/** « De contient « x » et Objet contient « y » → étiqueter « Z », marquer comme suivi » */388export function ruleSummary(r: Pick<RuleInput, "match" | "conditions" | "actions" | "stop">, ctx: SummaryContext): string {389 const conds = r.conditions.length ? r.conditions.map(conditionSummary).join(r.match === "any" ? t("nx.settings.rules.sum.or") : t("nx.settings.rules.sum.and")) : t("nx.settings.rules.sum.always")390 const acts = r.actions.map((a) => actionSummary(a, ctx)).join(", ")391 return `${conds} → ${acts}${r.stop ? t("nx.settings.rules.sum.stop") : ""}`392}393export function scopeSummary(r: Pick<RuleInput, "mailbox_ids">, ctx: SummaryContext): string {394 if (!r.mailbox_ids || !r.mailbox_ids.length) return t("nx.settings.rules.scopeAll")395 return r.mailbox_ids.map((id) => ctx.mailbox(id) || t("nx.settings.rules.sum.gone")).join(", ")396}397398// ---------------------------------------------------------------- ordre399/**400 * Déplace une règle d'un cran. Rend la liste réordonnée (positions renumérotées 0…n-1) et les seules écritures nécessaires.401 * L'ordre compte : les règles s'appliquent de haut en bas, « arrêter » coupe les suivantes.402 */403export function reorderRules<T extends { id: string; position: number }>(rules: T[], id: string, delta: -1 | 1): { rules: T[]; patches: { id: string; position: number }[] } {404 const at = rules.findIndex((r) => r.id === id)405 const to = at + delta406 if (at < 0 || to < 0 || to >= rules.length) return { rules, patches: [] }407 const next = [...rules]408 ;[next[at], next[to]] = [next[to], next[at]]409 const patches: { id: string; position: number }[] = []410 const out = next.map((r, i) => {411 if (r.position === i) return r412 patches.push({ id: r.id, position: i })413 return { ...r, position: i }414 })415 return { rules: out, patches }416}417418// ---------------------------------------------------------------- appels419export const listRules = (signal?: AbortSignal) => nx.list<Rule>("rules", undefined, signal)420export const createRule = (rule: RuleInput) => nx.post<Rule>("rules", rule)421export const patchRule = (id: string, patch: Partial<RuleInput> & { position?: number }) => nx.patch<Rule>(`rules/${encodeURIComponent(id)}`, patch)422export const deleteRule = (id: string) => nx.del(`rules/${encodeURIComponent(id)}`)423export const listRuns = (id: string, signal?: AbortSignal) => nx.list<RuleRun>(`rules/${encodeURIComponent(id)}/runs`, { limit: 30 }, signal)424export const testRule = (rule: RuleInput, mailboxId: string, emailId: string, signal?: AbortSignal) => nx.post<RuleTestResult>("rules/test", { rule, mailbox_id: mailboxId, email_id: emailId }, signal)425export const listLabels = (signal?: AbortSignal) => nx.list<LabelRef>("labels", undefined, signal)426export const listSnippets = (signal?: AbortSignal) => nx.list<SnippetRef>("snippets", undefined, signal)427/** Messages récents d'une boîte, pour choisir celui de l'essai à blanc. */428export const recentMessages = async (mailboxId: string, signal?: AbortSignal) => (await nx.get<{ data: MessageSummary[] }>("search", { q: "in:inbox", mailboxes: mailboxId, limit: 20 }, signal)).data429/** La couche d'intelligence est-elle active pour ce compte ? (`provider` autre que « off » ; faux si la lecture échoue). */430export const aiActive = async (signal?: AbortSignal): Promise<boolean> => {431 try {432 return ((await nx.get<{ provider?: string }>("ai/settings", undefined, signal)).provider ?? "off") !== "off"433 } catch {434 return false435 }436}437