SPB Git

Repository Public

Create.tsx 8.3 KB 162 lines tsx

1// Création d'une adresse, sans code : nature (boîte, boîte partagée, alias, notification, envoi seul, réception seule,2// temporaire), puis les seuls champs utiles à cette nature. Le corps de la requête est construit par admin/addresses.ts.3import { useId, useMemo, useState, type FormEvent } from "react"4import { ALL_KINDS, buildCreatePayload, emptyCreateForm, isPhysicalKind, normaliseGrants, type CreateForm, type Grant } from "../../../admin/addresses"5import { t } from "../../../i18n"6import { apiPut } from "../../../jmap/http"7import { v1, type AddressKind, type ApiAddress } from "../../../mail/v1"8import { S, toast } from "../../../state/app"9import { Dialog, Field } from "../../kit"10import { isCancelled, sensitive } from "../kit"11import { DASH, errorText } from "../shared"12import { GrantsFields, addrCodes, formErrorText, refreshOwnBoxes, userLabel, type AdminUser } from "./common"1314export function CreateDialog({ initialKind, addresses, users, domains, onCreated, onClose }: { initialKind: AddressKind; addresses: readonly ApiAddress[]; users: readonly AdminUser[]; domains: readonly string[]; onCreated: (a: ApiAddress) => void; onClose: () => void }) {15  const meId = S.get().me?.user.id ?? ""16  const [form, setForm] = useState<CreateForm>(() => ({ ...emptyCreateForm(initialKind), ownerId: users.some((u) => u.id === meId) ? meId : "" }))17  const [grants, setGrants] = useState<Grant[]>([])18  const [busy, setBusy] = useState(false)19  const [error, setError] = useState<string | null>(null)20  const id = useId()21  const set = (patch: Partial<CreateForm>) => setForm((f) => ({ ...f, ...patch }))22  const physical = isPhysicalKind(form.kind)23  const boxes = useMemo(() => addresses.filter((a) => isPhysicalKind(a.kind)), [addresses])24  const known = useMemo(() => new Set(addresses.map((a) => a.address)), [addresses])25  const ownerId = form.ownerId || meId || null2627  const submit = async (e?: FormEvent) => {28    e?.preventDefault()29    if (busy) return30    const built = buildCreatePayload(form, known)31    if (!built.ok) return setError(formErrorText(built))32    setError(null)33    setBusy(true)34    try {35      const created = await sensitive(() => v1<ApiAddress>("/addresses", { method: "POST", json: built.value }))36      if (physical) refreshOwnBoxes()37      const wanted = form.kind === "shared" ? normaliseGrants(grants, ownerId) : []38      if (wanted.length) {39        try {40          await sensitive(() => apiPut(`/api/admin/mailboxes/${encodeURIComponent(created.mailbox_id)}/grants`, { grants: wanted }))41        } catch (err) {42          // la boîte existe : on le dit, plutôt que de laisser croire que rien n'a été créé43          toast({ kind: "error", text: t("adm.addr.create.grantsFailed", { address: created.address }), detail: isCancelled(err) ? undefined : errorText(err, addrCodes(err)) })44          onCreated(created)45          return46        }47      }48      toast({ kind: "success", text: t("adm.addr.created", { address: created.address }) })49      onCreated(created)50    } catch (err) {51      if (!isCancelled(err)) setError(errorText(err, addrCodes(err)))52    } finally {53      setBusy(false)54    }55  }5657  return (58    <Dialog59      title={t("adm.addr.create.title")}60      onClose={onClose}61      wide62      footer={63        <>64          <button type="button" className="btn" onClick={onClose}>65            {t("common.cancel")}66          </button>67          <button type="button" className="btn primary" disabled={busy} onClick={() => void submit()} data-testid="address-create-submit">68            {busy ? <span className="spinner" aria-hidden="true" /> : null}69            <span>{t("adm.addr.create.submit")}</span>70          </button>71        </>72      }73    >74      <form className="stack" onSubmit={(e) => void submit(e)} noValidate data-testid="address-create">75        <fieldset className="adm-addr-kinds">76          <legend className="label">{t("adm.addr.create.kind")}</legend>77          {ALL_KINDS.map((k) => (78            <label key={k} className="adm-choice">79              <input type="radio" name={`${id}-kind`} checked={form.kind === k} onChange={() => set({ kind: k })} data-testid={`kind-${k}`} />80              <span>81                <strong>{t(`adm.kind.${k}`)}</strong>82                <span className="muted small">{t(`adm.addr.kindDesc.${k}`)}</span>83              </span>84            </label>85          ))}86        </fieldset>8788        <div className="adm-addr-grid">89          <Field id={`${id}-address`} label={t("adm.addr.create.address")} hint={domains.length ? t("adm.addr.create.addressHint", { domains: domains.join(", ") }) : undefined}>90            <input id={`${id}-address`} className="input" type="email" inputMode="email" autoComplete="off" autoCapitalize="off" spellCheck={false} value={form.address} onChange={(e) => set({ address: e.target.value })} maxLength={254} required data-autofocus />91          </Field>92          <Field id={`${id}-name`} label={t("adm.addr.create.name")}>93            <input id={`${id}-name`} className="input" value={form.displayName} onChange={(e) => set({ displayName: e.target.value })} maxLength={80} autoComplete="off" />94          </Field>95        </div>9697        {physical ? (98          <>99            {users.length ? (100              <Field id={`${id}-owner`} label={t("adm.addr.create.owner")} hint={t("adm.addr.create.ownerHint")}>101                <select id={`${id}-owner`} className="select" value={form.ownerId} onChange={(e) => set({ ownerId: e.target.value })}>102                  {users.some((u) => u.id === form.ownerId) ? null : <option value="">{DASH}</option>}103                  {users.map((u) => (104                    <option key={u.id} value={u.id}>105                      {userLabel(u)}106                    </option>107                  ))}108                </select>109              </Field>110            ) : null}111            {form.kind === "shared" ? (112              <div className="stack">113                <p className="muted small">{t("adm.addr.grants.desc")}</p>114                <GrantsFields users={users} ownerId={ownerId} value={grants} onChange={setGrants} />115              </div>116            ) : null}117          </>118        ) : (119          <>120            <Field id={`${id}-mailbox`} label={t("adm.addr.create.mailbox")} hint={t("adm.addr.create.mailboxHint")}>121              <select id={`${id}-mailbox`} className="select" value={form.mailbox} onChange={(e) => set({ mailbox: e.target.value })} required>122                <option value="">{t("adm.addr.create.chooseMailbox")}</option>123                {boxes.map((b) => (124                  <option key={b.id} value={b.address}>125                    {b.address}126                  </option>127                ))}128              </select>129            </Field>130            {form.kind === "send_only" ? (131              <Field id={`${id}-reply`} label={t("adm.addr.field.replyPolicy")}>132                <select id={`${id}-reply`} className="select" value={form.replyPolicy} onChange={(e) => set({ replyPolicy: e.target.value as CreateForm["replyPolicy"] })}>133                  {(["reject", "accept", "discard"] as const).map((p) => (134                    <option key={p} value={p}>135                      {t(`adm.addr.reply.${p}`)}136                    </option>137                  ))}138                </select>139              </Field>140            ) : (141              <Field id={`${id}-dest`} label={t("adm.addr.field.destinations")} hint={t("adm.addr.field.destinationsHint")}>142                <textarea id={`${id}-dest`} className="textarea mono" rows={3} value={form.destinations} onChange={(e) => set({ destinations: e.target.value })} spellCheck={false} autoCapitalize="off" />143              </Field>144            )}145            <Field id={`${id}-expires`} label={t("adm.addr.field.expires")} hint={t(form.kind === "temporary" ? "adm.addr.field.expiresHintTemp" : "adm.addr.field.expiresHint")}>146              <input id={`${id}-expires`} className="input" type="datetime-local" value={form.expiresLocal} onChange={(e) => set({ expiresLocal: e.target.value })} required={form.kind === "temporary"} aria-required={form.kind === "temporary"} />147            </Field>148          </>149        )}150151        {error ? (152          <p className="adm-error" role="alert" data-testid="address-create-error">153            {error}154          </p>155        ) : null}156        {/* Entrée dans un champ valide le formulaire */}157        <button type="submit" hidden />158      </form>159    </Dialog>160  )161}162
Files main
Menu

Theme