Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

11.0 KB
Raw Blame
import { useCallback } from "react";
import { InfoTooltip } from "@editor/ui/InfoTooltip";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import {
  TextInput,
  NumberInput,
  Switch,
  Stack,
  Paper,
  Text,
  Loader,
  Group,
  Anchor,
} from "@mantine/core";
import { alert } from "@editor/components/toast";
import RestartConfirmationModal from "@editor/components/shared/config/RestartConfirmationModal";
import { useRestartServer } from "@editor/components/shared/config/useRestartServer";
import { useAdminSettings } from "@editor/hooks/useAdminSettings";
import { useSettingsDirty } from "@editor/hooks/useSettingsDirty";
import PendingBadge from "@editor/components/shared/config/PendingBadge";
import { SettingsStickyFooter } from "@editor/components/shared/config/SettingsStickyFooter";
import EditableSecretField from "@editor/components/shared/EditableSecretField";
import apiClient from "@editor/services/apiClient";
import { useLoginRequired } from "@editor/hooks/useLoginRequired";
import { privateContentClassName } from "@editor/components/shared/privateContentClassName";

type MailSettingsData = {
  enabled?: boolean;
  enableInvites?: boolean;
  inviteLinkExpiryHours?: number;
  host?: string;
  port?: number;
  username?: string;
  password?: string;
  from?: string;
};

interface ApiResponseWithPending<T> {
  _pending?: Partial<T>;
}

type MailApiResponse = MailSettingsData &
  ApiResponseWithPending<MailSettingsData>;

