SPB Git

Repository Public

Editor.tsx 20.1 KB 383 lines tsx

1// Fiche d'une adresse : identité (nom, avatar), signatures (texte + HTML assaini, aperçu dans un cadre isolé), envoi et2// réception, état, échéance, destinations, quota et conservation (boîtes), accès partagés, automatisation, clés d'API3// autorisées (lecture seule), zone sensible. L'enregistrement n'envoie que ce qui a changé (admin/addresses.ts › buildPatch).4import { useEffect, useId, useMemo, useRef, useState, type FormEvent } from "react"5import { PROTECTED_LOCKED, addressState, buildPatch, convertibleKinds, editFormOf, isPhysicalKind, keysForAddress, normaliseGrants, patchIsEmpty, usageRatio, type EditForm, type Grant, type KeyRef } from "../../../admin/addresses"6import { t } from "../../../i18n"7import { apiGet, apiPut } from "../../../jmap/http"8import { v1, type AddressKind, type ApiAddress } from "../../../mail/v1"9import { toast } from "../../../state/app"10import { linkProps } from "../../../state/session"11import { Field, Icon, Spinner } from "../../kit"12import { Section } from "../../Page"13import { MailboxAutomation } from "../automation/panel"14import { SafeHtmlFrame, isCancelled, sensitive, toastFail } from "../kit"15import { asArray, asString, errorText, fmtBytes, isRecord, useLoad } from "../shared"16import { DeleteDialog, GrantsFields, ProtectedBadge, StateBadge, SuspendDialog, addrCodes, formErrorText, ownerOf, setAddressStatus, userLabel, type AdminUser } from "./common"17import { AvatarField, RichField } from "./Signature"1819const AUTO_PARTS = ["forward", "vacation", "rules"] as const2021function parseKey(raw: unknown): KeyRef | null {22  if (!isRecord(raw)) return null23  const id = asString(raw.id)24  if (!id) return null25  const strings = (v: unknown) => asArray(v).filter((x): x is string => typeof x === "string")26  return { id, name: asString(raw.name) ?? id, prefix: asString(raw.prefix) ?? "", state: asString(raw.state) ?? "active", scopes: strings(raw.scopes), address_ids: strings(raw.address_ids), all_addresses: raw.all_addresses === true }27}2829export function AddressEditor({ address, all, users, usedBytes, onBack, onChanged, onOpen, onDeleted }: {30  address: ApiAddress31  all: readonly ApiAddress[]32  users: readonly AdminUser[]33  usedBytes: number | null34  onBack: () => void35  /** la liste doit être relue (sans quitter la fiche) */36  onChanged: () => void37  onOpen: (id: string) => void38  onDeleted: () => void39}) {40  const [a, setA] = useState(address)41  const [form, setForm] = useState<EditForm>(() => editFormOf(address))42  const [saving, setSaving] = useState(false)43  const [error, setError] = useState<string | null>(null)44  const [suspending, setSuspending] = useState(false)45  const [deleting, setDeleting] = useState(false)46  const heading = useRef<HTMLHeadingElement>(null)47  const id = useId()48  const set = (patch: Partial<EditForm>) => setForm((f) => ({ ...f, ...patch }))4950  // à l'ouverture, le titre de la fiche reçoit le focus (lecteurs d'écran, clavier)51  useEffect(() => heading.current?.focus(), [])5253  const physical = isPhysicalKind(a.kind)54  const known = useMemo(() => new Set(all.map((x) => x.address)), [all])55  const built = buildPatch(a, form, known)56  const dirty = !built.ok || !patchIsEmpty(built.value)57  const locked = (field: (typeof PROTECTED_LOCKED)[number]) => a.protected && PROTECTED_LOCKED.includes(field)58  const forced = form.kind === "send_only" || form.kind === "receive_only"59  const receives = form.kind === "send_only" ? false : form.kind === "receive_only" ? true : form.canReceive60  const box = all.find((x) => x.address === a.mailbox && isPhysicalKind(x.kind))61  const ratio = usageRatio(usedBytes, a.quota_bytes)6263  const adopt = (next: ApiAddress) => {64    setA(next)65    setForm(editFormOf(next))66    onChanged()67  }68  const save = async (e: FormEvent) => {69    e.preventDefault()70    if (saving) return71    if (!built.ok) return setError(formErrorText(built))72    setError(null)73    if (patchIsEmpty(built.value)) return void toast({ kind: "info", text: t("adm.addr.unchanged") })74    setSaving(true)75    try {76      const next = await sensitive(() => v1<ApiAddress>(`/addresses/${encodeURIComponent(a.id)}`, { method: "PATCH", json: built.value }))77      adopt(next)78      toast({ kind: "success", text: t("adm.addr.saved", { address: next.address }) })79    } catch (err) {80      if (!isCancelled(err)) setError(errorText(err, addrCodes(err)))81    } finally {82      setSaving(false)83    }84  }85  const refetch = async () => {86    try {87      const next = await v1<ApiAddress>(`/addresses/${encodeURIComponent(a.id)}`)88      setA(next)89      setForm((f) => ({ ...f, kind: next.kind }))90    } catch {91      /* la liste relue portera l'état à jour */92    }93    onChanged()94  }9596  return (97    <div className="adm adm-addr-editor" data-testid="address-editor" data-address={a.address}>98      <div className="adm-addr-head">99        <button type="button" className="btn small" onClick={onBack} data-testid="address-editor-back">100          <Icon name="back" small />101          <span>{t("adm.addr.edit.back")}</span>102        </button>103        <h3 ref={heading} tabIndex={-1}>104          {t("adm.addr.edit.title", { address: a.address })}105        </h3>106        <span className="badge">{t(`adm.kind.${a.kind}`)}</span>107        <StateBadge a={a} />108        {a.protected ? <ProtectedBadge /> : null}109      </div>110      {a.protected ? (111        <div className="banner warn" role="note" data-testid="address-protected-banner">112          <Icon name="shield" />113          <div>{t("adm.addr.edit.protectedBanner")}</div>114        </div>115      ) : null}116117      <form className="adm-addr-form" onSubmit={(e) => void save(e)} noValidate>118        <Section title={t("adm.addr.edit.identity")}>119          <div className="adm-addr-fields">120            <Field id={`${id}-name`} label={t("adm.addr.edit.name")} hint={t("adm.addr.edit.nameHint")}>121              <input id={`${id}-name`} className="input" value={form.displayName} onChange={(e) => set({ displayName: e.target.value })} maxLength={80} autoComplete="off" />122            </Field>123            <AvatarField address={a.address} value={form.avatar} onChange={(avatar) => set({ avatar })} />124          </div>125        </Section>126127        <Section title={t("adm.addr.edit.signatures")} description={t("adm.addr.edit.signaturesDesc")}>128          <div className="adm-addr-fields">129            <Field id={`${id}-sigt`} label={t("adm.addr.sig.text")}>130              <textarea id={`${id}-sigt`} className="textarea" rows={4} value={form.signatureText} onChange={(e) => set({ signatureText: e.target.value })} maxLength={4000} />131            </Field>132            <RichField key={a.id} label={t("adm.addr.sig.html")} hint={t("adm.addr.sig.htmlHint")} value={form.signatureHtml} onChange={(signatureHtml) => set({ signatureHtml })} />133            <div className="field">134              <span className="label">{t("adm.addr.sig.preview")}</span>135              {form.signatureHtml.trim() ? <SafeHtmlFrame html={form.signatureHtml} title={t("adm.addr.sig.preview")} height={140} /> : <p className="muted small">{t("adm.addr.sig.previewEmpty")}</p>}136            </div>137          </div>138        </Section>139140        <Section title={t("adm.addr.edit.delivery")}>141          <div className="adm-addr-fields">142            <Field id={`${id}-kind`} label={t("adm.addr.edit.kind")} hint={locked("kind") ? t("adm.addr.edit.lockedHint") : t(physical ? "adm.addr.edit.kindBoxHint" : "adm.addr.edit.kindAliasHint")}>143              <select id={`${id}-kind`} className="select" value={form.kind} disabled={physical || locked("kind")} onChange={(e) => set({ kind: e.target.value as AddressKind })}>144                {convertibleKinds(a.kind).map((k) => (145                  <option key={k} value={k}>146                    {t(`adm.kind.${k}`)}147                  </option>148                ))}149              </select>150            </Field>151            <div className="stack">152              <label className="check">153                <input type="checkbox" checked={form.kind === "send_only" ? true : form.kind === "receive_only" ? false : form.canSend} disabled={forced} onChange={(e) => set({ canSend: e.target.checked })} />154                <span>{t("adm.addr.edit.canSend")}</span>155              </label>156              <label className="check">157                <input type="checkbox" checked={receives} disabled={forced || locked("can_receive")} onChange={(e) => set({ canReceive: e.target.checked })} />158                <span>{t("adm.addr.edit.canReceive")}</span>159              </label>160              {forced ? <span className="muted small">{t("adm.addr.edit.forcedHint")}</span> : locked("can_receive") ? <span className="muted small">{t("adm.addr.edit.lockedHint")}</span> : null}161            </div>162            {receives ? null : (163              <Field id={`${id}-reply`} label={t("adm.addr.field.replyPolicy")} hint={locked("reply_policy") ? t("adm.addr.edit.lockedHint") : undefined}>164                <select id={`${id}-reply`} className="select" value={form.replyPolicy} disabled={locked("reply_policy")} onChange={(e) => set({ replyPolicy: e.target.value as EditForm["replyPolicy"] })}>165                  {(["reject", "accept", "discard"] as const).map((p) => (166                    <option key={p} value={p}>167                      {t(`adm.addr.reply.${p}`)}168                    </option>169                  ))}170                </select>171              </Field>172            )}173            <Field id={`${id}-status`} label={t("adm.addr.edit.status")} hint={locked("status") ? t("adm.addr.edit.lockedHint") : t("adm.addr.edit.statusHint")}>174              <select id={`${id}-status`} className="select" value={form.status} disabled={locked("status")} onChange={(e) => set({ status: e.target.value as EditForm["status"] })}>175                <option value="active">{t("adm.status.active")}</option>176                <option value="suspended">{t("adm.status.suspended")}</option>177              </select>178            </Field>179            {physical ? null : (180              <>181                <Field id={`${id}-expires`} label={t("adm.addr.field.expires")} hint={locked("expires_at") ? t("adm.addr.edit.lockedHint") : t(form.kind === "temporary" ? "adm.addr.field.expiresHintTemp" : "adm.addr.field.expiresHint")}>182                  <input id={`${id}-expires`} className="input" type="datetime-local" value={form.expiresLocal} disabled={locked("expires_at")} onChange={(e) => set({ expiresLocal: e.target.value })} aria-required={form.kind === "temporary"} />183                </Field>184                {form.kind === "send_only" ? null : (185                  <Field id={`${id}-dest`} label={t("adm.addr.field.destinations")} hint={locked("extra_destinations") ? t("adm.addr.edit.lockedHint") : t("adm.addr.field.destinationsHint")}>186                    <textarea id={`${id}-dest`} className="textarea mono" rows={3} value={form.destinations} disabled={locked("extra_destinations")} onChange={(e) => set({ destinations: e.target.value })} spellCheck={false} autoCapitalize="off" />187                  </Field>188                )}189              </>190            )}191          </div>192        </Section>193194        {physical ? (195          <Section title={t("adm.addr.edit.storage")} description={t("adm.addr.edit.retentionDesc")}>196            <div className="adm-addr-fields">197              <Field id={`${id}-quota`} label={t("adm.addr.edit.quota")} hint={t("adm.addr.edit.quotaHint")}>198                <input id={`${id}-quota`} className="input set-narrow" inputMode="decimal" value={form.quotaGb} onChange={(e) => set({ quotaGb: e.target.value })} autoComplete="off" />199              </Field>200              {usedBytes !== null ? (201                <div className="adm-addr-usage">202                  <span className="small">{t("adm.addr.edit.used", { used: a.quota_bytes ? t("adm.addr.usage.of", { used: fmtBytes(usedBytes), quota: fmtBytes(a.quota_bytes) }) : fmtBytes(usedBytes) })}</span>203                  {ratio !== null ? <progress className={ratio >= 0.9 ? "danger" : undefined} value={ratio} max={1} aria-label={t("adm.addr.usage.label", { address: a.address })} /> : null}204                </div>205              ) : null}206              <div className="adm-addr-grid">207                <Field id={`${id}-rt`} label={t("adm.addr.edit.retTrash")} hint={locked("retention_trash_days") ? t("adm.addr.edit.lockedHint") : undefined}>208                  <input id={`${id}-rt`} className="input" inputMode="numeric" value={form.retentionTrashDays} disabled={locked("retention_trash_days")} onChange={(e) => set({ retentionTrashDays: e.target.value })} autoComplete="off" />209                </Field>210                <Field id={`${id}-rj`} label={t("adm.addr.edit.retJunk")} hint={locked("retention_junk_days") ? t("adm.addr.edit.lockedHint") : undefined}>211                  <input id={`${id}-rj`} className="input" inputMode="numeric" value={form.retentionJunkDays} disabled={locked("retention_junk_days")} onChange={(e) => set({ retentionJunkDays: e.target.value })} autoComplete="off" />212                </Field>213                <Field id={`${id}-ra`} label={t("adm.addr.edit.retAll")} hint={locked("retention_days") ? t("adm.addr.edit.lockedHint") : t("adm.addr.edit.retAllHint")}>214                  <input id={`${id}-ra`} className="input" inputMode="numeric" value={form.retentionDays} disabled={locked("retention_days")} onChange={(e) => set({ retentionDays: e.target.value })} autoComplete="off" />215                </Field>216              </div>217            </div>218          </Section>219        ) : null}220221        <div className="adm-addr-savebar">222          <button type="submit" className="btn primary" disabled={saving} data-testid="address-save">223            {saving ? <span className="spinner" aria-hidden="true" /> : null}224            <span>{t("adm.addr.edit.save")}</span>225          </button>226          <span className="muted small" role="status" data-testid="address-dirty">227            {dirty ? t("adm.addr.edit.dirty") : ""}228          </span>229          {error ? (230            <p className="adm-error adm-grow" role="alert" data-testid="address-save-error">231              {error}232            </p>233          ) : null}234        </div>235      </form>236237      {physical ? <GrantsCard a={a} users={users} onSaved={() => void refetch()} /> : null}238239      {physical ? (240        <MailboxAutomation key={a.address} address={a.address} parts={AUTO_PARTS} />241      ) : (242        <Section title={t("adm.addr.auto.title")}>243          <div className="stack">244            <p>{t("adm.addr.auto.aliasNote", { mailbox: a.mailbox })}</p>245            {box ? (246              <div>247                <button type="button" className="btn small" onClick={() => onOpen(box.id)}>248                  {t("adm.addr.auto.openBox", { mailbox: box.address })}249                </button>250              </div>251            ) : null}252          </div>253        </Section>254      )}255256      <KeysCard addressId={a.id} />257258      <section className="card section adm-addr-danger">259        <div className="row section-head">260          <h3>{t("adm.addr.danger.title")}</h3>261        </div>262        <div className="stack">263          <p className="muted small">{t(physical ? "adm.addr.danger.boxDesc" : "adm.addr.danger.aliasDesc")}</p>264          {a.protected ? (265            <p className="row" id={`${id}-prot`}>266              <ProtectedBadge />267              <span>{t("adm.addr.danger.protected")}</span>268            </p>269          ) : null}270          <div className="row wrap">271            {addressState(a) === "suspended" ? (272              <button type="button" className="btn" disabled={a.protected} onClick={() => void setAddressStatus(a, "active").then((next) => next && adopt(next))}>273                {t("adm.addr.act.resume")}274              </button>275            ) : (276              <button type="button" className="btn" disabled={a.protected || a.status === "suspended"} aria-describedby={a.protected ? `${id}-prot` : undefined} onClick={() => setSuspending(true)}>277                {t("adm.addr.act.suspend")}278              </button>279            )}280            <button type="button" className="btn danger" disabled={a.protected} aria-describedby={a.protected ? `${id}-prot` : undefined} onClick={() => setDeleting(true)} data-testid="address-delete">281              {t(physical ? "adm.addr.danger.deleteBox" : "adm.addr.danger.deleteAlias")}282            </button>283          </div>284        </div>285      </section>286287      {suspending ? <SuspendDialog address={a} onDone={adopt} onClose={() => setSuspending(false)} /> : null}288      {deleting ? <DeleteDialog address={a} onDeleted={onDeleted} onClose={() => setDeleting(false)} /> : null}289    </div>290  )291}292293// ---------------------------------------------------------------- accès partagés294function GrantsCard({ a, users, onSaved }: { a: ApiAddress; users: readonly AdminUser[]; onSaved: () => void }) {295  const path = `/api/admin/mailboxes/${encodeURIComponent(a.mailbox_id)}/grants`296  const load = useLoad(async (signal) =>297    asArray(await apiGet<unknown>(path, signal)).flatMap((g): Grant[] => (isRecord(g) && asString(g.user_id) ? [{ user_id: asString(g.user_id)!, can_read: g.can_read === true, can_send: g.can_send === true }] : [])),298  )299  const [draft, setDraft] = useState<Grant[] | null>(null)300  const [saving, setSaving] = useState(false)301  useEffect(() => setDraft(null), [load.data])302  const owner = ownerOf(users, a.mailbox_id)303  const value = draft ?? load.data ?? []304305  const save = async () => {306    setSaving(true)307    try {308      await sensitive(() => apiPut(path, { grants: normaliseGrants(value, owner?.id ?? null) }))309      toast({ kind: "success", text: t("adm.addr.grants.saved", { address: a.address }) })310      load.reload()311      onSaved()312    } catch (e) {313      toastFail(e, addrCodes(e))314    } finally {315      setSaving(false)316    }317  }318  return (319    <Section title={t("adm.addr.grants.title")} description={t("adm.addr.grants.desc")}>320      {load.error ? (321        <p className="adm-error" role="alert">322          {errorText(load.error)}323        </p>324      ) : load.data === null ? (325        <Spinner label={t("common.loading")} />326      ) : (327        <div className="stack">328          {owner ? <p className="small">{t("adm.addr.grants.owner", { user: userLabel(owner) })}</p> : null}329          <GrantsFields users={users} ownerId={owner?.id ?? null} value={value} onChange={setDraft} disabled={saving} />330          <div className="row wrap">331            <button type="button" className="btn" disabled={saving || draft === null} onClick={() => void save()} data-testid="grants-save">332              {t("adm.addr.grants.save")}333            </button>334            {saving ? <Spinner /> : null}335          </div>336        </div>337      )}338    </Section>339  )340}341342// ---------------------------------------------------------------- clés d'API autorisées (lecture seule)343function KeysCard({ addressId }: { addressId: string }) {344  const load = useLoad(async (signal) => asArray(await apiGet<unknown>("/api/admin/api-keys", signal)).map(parseKey).filter((k): k is KeyRef => k !== null))345  const keys = load.data ? keysForAddress(load.data, addressId) : []346  return (347    <Section348      title={t("adm.addr.keys.title")}349      description={t("adm.addr.keys.desc")}350      actions={351        <a className="btn small" {...linkProps("/admin/keys")}>352          <Icon name="key" small />353          <span>{t("adm.addr.keys.open")}</span>354        </a>355      }356    >357      {load.error ? (358        <p className="adm-error" role="alert">359          {t("adm.addr.keys.failed", { detail: errorText(load.error) })}360        </p>361      ) : load.data === null ? (362        <Spinner label={t("common.loading")} />363      ) : keys.length === 0 ? (364        <p className="muted" data-testid="address-keys-empty">365          {t("adm.addr.keys.none")}366        </p>367      ) : (368        <ul className="adm-addr-keys" data-testid="address-keys">369          {keys.map((k) => (370            <li key={k.id}>371              <strong className="adm-break">{k.name}</strong>372              {k.prefix ? <span className="mono muted">{k.prefix}…</span> : null}373              <span className={`badge ${k.state === "active" ? "ok" : "warn"}`}>{k.state === "revoked" ? t("adm.addr.keys.state.revoked") : k.state === "expired" ? t("adm.addr.keys.state.expired") : t("adm.addr.keys.state.active")}</span>374              <span className="badge">{k.all_addresses ? t("adm.addr.keys.all") : t("adm.addr.keys.explicit")}</span>375              <span className="muted small adm-break">{k.scopes.join(", ")}</span>376            </li>377          ))}378        </ul>379      )}380    </Section>381  )382}383
Files main
Menu

Theme