Skip to content

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

9.4 KB
Raw Blame
import React, { Suspense, lazy, useState, useEffect } from "react";
import { SettingsEmptyState } from "@editor/components/shared/config/SettingsEmptyState";
import { isAxiosError } from "axios";
import {
  Tabs,
  Loader,
  Alert,
  Stack,
  Text,
  Accordion,
  Center,
} from "@mantine/core";
import { Button } from "@editor/ui/Button";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import auditService, {
  AuditSystemStatus as AuditStatus,
} from "@editor/services/auditService";
import AuditSystemStatus from "@editor/components/shared/config/configSections/audit/AuditSystemStatus";
import AuditStatsCards from "@editor/components/shared/config/configSections/audit/AuditStatsCards";

// AuditChartsSection pulls in recharts (~200 kB gzip). It's only rendered when
// the user expands the "Events Over Time" accordion on this page, so we keep
// the rest of the audit page eager and lazy-load just the charts.
const AuditChartsSection = lazy(
  () =>
    import("@editor/components/shared/config/configSections/audit/AuditChartsSection"),
);
import AuditEventsTable from "@editor/components/shared/config/configSections/audit/AuditEventsTable";
import AuditExportSection from "@editor/components/shared/config/configSections/audit/AuditExportSection";
import AuditClearDataSection from "@editor/components/shared/config/configSections/audit/AuditClearDataSection";
import { useLoginRequired } from "@editor/hooks/useLoginRequired";
import { useAppConfig } from "@editor/contexts/AppConfigContext";
import EnterpriseRequiredBanner from "@editor/components/shared/config/EnterpriseRequiredBanner";
import { Icon } from "@editor/ui/Icon";

type TimePeriod = "day" | "week" | "month";

const ConfigureAuditBanner = ({ show }: { show: boolean }) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  if (!show) return null;
  return (
    <Alert
      icon={<Icon name="info" size="1.2rem" />}
      title={t("audit.configureAudit", "Configure Audit Logging")}
      color="blue"
      variant="light"
    >
      <Stack gap="xs">
        <Text size="sm">
          {t(
            "audit.configureAuditMessage",
            "Adjust audit logging level, retention period, and other settings in the Security & Authentication section.",
          )}
        </Text>
        <Button
          variant="secondary"
          size="sm"
          onClick={() => navigate("/settings/adminSecurity#auditLogging")}
          rightSection={<Icon name="arrow-right" size="0.9rem" />}
        >
          {t("audit.goToSettings", "Go to Audit Settings")}
        </Button>
      </Stack>
    </Alert>
  );
};

interface AuditDashboardProps {
  isEnabled: boolean;
  timePeriod: TimePeriod;
  onTimePeriodChange: (period: TimePeriod) => void;
}

const AuditDashboard = ({
  isEnabled,
  timePeriod,
  onTimePeriodChange,
}: AuditDashboardProps) => {
  const { t } = useTranslation();
  return (
    <Stack gap="lg">
      {/* Stats Cards - Always Visible */}
      <AuditStatsCards loginEnabled={isEnabled} timePeriod={timePeriod} />

      {/* Charts in Accordion - Collapsible */}
      <Accordion defaultValue={["events-over-time"]} multiple>
        <Accordion.Item value="events-over-time">
          <Accordion.Control>
            {t("audit.charts.overTime", "Events Over Time")}
          </Accordion.Control>
          <Accordion.Panel>
            <Suspense
              fallback={
                <Center style={{ padding: "2rem" }}>
                  <Loader />
                </Center>
              }
            >
              <AuditChartsSection
                loginEnabled={isEnabled}
                timePeriod={timePeriod}
                onTimePeriodChange={onTimePeriodChange}
              />
            </Suspense>
          </Accordion.Panel>
        </Accordion.Item>
      </Accordion>
    </Stack>
  );
};

interface AuditTabsProps extends AuditDashboardProps {
  status: AuditStatus;
}