export default function AdminMailSection() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { loginEnabled } = useLoginRequired();
  const {
    restartModalOpened,
    showRestartModal,
    closeRestartModal,
    restartServer,
  } = useRestartServer();

  const {
    settings,
    setSettings,
    loading,
    saving,
    saveSettings,
    isFieldPending,
  } = useAdminSettings<MailSettingsData>({
    sectionName: "mail",
    fetchTransformer: async (): Promise<
      MailSettingsData & { _pending?: Partial<MailSettingsData> }
    > => {
      const mailResponse = await apiClient.get<MailApiResponse>(
        "/api/v1/admin/settings/section/mail",
      );
      return mailResponse.data || {};
    },
    saveTransformer: (settings: MailSettingsData) => {
      return {
        sectionData: settings,
        deltaSettings: {},
      };
    },
  });

  const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(
    settings,
    loading,
  );

  const handleSave = async () => {
    try {
      markSaved();
      await saveSettings();
      showRestartModal();
    } catch (_error) {
      alert({
        alertType: "error",
        title: t("admin.error", "Error"),
        body: t("admin.settings.saveError", "Failed to save settings"),
      });
    }
  };

  const handleDiscard = useCallback(() => {
    const original = resetToSnapshot();
    setSettings(original);
  }, [resetToSnapshot, setSettings]);

  if (loading) {
    return (
      <Stack align="center" justify="center" h={200}>
        <Loader size="lg" />
      </Stack>
    );
  }

  return (
    <div className="settings-section-container">
      <Stack gap="lg" className="settings-section-content">
        <div>
          <Text fw={600} size="lg">
            {t("admin.settings.mail.title", "Mail Configuration")}
          </Text>
          <Text size="sm" c="dimmed">
            {t(
              "admin.settings.mail.description",
              "Configure SMTP settings for email notifications.",
            )}
          </Text>
        </div>

        <Paper withBorder p="md" radius="md">
          <Stack gap="md">
            <Group justify="space-between" align="flex-start" wrap="nowrap">
              <div>
                <Text fw={500} size="sm">
                  {t("admin.settings.mail.enabled.label", "Enable Mail")}{" "}
                  <InfoTooltip
                    label={t(
                      "admin.settings.mail.enabled.description",
                      "Enable email notifications and SMTP functionality",
                    )}
                  />
                </Text>
              </div>
              <Group gap="xs">
                <Switch
                  checked={settings.enabled || false}
                  onChange={(e) =>
                    setSettings({ ...settings, enabled: e.target.checked })
                  }
                />
                <PendingBadge show={isFieldPending("enabled")} />
              </Group>
            </Group>

            <Group justify="space-between" align="flex-start" wrap="nowrap">
              <div>
                <Text fw={500} size="sm">
                  {t(
                    "admin.settings.mail.enableInvites.label",
                    "Enable Email Invites",
                  )}{" "}
                  <InfoTooltip
                    label={t(
                      "admin.settings.mail.enableInvites.description",
                      "Allow admins to invite users via email with auto-generated passwords",
                    )}
                  />
                </Text>
                <Text size="xs" c="var(--color-amber-dark)" mt={8} fw={500}>
                  {t(
                    "admin.settings.mail.frontendUrlNote.note",
                    "Note: Requires Frontend URL to be configured. ",
                  )}
                  <Anchor
                    href="#"
                    onClick={(e) => {
                      e.preventDefault();
                      navigate("/settings/adminGeneral#frontendUrl");
                    }}
                    c="var(--color-amber-dark)"
                    td="underline"
                  >
                    {t(
                      "admin.settings.mail.frontendUrlNote.link",
                      "Configure in System Settings",
                    )}
                  </Anchor>
                </Text>
              </div>
              <Group gap="xs">
                <Switch
                  checked={settings.enableInvites || false}
                  onChange={(e) =>
                    setSettings({
                      ...settings,
                      enableInvites: e.target.checked,
                    })
                  }
                  disabled={!settings.enabled}
                />
                <PendingBadge show={isFieldPending("enableInvites")} />
              </Group>
            </Group>

            <div>
              <TextInput
                className={privateContentClassName}
                label={
                  <Group gap="xs">
                    <span>
                      {t("admin.settings.mail.host.label", "SMTP Host")}
                    </span>
                    <PendingBadge show={isFieldPending("host")} />
                    <InfoTooltip
                      label={t(
                        "admin.settings.mail.host.description",
                        "SMTP server hostname",
                      )}
                    />
                  </Group>
                }
                value={settings.host || ""}
                onChange={(e) =>
                  setSettings({ ...settings, host: e.target.value })
                }
                placeholder="smtp.example.com"
              />
            </div>

            <div>
              <NumberInput
                label={
                  <Group gap="xs">
                    <span>
                      {t("admin.settings.mail.port.label", "SMTP Port")}
                    </span>
                    <PendingBadge show={isFieldPending("port")} />
                    <InfoTooltip
                      label={t(
                        "admin.settings.mail.port.description",
                        "SMTP server port (typically 587 for TLS, 465 for SSL)",
                      )}
                    />
                  </Group>
                }
                value={settings.port || 587}
                onChange={(value) =>
                  setSettings({ ...settings, port: Number(value) })
                }
                min={1}
                max={65535}
              />
            </div>

            <div>
              <TextInput
                className={privateContentClassName}
                label={
                  <Group gap="xs">
                    <span>
                      {t("admin.settings.mail.username.label", "SMTP Username")}
                    </span>
                    <PendingBadge show={isFieldPending("username")} />
                    <InfoTooltip
                      label={t(
                        "admin.settings.mail.username.description",
                        "SMTP authentication username",
                      )}
                    />
                  </Group>
                }
                value={settings.username || ""}
                onChange={(e) =>
                  setSettings({ ...settings, username: e.target.value })
                }
              />
            </div>

            <div>
              <Group gap="xs" align="center" mb={4}>
                <span style={{ fontWeight: 500, fontSize: "0.875rem" }}>
                  {t("admin.settings.mail.password.label", "SMTP Password")}
                </span>
                <PendingBadge show={isFieldPending("password")} />
              </Group>
              <EditableSecretField
                description={t(
                  "admin.settings.mail.password.description",
                  "SMTP authentication password",
                )}
                value={settings.password || ""}
                onChange={(value) =>
                  setSettings({ ...settings, password: value })
                }
                placeholder={t(
                  "admin.settings.mail.password.placeholder",
                  "Enter SMTP password",
                )}
              />
            </div>

            <div>
              <TextInput
                className={privateContentClassName}
                label={
                  <Group gap="xs">
                    <span>
                      {t("admin.settings.mail.from.label", "From Address")}
                    </span>
                    <PendingBadge show={isFieldPending("from")} />
                    <InfoTooltip
                      label={t(
                        "admin.settings.mail.from.description",
                        "Email address to use as sender",
                      )}
                    />
                  </Group>
                }
                value={settings.from || ""}
                onChange={(e) =>
                  setSettings({ ...settings, from: e.target.value })
                }
                placeholder="[email protected]"
              />
            </div>
          </Stack>
        </Paper>
      </Stack>

      <SettingsStickyFooter
        isDirty={isDirty}
        saving={saving}
        loginEnabled={loginEnabled}
        onSave={handleSave}
        onDiscard={handleDiscard}
      />

      {/* Restart Confirmation Modal */}
      <RestartConfirmationModal
        opened={restartModalOpened}
        onClose={closeRestartModal}
        onRestart={restartServer}
      />
    </div>
  );
}