Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Mail8 * File : web/src/ui/admin/automation/panel.tsx9 * Module : ui10 * Repository : https://git.spboucher.ai/sp-mail11 * Project Website : https://mail.spboucher.ai12 * Created : 2026-11-1913 * Last Modified : 2026-11-1914 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Automatisation d'une boîte, vue par l'administrateur : règles de tri, réexpédition et réponse automatique, lues et écrites44// par GET/PUT /api/v1/addresses/{boîte}/automation. Le constructeur de règles et le formulaire de réponse automatique45// sont ceux des Réglages (settings/Filters.tsx, settings/Vacation.tsx), réutilisés tels quels.46import { useCallback, useEffect, useId, useMemo, useState, type FormEvent } from "react"47import { isPhysicalKind } from "../../../admin/addresses"48import { addMessages, t } from "../../../i18n"49import { enAdmAutomation } from "../../../i18n/en.adm.automation"50import { frAdmAutomation } from "../../../i18n/fr.adm.automation"51import { HttpError } from "../../../jmap/errors"52import { isValidEmail } from "../../../mail/address"53import { emptySieveConfig, newRule, ruleIsComplete, type Rule, type VacationConfig } from "../../../mail/sieve"54import { v1, type ApiAddress } from "../../../mail/v1"55import { S, toast } from "../../../state/app"56import { ConfirmDialog, Field, Icon, IconButton, Spinner } from "../../kit"57import { Section } from "../../Page"58import { RuleDialog, ruleSummary } from "../../settings/Filters"59import { VacationForm } from "../../settings/Vacation"60import type { SieveApi, SieveData } from "../../settings/useSieve"61import { loadAddresses } from "../kit"62import { Loadable, errorText, useLoad } from "../shared"63import "../../settings/settings.css"64import "./automation.css"6566addMessages("fr", frAdmAutomation)67addMessages("en", enAdmAutomation)6869// ---------------------------------------------------------------- API70export interface Forward {71 to: string72 keep_copy: boolean73}74export interface Automation {75 /** faux = script écrit à la main : règles et réponse automatique ne sont pas modifiables (409 custom_script) */76 managed: boolean77 active: boolean78 rules: Rule[]79 vacation: VacationConfig80 forward: Forward | null81 /** script stocké, rendu aux administrateurs seulement */82 raw_sieve?: string83}84type AutomationInput = { rules?: Rule[]; vacation?: VacationConfig; forward?: Forward | null }8586const autoPath = (address: string) => `/addresses/${encodeURIComponent(address)}/automation`87/** Lecture défensive : l'API type `rules` et `vacation` en « any ». */88function tidy(raw: Automation): Automation {89 const rules = Array.isArray(raw.rules) ? raw.rules.filter((r): r is Rule => !!r && typeof r.id === "string" && Array.isArray(r.conditions) && Array.isArray(r.actions)) : []90 return { ...raw, managed: raw.managed !== false, active: raw.active === true, rules, vacation: { ...emptySieveConfig().vacation, ...(raw.vacation ?? {}) }, forward: raw.forward && typeof raw.forward.to === "string" ? raw.forward : null }91}92export const getAutomation = async (address: string, signal?: AbortSignal): Promise<Automation> => tidy(await v1<Automation>(autoPath(address), { signal }))93export const putAutomation = async (address: string, input: AutomationInput): Promise<Automation> => tidy(await v1<Automation>(autoPath(address), { method: "PUT", json: input }))9495export const autoErrorText = (e: unknown): string =>96 errorText(e, {97 custom_script: t("adm.auto.err.customScript"),98 forward_not_local: t("adm.auto.err.forwardNotLocal"),99 forward_loop: t("adm.auto.err.forwardLoop"),100 not_a_mailbox: t("adm.auto.err.notAMailbox"),101 invalid_sieve: t("adm.auto.err.invalidSieve", { detail: e instanceof HttpError ? e.message : "" }),102 })103104/**105 * Dossiers proposés comme destination d'une règle. L'administrateur ne lit les dossiers que de ses propres boîtes106 * (ou de celles qu'on lui partage) : pour les autres, la liste reste vide et le nom du dossier se saisit.107 */108async function loadFolders(address: string, signal: AbortSignal): Promise<string[]> {109 if (!S.get().me?.mailboxes.some((m) => m.address === address)) return []110 try {111 const { data } = await v1<{ data: { id: string; name: string; role: string | null; parent_id: string | null }[] }>(`/folders?address=${encodeURIComponent(address)}`, { signal })112 const byId = new Map(data.map((f) => [f.id, f]))113 const path = (f: (typeof data)[number]) => {114 const parts = [f.name]115 let cur = f116 for (let i = 0; i < 12 && cur.parent_id; i++) {117 const p = byId.get(cur.parent_id)118 if (!p) break119 parts.unshift(p.name)120 cur = p121 }122 return parts.join("/")123 }124 return data.filter((f) => !["drafts", "sent", "trash", "junk"].includes(f.role ?? "")).map(path).sort((a, b) => a.localeCompare(b))125 } catch {126 return [] // la liste des dossiers est un confort : son absence ne bloque pas l'édition des règles127 }128}129130// ---------------------------------------------------------------- une boîte131export type AutoPart = "forward" | "rules" | "vacation"132133/** Automatisation d'une boîte (adresse principale). `parts` choisit les blocs affichés, dans l'ordre donné. */134export function MailboxAutomation({ address, parts }: { address: string; parts: readonly AutoPart[] }) {135 const load = useLoad(async (signal) => {136 const [auto, folders] = await Promise.all([getAutomation(address, signal), parts.includes("rules") ? loadFolders(address, signal) : Promise.resolve([])])137 return { auto, folders }138 })139 const [fresh, setFresh] = useState<Automation | null>(null)140 // un rechargement explicite repart de la réponse du serveur141 useEffect(() => setFresh(null), [load.data])142143 if (load.error) {144 return (145 <div className="banner danger" role="alert">146 <Icon name="warn" />147 <span className="adm-grow">{autoErrorText(load.error)}</span>148 <button type="button" className="btn small" onClick={load.reload}>149 {t("common.retry")}150 </button>151 </div>152 )153 }154 if (!load.data) return <Spinner label={t("common.loading")} />155 const auto = fresh ?? load.data.auto156 return (157 <div className="adm-auto" data-testid="automation" data-mailbox={address}>158 {auto.managed ? null : <CustomScript auto={auto} />}159 {parts.map((part) =>160 part === "forward" ? (161 <ForwardCard key={`f-${auto.forward?.to ?? ""}-${auto.forward?.keep_copy ?? ""}`} address={address} auto={auto} onSaved={setFresh} />162 ) : part === "rules" ? (163 auto.managed ? <RulesCard key="r" address={address} auto={auto} folders={load.data!.folders} onSaved={setFresh} /> : null164 ) : auto.managed ? (165 <VacationCard key="v" address={address} auto={auto} onSaved={setFresh} />166 ) : null,167 )}168 </div>169 )170}171172function CustomScript({ auto }: { auto: Automation }) {173 return (174 <Section title={t("adm.auto.custom.title")}>175 <div className="banner warn" role="status" data-testid="automation-custom">176 <Icon name="warn" />177 <div>{t("adm.auto.custom.body")}</div>178 </div>179 {auto.raw_sieve ? (180 <details className="adm-auto-raw">181 <summary>{t("adm.auto.custom.show")}</summary>182 <pre className="adm-pre mono" tabIndex={0} aria-label={t("adm.auto.custom.script")}>183 {auto.raw_sieve}184 </pre>185 </details>186 ) : null}187 </Section>188 )189}190191// ---------------------------------------------------------------- règles192function RulesCard({ address, auto, folders, onSaved }: { address: string; auto: Automation; folders: string[]; onSaved: (a: Automation) => void }) {193 const [rules, setRules] = useState<Rule[]>(auto.rules)194 const [dirty, setDirty] = useState(false)195 const [saving, setSaving] = useState(false)196 const [error, setError] = useState<string | null>(null)197 const [editing, setEditing] = useState<{ rule: Rule; isNew: boolean } | null>(null)198 const [removing, setRemoving] = useState<Rule | null>(null)199 const own = S.get().me?.mailboxes.some((m) => m.address === address) ?? false200201 const change = (next: Rule[]) => {202 setRules(next)203 setDirty(true)204 }205 const move = (i: number, delta: number) => {206 const j = i + delta207 if (j < 0 || j >= rules.length) return208 const next = [...rules]209 ;[next[i], next[j]] = [next[j], next[i]]210 change(next)211 }212 const apply = (rule: Rule) => {213 change(rules.some((r) => r.id === rule.id) ? rules.map((r) => (r.id === rule.id ? rule : r)) : [...rules, rule])214 setEditing(null)215 }216 const save = async () => {217 if (saving) return218 setSaving(true)219 setError(null)220 try {221 const next = await putAutomation(address, { rules })222 setRules(next.rules)223 setDirty(false)224 onSaved(next)225 toast({ kind: "success", text: t("adm.auto.rules.saved", { address }) })226 } catch (e) {227 setError(autoErrorText(e))228 } finally {229 setSaving(false)230 }231 }232233 return (234 <>235 <Section236 title={t("settings.filters.title")}237 description={t("adm.auto.rules.desc")}238 actions={239 <button type="button" className="btn small" onClick={() => setEditing({ rule: newRule(crypto.randomUUID()), isNew: true })}>240 <Icon name="plus" small />241 <span>{t("settings.filters.add")}</span>242 </button>243 }244 >245 {rules.length === 0 ? (246 <p className="muted">{t("settings.filters.empty")}</p>247 ) : (248 <ol className="set-list adm-auto-rules" aria-label={t("settings.filters.title")}>249 {rules.map((r, i) => {250 const name = r.name.trim() || t("settings.filters.unnamed")251 return (252 <li key={r.id} className="set-item" data-rule-id={r.id}>253 <div className="set-item-row">254 <label className="check set-item-main">255 <input type="checkbox" checked={r.enabled} aria-label={t("settings.filters.enableLabel", { name })} onChange={(e) => change(rules.map((x) => (x.id === r.id ? { ...x, enabled: e.target.checked } : x)))} />256 <span className="set-rule-text">257 <strong className="set-wrap">{name}</strong> {ruleIsComplete(r) ? null : <span className="badge warn">{t("settings.filters.incompleteBadge")}</span>}258 <span className="muted small set-wrap set-block">{ruleSummary(r)}</span>259 </span>260 </label>261 <div className="row set-rule-actions">262 <IconButton icon="chevron" className="set-up" label={t("settings.filters.moveUp", { name })} disabled={i === 0} onClick={() => move(i, -1)} />263 <IconButton icon="chevron" label={t("settings.filters.moveDown", { name })} disabled={i === rules.length - 1} onClick={() => move(i, 1)} />264 <IconButton icon="edit" label={t("settings.filters.editLabel", { name })} onClick={() => setEditing({ rule: r, isNew: false })} />265 <IconButton icon="trash" label={t("settings.filters.deleteLabel", { name })} onClick={() => setRemoving(r)} />266 </div>267 </div>268 </li>269 )270 })}271 </ol>272 )}273 <div className="row wrap set-actions">274 <button type="button" className="btn primary" disabled={saving} onClick={() => void save()} data-testid="rules-save">275 {t("settings.filters.saveActivate")}276 </button>277 {saving ? <Spinner /> : null}278 <span className="muted small" role="status">279 {dirty ? t("settings.filters.unsaved") : ""}280 </span>281 <span className="spacer" />282 <span className={`badge ${auto.active ? "ok" : ""}`}>{auto.active ? t("adm.auto.stateActive") : t("adm.auto.stateInactive")}</span>283 </div>284 {error ? (285 <p className="adm-error" role="alert">286 {error}287 </p>288 ) : null}289 {own ? null : <p className="muted small">{t("adm.auto.rules.foldersNote")}</p>}290 </Section>291 {editing ? <RuleDialog initial={editing.rule} isNew={editing.isNew} folders={folders} onApply={apply} onClose={() => setEditing(null)} /> : null}292 {removing ? (293 <ConfirmDialog294 title={t("settings.filters.deleteTitle")}295 body={t("settings.filters.deleteBody", { name: removing.name.trim() || t("settings.filters.unnamed") })}296 confirmLabel={t("common.delete")}297 danger298 onConfirm={() => change(rules.filter((r) => r.id !== removing.id))}299 onClose={() => setRemoving(null)}300 />301 ) : null}302 </>303 )304}305306// ---------------------------------------------------------------- réexpédition307function ForwardCard({ address, auto, onSaved }: { address: string; auto: Automation; onSaved: (a: Automation) => void }) {308 const [enabled, setEnabled] = useState(auto.forward !== null)309 const [to, setTo] = useState(auto.forward?.to ?? "")310 const [keep, setKeep] = useState(auto.forward?.keep_copy ?? true)311 const [saving, setSaving] = useState(false)312 const [error, setError] = useState<string | null>(null)313 const id = useId()314 // Avec un script écrit à la main, l'API régénérerait le script pour poser la réexpédition : on ne l'écrit pas d'ici.315 const locked = !auto.managed316317 const save = async (e: FormEvent) => {318 e.preventDefault()319 if (saving || locked) return320 const dest = to.trim().toLowerCase()321 if (enabled && !isValidEmail(dest)) return setError(t("adm.auto.err.forwardInvalid"))322 if (enabled && dest === address) return setError(t("adm.auto.err.forwardLoop"))323 setError(null)324 setSaving(true)325 try {326 const next = await putAutomation(address, { forward: enabled ? { to: dest, keep_copy: keep } : null })327 onSaved(next)328 toast({ kind: "success", text: enabled ? t("adm.auto.forward.savedOn", { to: dest }) : t("adm.auto.forward.savedOff") })329 } catch (err) {330 setError(autoErrorText(err))331 } finally {332 setSaving(false)333 }334 }335336 return (337 <Section338 title={t("adm.auto.forward.title")}339 description={t("adm.auto.forward.desc")}340 actions={341 <span className={`badge ${auto.forward ? "ok" : ""}`} role="status" data-forward-state={auto.forward ? "on" : "off"}>342 {auto.forward ? t("adm.auto.forward.on", { to: auto.forward.to }) : t("adm.auto.forward.off")}343 </span>344 }345 >346 <form className="stack set-form" onSubmit={(e) => void save(e)} noValidate>347 <label className="check">348 <input type="checkbox" checked={enabled} disabled={locked} onChange={(e) => setEnabled(e.target.checked)} />349 <span>{t("adm.auto.forward.enable")}</span>350 </label>351 <Field id={`${id}-to`} label={t("adm.auto.forward.to")} hint={t("adm.auto.forward.toHint")}>352 <input id={`${id}-to`} className="input" type="email" inputMode="email" autoComplete="off" spellCheck={false} value={to} disabled={locked || !enabled} onChange={(e) => setTo(e.target.value)} maxLength={254} aria-invalid={error && enabled ? true : undefined} />353 </Field>354 <label className="check">355 <input type="checkbox" checked={keep} disabled={locked || !enabled} onChange={(e) => setKeep(e.target.checked)} />356 <span>{t("adm.auto.forward.keep")}</span>357 </label>358 {error ? (359 <p className="adm-error" role="alert">360 {error}361 </p>362 ) : null}363 <div className="row wrap">364 <button type="submit" className="btn primary" disabled={saving || locked}>365 {t("common.save")}366 </button>367 {saving ? <Spinner /> : null}368 </div>369 </form>370 </Section>371 )372}373374// ---------------------------------------------------------------- réponse automatique375/** Le formulaire des Réglages, branché sur l'API d'automatisation au lieu du script JMAP de la boîte de l'utilisateur. */376function VacationCard({ address, auto, onSaved }: { address: string; auto: Automation; onSaved: (a: Automation) => void }) {377 const [saving, setSaving] = useState(false)378 const [scriptError, setScriptError] = useState<string | null>(null)379 const data: SieveData = useMemo(() => ({ scriptId: null, active: auto.active, config: { rules: auto.rules, vacation: auto.vacation }, custom: !auto.managed, raw: "", legacy: null }), [auto])380 const saveConfig = useCallback(381 async (config: { vacation: VacationConfig }): Promise<boolean> => {382 setSaving(true)383 setScriptError(null)384 try {385 onSaved(await putAutomation(address, { vacation: config.vacation }))386 return true387 } catch (e) {388 setScriptError(autoErrorText(e))389 return false390 } finally {391 setSaving(false)392 }393 },394 [address, onSaved],395 )396 const sieve: SieveApi = {397 state: { status: "ready", data },398 reload: () => {},399 saving,400 scriptError,401 clearScriptError: () => setScriptError(null),402 saveConfig,403 // le script brut ne se modifie pas d'ici : seul le formulaire (saveConfig) est utilisé404 saveRaw: async () => false,405 validate: async () => null,406 generate: () => "",407 }408 return (409 <div data-testid="autoreply" className="adm-auto">410 <VacationForm sieve={sieve} data={data} />411 </div>412 )413}414415// ---------------------------------------------------------------- choix de la boîte (onglets Règles et Réponses automatiques)416/** Dernière boîte choisie : conservée en passant d'un onglet d'automatisation à l'autre. */417let lastBox = ""418419export function MailboxScoped({ parts }: { parts: readonly AutoPart[] }) {420 const load = useLoad(async (signal) => (await loadAddresses(signal)).filter((a) => isPhysicalKind(a.kind)))421 const [picked, setPicked] = useState(lastBox)422 const id = useId()423 const boxes: ApiAddress[] = load.data ?? []424 const current = boxes.find((b) => b.address === picked) ?? boxes[0]425 const pick = (address: string) => {426 lastBox = address427 setPicked(address)428 }429 return (430 <Loadable431 load={load}432 toolbar={433 <div className="field adm-auto-pick">434 <label htmlFor={id}>{t("adm.auto.box")}</label>435 <select id={id} className="select" value={current?.address ?? ""} disabled={boxes.length === 0} onChange={(e) => pick(e.target.value)} data-testid="automation-mailbox">436 {boxes.map((b) => (437 <option key={b.id} value={b.address}>438 {b.kind === "shared" ? t("adm.auto.kindSuffix", { address: b.address, kind: t("adm.kind.shared") }) : b.address}439 </option>440 ))}441 </select>442 </div>443 }444 >445 {() =>446 current ? (447 <>448 <p className="muted small">{t("adm.auto.boxHint")}</p>449 <MailboxAutomation key={current.address} address={current.address} parts={parts} />450 </>451 ) : (452 <section className="card section empty">453 <p className="muted">{t("adm.auto.noBoxes")}</p>454 </section>455 )456 }457 </Loadable>458 )459}460