const AuditTabs = ({ status, ...dashboard }: AuditTabsProps) => {
  const { t } = useTranslation();
  const { isEnabled } = dashboard;
  if (!status.enabled) {
    return (
      <Alert
        color="blue"
        title={t("audit.disabled", "Audit logging is disabled")}
      >
        {t(
          "audit.disabledMessage",
          "Enable audit logging in your application configuration to track system events.",
        )}
      </Alert>
    );
  }
  return (
    <Tabs defaultValue="dashboard">
      <Tabs.List>
        <Tabs.Tab value="dashboard" disabled={!isEnabled}>
          {t("audit.tabs.dashboard", "Dashboard")}
        </Tabs.Tab>
        <Tabs.Tab value="events" disabled={!isEnabled}>
          {t("audit.tabs.events", "Audit Events")}
        </Tabs.Tab>
        <Tabs.Tab value="export" disabled={!isEnabled}>
          {t("audit.tabs.export", "Export")}
        </Tabs.Tab>
        <Tabs.Tab value="clearData" disabled={!isEnabled}>
          {t("audit.tabs.clearData", "Clear Data")}
        </Tabs.Tab>
      </Tabs.List>

      <Tabs.Panel value="dashboard" pt="md">
        <AuditDashboard {...dashboard} />
      </Tabs.Panel>

      <Tabs.Panel value="events" pt="md">
        <AuditEventsTable
          loginEnabled={isEnabled}
          captureFileHash={status.captureFileHash}
          capturePdfAuthor={status.capturePdfAuthor}
        />
      </Tabs.Panel>

      <Tabs.Panel value="export" pt="md">
        <AuditExportSection
          loginEnabled={isEnabled}
          captureFileHash={status.captureFileHash}
          capturePdfAuthor={status.capturePdfAuthor}
          captureOperationResults={status.captureOperationResults}
        />
      </Tabs.Panel>

      <Tabs.Panel value="clearData" pt="md">
        <AuditClearDataSection loginEnabled={isEnabled} />
      </Tabs.Panel>
    </Tabs>
  );
};

const AdminAuditSection: React.FC = () => {
  const { t } = useTranslation();
  const { loginEnabled } = useLoginRequired();
  const { config } = useAppConfig();
  const licenseType = config?.license ?? "NORMAL";
  const hasEnterpriseLicense = licenseType === "ENTERPRISE";
  const showDemoData = !loginEnabled || !hasEnterpriseLicense;
  const [systemStatus, setSystemStatus] = useState<AuditStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [timePeriod, setTimePeriod] = useState<TimePeriod>("week");

  useEffect(() => {
    const fetchSystemStatus = async () => {
      try {
        setLoading(true);
        setError(null);
        const status = await auditService.getSystemStatus();
        setSystemStatus(status);
      } catch (err: unknown) {
        // Check if this is a permission/license error (403/404)
        const status = isAxiosError(err) ? err.response?.status : undefined;
        if (status === 403 || status === 404) {
          setError("enterprise-license-required");
        } else {
          setError(
            err instanceof Error
              ? err.message
              : t(
                  "audit.error.loadStatus",
                  "Failed to load audit system status",
                ),
          );
        }
      } finally {
        setLoading(false);
      }
    };

    if (!showDemoData) {
      fetchSystemStatus();
    } else {
      // Provide example audit system status when running in demo mode
      setError(null);
      setSystemStatus({
        enabled: true,
        level: "INFO",
        retentionDays: 90,
        totalEvents: 1234,
        pdfMetadataEnabled: true,
        captureFileHash: true,
        capturePdfAuthor: true,
        captureOperationResults: false,
      });
      setLoading(false);
    }
  }, [loginEnabled, showDemoData]);

  // Override loading state when showing demo data
  const actualLoading = showDemoData ? false : loading;

  if (actualLoading) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          padding: "2rem 0",
        }}
      >
        <Loader size="lg" />
      </div>
    );
  }

  if (error) {
    if (error === "enterprise-license-required") {
      return (
        <Alert
          color="blue"
          title={t("audit.enterpriseRequired", "Enterprise License Required")}
        >
          {t(
            "audit.enterpriseRequiredMessage",
            "The audit logging system is an enterprise feature. Please upgrade to an enterprise license to access audit logs and analytics.",
          )}
        </Alert>
      );
    }
    return (
      <Alert
        color="red"
        title={t("audit.error.title", "Error loading audit system")}
      >
        {error}
      </Alert>
    );
  }

  if (!systemStatus) {
    return (
      <SettingsEmptyState
        icon="clipboard-check"
        title={t("audit.notAvailable", "Audit logging is off")}
      >
        {t(
          "audit.notAvailableMessage",
          "Turn it on in Sign-in & security to start recording activity.",
        )}
      </SettingsEmptyState>
    );
  }

  const isEnabled = loginEnabled && hasEnterpriseLicense;

  return (
    <Stack gap="lg">
      <EnterpriseRequiredBanner
        show={!hasEnterpriseLicense}
        featureName={t("settings.licensingAnalytics.audit", "Audit")}
      />

      <ConfigureAuditBanner show={isEnabled} />

      <AuditSystemStatus status={systemStatus} />

      <AuditTabs
        status={systemStatus}
        isEnabled={isEnabled}
        timePeriod={timePeriod}
        onTimePeriodChange={setTimePeriod}
      />
    </Stack>
  );
};

export default AdminAuditSection;