strapi-plugin-magic-sessionmanager 4.21.0 → 4.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +92 -47
  3. package/dist/admin/{Analytics-BqdZIBV4.js → Analytics-B7BAjApz.js} +1 -1
  4. package/dist/admin/{Analytics-C-OLLzoB.mjs → Analytics-CIHgaURb.mjs} +1 -1
  5. package/dist/admin/{App-BswHmNQT.mjs → App-CPE-CQGz.mjs} +1309 -2564
  6. package/dist/admin/{App-Cx9v6n_7.js → App-DJkJC06E.js} +1336 -2591
  7. package/dist/admin/{OnlineUsersWidget-BRmQPPp9.js → OnlineUsersWidget-CcjNfzzf.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-Dusgjc1d.mjs → OnlineUsersWidget-Dou2hxGY.mjs} +1 -1
  9. package/dist/admin/{Settings-DWGuf_Z3.js → Settings--eEiHv_a.js} +104 -81
  10. package/dist/admin/{Settings-DZyQheUS.mjs → Settings-h_exWUiI.mjs} +62 -39
  11. package/dist/admin/dashboardModel-DNT_l-Bk.js +169 -0
  12. package/dist/admin/dashboardModel-fApbKGay.mjs +170 -0
  13. package/dist/admin/{de-DUnrmFWk.mjs → de-Wz5Emtrb.mjs} +79 -7
  14. package/dist/admin/{de-24TPqzG6.js → de-oBmcAcXj.js} +79 -7
  15. package/dist/admin/{en-8mBSkWOF.js → en-B1TN5F62.js} +80 -8
  16. package/dist/admin/{en-D8J__tyF.mjs → en-B_1Ka64U.mjs} +80 -8
  17. package/dist/admin/{es-ChUKey-Q.js → es-Bb515J0p.js} +79 -7
  18. package/dist/admin/{es-BgpgWdk0.mjs → es-CVgw4zsj.mjs} +79 -7
  19. package/dist/admin/{fr-k1MHYKJo.mjs → fr-0AgMxTFc.mjs} +79 -7
  20. package/dist/admin/{fr-DE_CWmgq.js → fr-yDdwunmg.js} +79 -7
  21. package/dist/admin/index-DVQ7tdTC.mjs +4746 -0
  22. package/dist/admin/index-qtN2dOm4.js +4747 -0
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +2 -2
  25. package/dist/admin/{pt-BjqU5ioB.js → pt-BAB07LY-.js} +79 -7
  26. package/dist/admin/{pt-DPO4DmDc.mjs → pt-DtM74ffN.mjs} +79 -7
  27. package/dist/server/index.js +1487 -438
  28. package/dist/server/index.mjs +1487 -438
  29. package/package.json +4 -3
  30. package/dist/admin/index-Ceh3Q1Ki.js +0 -2308
  31. package/dist/admin/index-meLDPPwt.mjs +0 -2307
  32. package/dist/admin/settingsTabs-C1q5iMMw.mjs +0 -437
  33. package/dist/admin/settingsTabs-CfquZuKH.js +0 -436
@@ -3,12 +3,12 @@ import { useFetchClient, useNotification, useClipboard, useRBAC, useQueryParams,
3
3
  import { NavLink, Link as Link$1, Routes, Route } from "react-router-dom";
4
4
  import { useMemo, useState, useEffect, useRef, useId, useCallback, useLayoutEffect } from "react";
5
5
  import { useIntl } from "react-intl";
6
- import { Typography, Flex, Loader, Button, Modal, Accordion, Box, IconButton, Link, SimpleMenu, MenuItem, Grid, Table, Thead, Tr, Th, VisuallyHidden, Tbody, Td, Tooltip, SearchForm, Searchbar, TextButton, SingleSelect, SingleSelectOption, EmptyStateLayout, LinkButton, Badge, Tabs, Field, Textarea, Dialog, Tag } from "@strapi/design-system";
7
- import { Earth, Duplicate, Cross, Eye, Trash, More, CaretDown, Download, ArrowClockwise, Check, Clock, User, ChartBubble, Cog, SignOut, Information, Webhooks, WarningCircle, Monitor, Key, Stack, Lock, CrossCircle, Shield, CheckCircle, ArrowRight } from "@strapi/icons";
6
+ import { Typography, Flex, Loader, Button, Modal, Accordion, Box, IconButton, Link, SimpleMenu, MenuItem, Grid, Table, Thead, Tr, Th, VisuallyHidden, Tbody, Td, Tooltip, SearchForm, Searchbar, TextButton, SingleSelect, SingleSelectOption, LinkButton, EmptyStateLayout, Badge, Tabs, Field, Textarea, Dialog } from "@strapi/design-system";
7
+ import { Earth, Duplicate, Cross, Eye, Trash, More, CaretDown, Download, ArrowRight, ArrowClockwise, Check, Clock, User, ChartBubble, Cog, SignOut } from "@strapi/icons";
8
8
  import { EmptyDocuments } from "@strapi/icons/symbols";
9
9
  import styled, { useTheme } from "styled-components";
10
- import { g as getSessionEndReason, a as getEndReasonPresentation, b as getTranslation, p as presentText, u as useSessionFormatters, c as getSessionStatus, d as getDevicePresentation, i as isNativeOnlySession, e as getSessionEndReasonPresentation, D as DeviceIcon, S as StatusBadge, P as PropertyList, C as ConfirmAction, t as toValidDate, f as pluginId, l as logSafeAdminError, h as PersistentAlert, R as ReadableText, j as pluginPermissions, M as MissingValue, V as ValueOrMissing, k as SESSION_STATES, m as SESSION_STATUS_PRESENTATION, n as isCancelledRequest, o as SESSION_FILTER_OPTIONS, E as END_REASON_FILTER_OPTIONS, q as PageShell, r as StatGrid, s as StatCard, v as restoreDialogFocus, w as requireSessionList, x as getBadgeColors, T as TargetLink$1, y as useSettingsTranslate, z as useSecondsLeft, A as validateReason, B as REASON_MAX, F as formatClock } from "./index-meLDPPwt.mjs";
11
- import { i as isRiskSource, g as getSessionUserLabels, a as getUserEditPath, R as RISK_SETTINGS_PATH, b as RowActions, s as shouldIsolateActionKey, c as shouldRedispatchEscape, D as DASHBOARD_COMPACT_TABLE_COLUMNS, d as DASHBOARD_TABLE_COLUMNS, r as readDisclosureOpen, e as getBrowserStorage, w as writeDisclosureOpen, u as useElementWidth, p as parseDashboardQuery, A as AUTO_REFRESH_INTERVAL_MS, f as pickFocusSessionId, h as encodeSearchQuery, j as shouldUseCompactTable, P as PAGE_SIZE_OPTIONS, k as DEFAULT_PAGE_SIZE, l as getExportDeviceInfo, m as getErrorStatus, n as hasActiveFilters, S as SETTINGS_TAB_IDS, o as SETTINGS_TAB_FIELDS, q as SETTINGS_FIELD_LABELS, t as SETTINGS_TAB_LABELS } from "./settingsTabs-C1q5iMMw.mjs";
10
+ import { g as getSessionEndReason, a as getEndReasonPresentation, b as getTranslation, p as presentText, u as useSessionFormatters, c as getSessionStatus, d as getDevicePresentation, i as isNativeOnlySession, e as getSessionEndReasonPresentation, D as DeviceIcon, S as StatusBadge, P as PropertyList, C as ConfirmAction, t as toValidDate, f as pluginId, l as logSafeAdminError, h as PersistentAlert, R as ReadableText, j as pluginPermissions, M as MissingValue, V as ValueOrMissing, k as SESSION_STATES, m as SESSION_STATUS_PRESENTATION, n as buildSignInParams, o as useEventList, q as SignInEventTable, r as PERIOD_OPTIONS, s as buildSignInCsv, v as SIGN_IN_FILTER_OPTIONS, w as buildActivityParams, x as buildActivityCsv, A as ActivityEventTable, y as ACTIVITY_ACTION_OPTIONS, z as ACTIVITY_ACTION_LABELS, B as downloadCsv, E as MAX_EVENT_EXPORT_ROWS, F as isCancelledRequest, G as RECENT_EVENT_LIMIT, H as buildUserActivityParams, I as RECENT_USER_EVENT_LIMIT, U as USER_ACTIVITY_API_PATH, J as USER_ACTIVITY_PAGE_PATH, K as UserEventTable, L as useElementWidth, N as SESSION_FILTER_OPTIONS, O as END_REASON_FILTER_OPTIONS, Q as PageShell, T as StatGrid, W as StatCard, X as buildSessionCsv, Y as buildSessionJson, Z as restoreDialogFocus, _ as requireSessionList, $ as getAdminStatusPresentation, a0 as getBadgeColors, a1 as useSettingsTranslate, a2 as useSecondsLeft, a3 as validateReason, a4 as REASON_MAX, a5 as formatClock, a6 as parseAdminPanelQuery, a7 as buildAdminListParams, a8 as withIdentityPlaceholders, a9 as ADMIN_FILTER_OPTIONS, aa as ADMIN_PAGE_SIZE_OPTIONS, ab as ADMIN_DEFAULT_PAGE_SIZE, ac as hasAdminFilters, ad as getSignOutErrorMessage, ae as splitDuration, af as parseActivityPageQuery, ag as EVENT_PAGE_SIZE, ah as ACTIVITY_PAGE_SIZE_OPTIONS, ai as ALL_ADMINS_FILTER_OPTIONS, aj as hasActivityPageFilters, ak as parseUserActivityQuery, al as userText, am as buildUserActivityCsv, an as USER_ACTIVITY_SETTINGS_PATH, ao as USER_ACTIVITY_FILTER_OPTIONS, ap as USER_ACTIVITY_FILTER_LABELS, aq as hasUserActivityFilters } from "./index-DVQ7tdTC.mjs";
11
+ import { i as isRiskSource, g as getSessionUserLabels, a as getUserEditPath, R as RISK_SETTINGS_PATH, b as RowActions, s as shouldIsolateActionKey, c as shouldRedispatchEscape, D as DASHBOARD_COMPACT_TABLE_COLUMNS, d as DASHBOARD_TABLE_COLUMNS, r as readDisclosureOpen, e as getBrowserStorage, w as writeDisclosureOpen, p as parseDashboardQuery, A as AUTO_REFRESH_INTERVAL_MS, f as pickFocusSessionId, h as encodeSearchQuery, j as shouldUseCompactTable, P as PAGE_SIZE_OPTIONS, k as DEFAULT_PAGE_SIZE, l as getExportDeviceInfo, m as getErrorStatus, n as hasActiveFilters } from "./dashboardModel-fApbKGay.mjs";
12
12
  const EndReason = ({ session, reason, variant = "omega", textColor = "neutral800" }) => {
13
13
  const { formatMessage } = useIntl();
14
14
  const key = reason || getSessionEndReason(session);
@@ -90,112 +90,6 @@ function readSessionStats(payload) {
90
90
  stats.nativeOnlyAfterTracking = isCount$1(data?.nativeOnlyAfterTracking) ? data.nativeOnlyAfterTracking : null;
91
91
  return stats;
92
92
  }
93
- const CSV_HEADERS = Object.freeze([
94
- "ID",
95
- "Status",
96
- "User Email",
97
- "Username",
98
- "Device",
99
- "Browser",
100
- "OS",
101
- "IP Address",
102
- "Login Time",
103
- "Last Active",
104
- "Logout Time",
105
- "Minutes Idle",
106
- "End Reason"
107
- ]);
108
- const FORMULA_START = /^[\s\u00ad\u200b-\u200f\u2060-\u2064\ufeff]*[=+\-@\uff1d\uff0b\uff0d\uff20\t\r\n]/;
109
- const escapeCsvValue = (value) => {
110
- const text = String(value ?? "");
111
- const safe = typeof value === "string" && FORMULA_START.test(text) ? `'${text}` : text;
112
- return `"${safe.replace(/"/g, '""')}"`;
113
- };
114
- function toIsoTimestamp(value) {
115
- if (value === null || value === void 0 || value === "") return "";
116
- const date = value instanceof Date ? value : new Date(
117
- /** @type {any} */
118
- value
119
- );
120
- return Number.isFinite(date.getTime()) ? date.toISOString() : "";
121
- }
122
- function buildSessionCsv(sessions, {
123
- unavailableValue,
124
- getDeviceInfo,
125
- getSessionStatus: getSessionStatus2,
126
- getSessionEndReason: getSessionEndReason$1 = getSessionEndReason
127
- }) {
128
- const rows = Array.isArray(sessions) ? sessions : [];
129
- const csvRows = rows.map((session) => {
130
- const deviceInfo = getDeviceInfo(session, unavailableValue);
131
- const minutesIdle = Number.isFinite(session.minutesSinceActive) ? session.minutesSinceActive : "";
132
- return [
133
- session.id,
134
- getSessionStatus2(session),
135
- session.user?.email || "",
136
- session.user?.username || "",
137
- deviceInfo.device,
138
- deviceInfo.browser,
139
- deviceInfo.os,
140
- session.ipAddress || unavailableValue,
141
- toIsoTimestamp(session.loginTime),
142
- toIsoTimestamp(session.lastActive || session.loginTime),
143
- toIsoTimestamp(session.logoutTime),
144
- minutesIdle,
145
- getSessionEndReason$1(session) || ""
146
- ];
147
- });
148
- return [
149
- CSV_HEADERS.map(escapeCsvValue).join(","),
150
- ...csvRows.map((row) => row.map(escapeCsvValue).join(","))
151
- ].join("\n");
152
- }
153
- function buildSessionJson(sessions, {
154
- filterStatus,
155
- totalSessions,
156
- exportedAt,
157
- unavailableValue,
158
- getDeviceInfo,
159
- getSessionStatus: getSessionStatus2,
160
- getSessionEndReason: getSessionEndReason$1 = getSessionEndReason,
161
- truncated = false
162
- }) {
163
- const rows = Array.isArray(sessions) ? sessions : [];
164
- const exportData = {
165
- exportedAt,
166
- filter: filterStatus,
167
- totalSessions,
168
- exportedSessions: rows.length,
169
- ...truncated ? { truncated: true } : {},
170
- sessions: rows.map((session) => {
171
- const deviceInfo = getDeviceInfo(session, unavailableValue);
172
- return {
173
- id: session.id,
174
- status: getSessionStatus2(session),
175
- endReason: getSessionEndReason$1(session) || null,
176
- user: {
177
- id: session.user?.documentId || session.user?.id,
178
- email: session.user?.email,
179
- username: session.user?.username
180
- },
181
- device: {
182
- type: deviceInfo.device,
183
- browser: deviceInfo.browser,
184
- browserVersion: deviceInfo.browserVersion,
185
- os: deviceInfo.os
186
- },
187
- ipAddress: session.ipAddress || unavailableValue,
188
- loginTime: session.loginTime,
189
- lastActive: session.lastActive,
190
- logoutTime: session.logoutTime,
191
- minutesSinceActive: session.minutesSinceActive,
192
- isActive: session.isActive,
193
- isTrulyActive: session.isTrulyActive
194
- };
195
- })
196
- };
197
- return JSON.stringify(exportData, null, 2);
198
- }
199
93
  const DS_BREAKPOINTS = Object.freeze({
200
94
  small: "@media(min-width: 520px)",
201
95
  medium: "@media(min-width: 768px)",
@@ -1670,2557 +1564,1235 @@ const UntrackedSessionsNotice = ({ stats, onChanged, fallbackFocusRef }) => {
1670
1564
  )
1671
1565
  ] });
1672
1566
  };
1673
- const CLOCK_TICK_MS = 30 * 1e3;
1674
- const ANALYTICS_PATH = `/settings/${pluginId}/analytics`;
1675
- const CONFIGURATION_PATH = `/settings/${pluginId}/general`;
1676
- const PaginationTargets$2 = styled.div`
1677
- nav a {
1678
- min-width: 3.2rem;
1679
- }
1680
-
1681
- & > div {
1682
- flex-wrap: wrap;
1683
- gap: ${({ theme }) => theme.spaces[2]} ${({ theme }) => theme.spaces[4]};
1684
- }
1685
-
1686
- & > div > div > span {
1687
- white-space: nowrap;
1688
- }
1689
- `;
1690
- const downloadFile = (content, type, extension) => {
1691
- const blob = new Blob([content], { type });
1692
- const url = URL.createObjectURL(blob);
1693
- const link = document.createElement("a");
1694
- link.href = url;
1695
- link.download = `sessions-export-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.${extension}`;
1696
- link.click();
1697
- window.setTimeout(() => URL.revokeObjectURL(url), 0);
1698
- };
1699
- const HomePage = () => {
1567
+ const ADMIN_ACTIVITY_SETTINGS_PATH = `/settings/${pluginId}/general?tab=admin-activity`;
1568
+ const ADMIN_ACTIVITY_PAGE_PATH = `/plugins/${pluginId}/admin-panel/activity`;
1569
+ const useT$3 = () => {
1700
1570
  const { formatMessage } = useIntl();
1701
- const { get, post, del } = useFetchClient();
1571
+ return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
1572
+ };
1573
+ const PeriodSelect = ({ value, onChange }) => {
1574
+ const t = useT$3();
1575
+ const labels = {
1576
+ 1: t("adminPanel.activity.period.day", "Last 24 hours"),
1577
+ 7: t("adminPanel.activity.period.week", "Last 7 days"),
1578
+ 30: t("adminPanel.activity.period.month", "Last 30 days"),
1579
+ 90: t("adminPanel.activity.period.quarter", "Last 90 days"),
1580
+ all: t("adminPanel.activity.period.all", "All kept events")
1581
+ };
1582
+ return /* @__PURE__ */ jsx(
1583
+ SingleSelect,
1584
+ {
1585
+ size: "S",
1586
+ "aria-label": t("adminPanel.activity.period.label", "Period"),
1587
+ value,
1588
+ onChange: (next) => onChange(String(next)),
1589
+ children: PERIOD_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: labels[option] }, option))
1590
+ }
1591
+ );
1592
+ };
1593
+ const FilterTag = ({ label, onRemove, children, ...rest }) => /* @__PURE__ */ jsxs(
1594
+ Flex,
1595
+ {
1596
+ gap: 1,
1597
+ alignItems: "center",
1598
+ background: "primary100",
1599
+ borderColor: "primary200",
1600
+ hasRadius: true,
1601
+ paddingLeft: 3,
1602
+ minWidth: 0,
1603
+ ...rest,
1604
+ children: [
1605
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", fontWeight: "semiBold", textColor: "primary700", children }),
1606
+ /* @__PURE__ */ jsx(IconButton, { label, variant: "ghost", size: "S", onClick: onRemove, children: /* @__PURE__ */ jsx(Cross, {}) })
1607
+ ]
1608
+ }
1609
+ );
1610
+ const FilterSlot = ({ children }) => /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", minWidth: 0, flex: "1 1 18rem", children });
1611
+ const EmptyText = ({ children }) => /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", "data-event-empty": "", children });
1612
+ const EventList = ({
1613
+ filters,
1614
+ notice,
1615
+ list,
1616
+ empty,
1617
+ renderList,
1618
+ toCsv,
1619
+ fileName,
1620
+ exportLabel,
1621
+ footer
1622
+ }) => {
1623
+ const t = useT$3();
1702
1624
  const { toggleNotification } = useNotification();
1703
- const formatters = useSessionFormatters();
1704
- const { isBelowSmall, isBelowMedium, isBelowLarge } = useBreakpoint();
1705
- const [listWidthRef, listWidth] = useElementWidth();
1706
- const [{ query }, setQuery] = useQueryParams();
1707
- const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
1708
- const dashboard = parseDashboardQuery(query);
1709
- const [sessions, setSessions] = useState([]);
1710
- const [pagination, setPagination] = useState({ total: 0, pageCount: 1 });
1711
- const [stats, setStats] = useState(EMPTY_SESSION_STATS);
1712
1625
  const [exporting, setExporting] = useState(false);
1713
- const [loading, setLoading] = useState(true);
1714
- const [refreshing, setRefreshing] = useState(false);
1715
- const [loadError, setLoadError] = useState(false);
1716
- const [hasData, setHasData] = useState(false);
1717
- const [lastUpdated, setLastUpdated] = useState(null);
1718
- const [now, setNow] = useState(() => Date.now());
1719
- const [selectedSession, setSelectedSession] = useState(null);
1720
- const [showDetailModal, setShowDetailModal] = useState(false);
1721
- const [terminatingSessionId, setTerminatingSessionId] = useState(null);
1722
- const [deletingSessionId, setDeletingSessionId] = useState(null);
1723
- const openerRef = useRef(null);
1724
- const dashboardRef = useRef(null);
1725
- const listHeadingRef = useRef(null);
1726
- const hasLoadedRef = useRef(false);
1727
- const requestIdRef = useRef(0);
1728
- const visibleIdsRef = useRef([]);
1729
- const mutationSnapshotRef = useRef([]);
1730
- const listHeadingId = `session-list-caption-${useId().replace(/:/g, "")}`;
1731
- const mutationPending = Boolean(terminatingSessionId || deletingSessionId);
1732
- const listQuery = useMemo(
1733
- () => ({
1734
- page: dashboard.page,
1735
- pageSize: dashboard.pageSize,
1736
- status: dashboard.status,
1737
- reason: dashboard.reason,
1738
- search: dashboard.search
1739
- }),
1740
- [dashboard.page, dashboard.pageSize, dashboard.status, dashboard.reason, dashboard.search]
1741
- );
1742
- useEffect(() => {
1743
- const timer = setInterval(() => setNow(Date.now()), CLOCK_TICK_MS);
1744
- return () => clearInterval(timer);
1745
- }, []);
1746
- const fetchSessions = useCallback(async () => {
1747
- const requestId = requestIdRef.current + 1;
1748
- requestIdRef.current = requestId;
1749
- if (hasLoadedRef.current) setRefreshing(true);
1750
- else setLoading(true);
1751
- try {
1752
- const [listResponse, statsResponse] = await Promise.all([
1753
- get(`/${pluginId}/sessions`, { params: buildListParams(listQuery) }),
1754
- get(`/${pluginId}/sessions/stats`)
1755
- ]);
1756
- const page = readSessionPage(listResponse.data);
1757
- const nextStats = readSessionStats(statsResponse.data);
1758
- if (requestId !== requestIdRef.current) return;
1759
- setSessions(page.rows);
1760
- setPagination(page.pagination);
1761
- setStats(nextStats);
1762
- setLoadError(false);
1763
- setHasData(true);
1764
- setLastUpdated(Date.now());
1765
- setNow(Date.now());
1766
- hasLoadedRef.current = true;
1767
- } catch (err) {
1768
- if (requestId !== requestIdRef.current || isCancelledRequest(err)) return;
1769
- setLoadError(true);
1770
- logSafeAdminError("dashboard.loadSessions", err);
1771
- } finally {
1772
- if (requestId === requestIdRef.current) {
1773
- setLoading(false);
1774
- setRefreshing(false);
1775
- }
1776
- }
1777
- }, [get, listQuery]);
1778
- useEffect(() => {
1779
- fetchSessions();
1780
- }, [fetchSessions]);
1781
- useEffect(() => {
1782
- if (showDetailModal || mutationPending) return void 0;
1783
- const interval = setInterval(() => {
1784
- fetchSessions();
1785
- }, AUTO_REFRESH_INTERVAL_MS);
1786
- return () => clearInterval(interval);
1787
- }, [showDetailModal, mutationPending, fetchSessions]);
1788
- const handleTerminateSession = async (session) => {
1789
- if (terminatingSessionId || deletingSessionId) return;
1790
- const sessionId = session.id;
1791
- mutationSnapshotRef.current = visibleIdsRef.current;
1792
- setTerminatingSessionId(sessionId);
1626
+ const total = list.meta?.pagination?.total ?? 0;
1627
+ const handleExport = async () => {
1628
+ if (exporting) return;
1629
+ setExporting(true);
1793
1630
  try {
1794
- await post(`/${pluginId}/sessions/${sessionId}/terminate`);
1795
- await fetchSessions();
1796
- toggleNotification({
1797
- type: "success",
1798
- message: t("notifications.success.sessionEnded", "Session ended.")
1799
- });
1800
- } catch (err) {
1801
- logSafeAdminError("dashboard.terminateSession", err);
1802
- if (getErrorStatus(err) === 404) {
1803
- await fetchSessions();
1631
+ const { rows, capped } = await list.exportAll();
1632
+ downloadCsv(toCsv(rows), fileName);
1633
+ if (capped) {
1804
1634
  toggleNotification({
1805
1635
  type: "warning",
1806
1636
  message: t(
1807
- "notifications.error.sessionGone",
1808
- "This session no longer exists. The list was refreshed."
1637
+ "adminPanel.activity.export.capped",
1638
+ "The export contains the newest {limit, number} events. Narrow the filter to export the rest.",
1639
+ { limit: MAX_EVENT_EXPORT_ROWS }
1809
1640
  )
1810
1641
  });
1811
- return;
1812
1642
  }
1813
- toggleNotification({
1814
- type: "danger",
1815
- message: t(
1816
- "notifications.error.endSession",
1817
- "The session could not be ended. Please try again."
1818
- )
1819
- });
1820
- throw err;
1821
- } finally {
1822
- setTerminatingSessionId(null);
1823
- }
1824
- };
1825
- const handleDeleteSession = async (session) => {
1826
- if (terminatingSessionId || deletingSessionId) return;
1827
- const sessionId = session.id;
1828
- mutationSnapshotRef.current = visibleIdsRef.current;
1829
- setDeletingSessionId(sessionId);
1830
- try {
1831
- await del(`/${pluginId}/sessions/${sessionId}`);
1832
- await fetchSessions();
1833
- toggleNotification({
1834
- type: "success",
1835
- message: t(
1836
- "notifications.success.recordDeleted",
1837
- "Session record deleted. Its token stays revoked."
1838
- )
1839
- });
1840
1643
  } catch (err) {
1841
- logSafeAdminError("dashboard.deleteSession", err);
1842
- if (getErrorStatus(err) === 404) {
1843
- await fetchSessions();
1844
- toggleNotification({
1845
- type: "warning",
1846
- message: t(
1847
- "notifications.error.sessionGone",
1848
- "This session no longer exists. The list was refreshed."
1849
- )
1850
- });
1851
- return;
1852
- }
1644
+ if (isCancelledRequest(err)) return;
1645
+ logSafeAdminError("adminPanel.activity.export", err);
1853
1646
  toggleNotification({
1854
1647
  type: "danger",
1855
- message: t(
1856
- "notifications.error.deleteRecord",
1857
- "The record could not be deleted. Please try again."
1858
- )
1648
+ message: t("adminPanel.activity.export.error", "The export could not be created.")
1859
1649
  });
1860
- throw err;
1861
1650
  } finally {
1862
- setDeletingSessionId(null);
1651
+ setExporting(false);
1863
1652
  }
1864
1653
  };
1865
- const pageSize = Number(dashboard.pageSize);
1866
- const pageResult = {
1867
- items: sessions,
1868
- total: pagination.total,
1869
- pageCount: pagination.pageCount,
1870
- startIndex: pagination.total > 0 ? (dashboard.page - 1) * pageSize + 1 : 0,
1871
- endIndex: pagination.total > 0 ? (dashboard.page - 1) * pageSize + sessions.length : 0
1872
- };
1873
- const visibleIds = pageResult.items.map((session) => String(session.id));
1874
- useLayoutEffect(() => {
1875
- visibleIdsRef.current = visibleIds;
1876
- });
1877
- const fetchExportRows = async () => {
1878
- const rows = [];
1879
- let cursor = null;
1880
- do {
1881
- const { data } = await get(`/${pluginId}/sessions/export`, {
1882
- params: buildExportParams(listQuery, cursor)
1883
- });
1884
- rows.push(...requireSessionList(data));
1885
- cursor = typeof data?.meta?.nextCursor === "string" ? data.meta.nextCursor : null;
1886
- } while (cursor && rows.length < MAX_EXPORT_ROWS);
1887
- const capped = rows.length > MAX_EXPORT_ROWS || Boolean(cursor) && rows.length >= MAX_EXPORT_ROWS;
1888
- return { rows: rows.slice(0, MAX_EXPORT_ROWS), capped };
1889
- };
1890
- const handleExport = async (format) => {
1891
- if (exporting) return;
1892
- setExporting(true);
1893
- try {
1894
- const { rows, capped } = await fetchExportRows();
1895
- if (format === "csv") {
1896
- const csvContent = buildSessionCsv(rows, {
1897
- unavailableValue: "",
1898
- getDeviceInfo: getExportDeviceInfo,
1899
- getSessionStatus
1900
- });
1901
- downloadFile(csvContent, "text/csv;charset=utf-8;", "csv");
1902
- } else {
1903
- const jsonContent = buildSessionJson(rows, {
1904
- filterStatus: dashboard.status,
1905
- totalSessions: stats.total,
1906
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1907
- unavailableValue: "",
1908
- getDeviceInfo: getExportDeviceInfo,
1909
- getSessionStatus,
1910
- truncated: capped
1911
- });
1912
- downloadFile(jsonContent, "application/json", "json");
1913
- }
1914
- if (capped) {
1915
- toggleNotification({
1916
- type: "warning",
1917
- message: t(
1918
- "homepage.export.capped",
1919
- "The export contains the newest {limit, number} sessions. Narrow the filter to export the rest.",
1920
- { limit: MAX_EXPORT_ROWS }
1921
- )
1922
- });
1923
- }
1924
- } catch (err) {
1925
- if (isCancelledRequest(err)) return;
1926
- logSafeAdminError(format === "csv" ? "dashboard.exportCsv" : "dashboard.exportJson", err);
1927
- toggleNotification({
1928
- type: "danger",
1929
- message: t("notifications.error.exportFailed", "The export could not be created.")
1930
- });
1931
- } finally {
1932
- setExporting(false);
1933
- }
1934
- };
1935
- const handleSessionClick = (session, opener) => {
1936
- openerRef.current = opener;
1937
- setSelectedSession(session);
1938
- setShowDetailModal(true);
1939
- };
1940
- const handleModalClose = () => {
1941
- setShowDetailModal(false);
1942
- setSelectedSession(null);
1943
- };
1944
- const handleCloseAutoFocus = (event) => {
1945
- restoreDialogFocus(event, openerRef.current, listHeadingRef.current || dashboardRef.current);
1946
- };
1947
- const getFocusFallback = useCallback(
1948
- (sessionId) => ({
1949
- get current() {
1950
- const targetId = pickFocusSessionId(
1951
- mutationSnapshotRef.current,
1952
- visibleIdsRef.current,
1953
- sessionId
1954
- );
1955
- const root = dashboardRef.current;
1956
- if (targetId && root) {
1957
- const escaped = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(targetId) : targetId;
1958
- const button = root.querySelector(`[data-session-view="${escaped}"]`);
1959
- if (button) return button;
1654
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, minWidth: 0, children: [
1655
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", alignItems: "center", justifyContent: "space-between", children: [
1656
+ /* @__PURE__ */ jsx(Flex, { gap: 2, wrap: "wrap", alignItems: "center", flex: "1 1 auto", minWidth: 0, children: filters }),
1657
+ /* @__PURE__ */ jsx(
1658
+ Button,
1659
+ {
1660
+ size: "S",
1661
+ variant: "tertiary",
1662
+ startIcon: /* @__PURE__ */ jsx(Download, {}),
1663
+ onClick: handleExport,
1664
+ loading: exporting,
1665
+ disabled: list.loading || total === 0,
1666
+ "aria-label": exportLabel,
1667
+ children: t("adminPanel.activity.export.csv", "Export CSV")
1960
1668
  }
1961
- return listHeadingRef.current;
1669
+ )
1670
+ ] }),
1671
+ notice,
1672
+ list.loading ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 4, children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("adminPanel.activity.loading", "Loading events") }) }) : null,
1673
+ !list.loading && list.error ? /* @__PURE__ */ jsx(
1674
+ PersistentAlert,
1675
+ {
1676
+ variant: "danger",
1677
+ action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: list.reload, children: t("common.tryAgain", "Try again") }),
1678
+ children: t("adminPanel.activity.error", "The events could not be loaded.")
1962
1679
  }
1963
- }),
1964
- []
1965
- );
1966
- useEffect(() => {
1967
- if (!loading && !refreshing && dashboard.page > pageResult.pageCount) {
1968
- setQuery({ page: String(pageResult.pageCount) }, "push", true);
1680
+ ) : null,
1681
+ !list.loading && !list.error && list.rows.length === 0 ? empty : null,
1682
+ list.rows.length > 0 ? renderList(list.rows) : null,
1683
+ footer !== void 0 ? list.rows.length > 0 ? footer : null : list.hasMore ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", children: /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: list.loadMore, loading: list.loadingMore, children: t("adminPanel.activity.showMore", "Show more") }) }) : null
1684
+ ] });
1685
+ };
1686
+ const RecordingOff = ({ children, to = ADMIN_ACTIVITY_SETTINGS_PATH }) => {
1687
+ const t = useT$3();
1688
+ return /* @__PURE__ */ jsx(
1689
+ PersistentAlert,
1690
+ {
1691
+ variant: "neutral",
1692
+ action: /* @__PURE__ */ jsx(Link, { tag: Link$1, to, children: t("adminPanel.activity.openSettings", "Open settings") }),
1693
+ children
1969
1694
  }
1970
- }, [loading, refreshing, dashboard.page, pageResult.pageCount, setQuery]);
1971
- const handleStatusChange = (value) => {
1972
- const status = String(value);
1973
- setQuery({ status: status === "all" ? void 0 : status, reason: void 0, page: "1" });
1974
- };
1975
- const handleReasonChange = (value) => {
1976
- const reason = String(value);
1977
- setQuery({ reason: reason === "all" ? void 0 : reason, page: "1" });
1978
- };
1979
- const handleSearch = useCallback(
1980
- (value) => {
1981
- setQuery({ search: encodeSearchQuery(value), _q: void 0, page: "1" }, "push", true);
1982
- },
1983
- [setQuery]
1984
1695
  );
1985
- const handleClearFilters = () => {
1986
- setQuery({ search: void 0, _q: void 0, status: void 0, reason: void 0, page: "1" });
1987
- listHeadingRef.current?.focus();
1696
+ };
1697
+ const SignInHistoryPanel = ({ admin }) => {
1698
+ const t = useT$3();
1699
+ const [event, setEvent] = useState("all");
1700
+ const [period, setPeriod] = useState("30");
1701
+ const params = useMemo(
1702
+ () => buildSignInParams({ adminId: admin.id, event, period }),
1703
+ [admin.id, event, period]
1704
+ );
1705
+ const list = useEventList({
1706
+ path: `/${pluginId}/admin-activity/sign-ins`,
1707
+ params,
1708
+ logKey: "adminPanel.activity.signIns"
1709
+ });
1710
+ const recording = list.meta?.recording;
1711
+ const labels = {
1712
+ all: t("adminPanel.activity.filter.allEvents", "All events"),
1713
+ succeeded: t("adminPanel.activity.filter.succeeded", "Sign-ins"),
1714
+ failed: t("adminPanel.activity.filter.failed", "Failed and locked out"),
1715
+ "signed-out": t("adminPanel.activity.filter.signedOut", "Sign-outs")
1988
1716
  };
1989
- const showSessionData = !loading && hasData;
1990
- const showToolbar = showSessionData && stats.total > 0;
1991
- const canExport = showSessionData && pageResult.total > 0 && !exporting;
1992
- const filtersActive = hasActiveFilters(dashboard);
1993
- const exportValues = { count: Math.min(pageResult.total, MAX_EXPORT_ROWS) };
1994
- const exportMenu = /* @__PURE__ */ jsxs(
1995
- SimpleMenu,
1717
+ return /* @__PURE__ */ jsx(
1718
+ EventList,
1996
1719
  {
1997
- label: t("homepage.export.label", "Export"),
1998
- variant: "secondary",
1999
- startIcon: /* @__PURE__ */ jsx(Download, {}),
2000
- disabled: !canExport,
2001
- children: [
2002
- /* @__PURE__ */ jsx(MenuItem, { onSelect: () => void handleExport("csv"), children: t(
2003
- "homepage.export.csv",
2004
- "{count, plural, one {Export # session as CSV} other {Export # sessions as CSV}}",
2005
- exportValues
1720
+ list,
1721
+ filters: /* @__PURE__ */ jsxs(Fragment, { children: [
1722
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
1723
+ SingleSelect,
1724
+ {
1725
+ size: "S",
1726
+ "aria-label": t("adminPanel.activity.filter.event", "Event"),
1727
+ value: event,
1728
+ onChange: (next) => setEvent(String(next)),
1729
+ children: SIGN_IN_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: labels[option] }, option))
1730
+ }
2006
1731
  ) }),
2007
- /* @__PURE__ */ jsx(MenuItem, { onSelect: () => void handleExport("json"), children: t(
2008
- "homepage.export.json",
2009
- "{count, plural, one {Export # session as JSON} other {Export # sessions as JSON}}",
2010
- exportValues
2011
- ) })
2012
- ]
1732
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(PeriodSelect, { value: period, onChange: setPeriod }) })
1733
+ ] }),
1734
+ notice: recording && !recording.signIns ? /* @__PURE__ */ jsx(RecordingOff, { children: t(
1735
+ "adminPanel.activity.signIns.off",
1736
+ "Sign-in history is turned off. New sign-ins are not recorded."
1737
+ ) }) : null,
1738
+ empty: /* @__PURE__ */ jsx(EmptyText, { children: t("adminPanel.activity.signIns.empty", "No sign-in events in this period.") }),
1739
+ renderList: (rows) => /* @__PURE__ */ jsx(
1740
+ SignInEventTable,
1741
+ {
1742
+ rows,
1743
+ busy: list.loading,
1744
+ label: t("adminPanel.activity.signIns.listLabel", "Sign-in history of {name}", {
1745
+ name: admin.name
1746
+ })
1747
+ }
1748
+ ),
1749
+ toCsv: buildSignInCsv,
1750
+ fileName: "admin-sign-in-history",
1751
+ exportLabel: t(
1752
+ "adminPanel.activity.signIns.export",
1753
+ "Export the sign-in history of {name} as CSV",
1754
+ {
1755
+ name: admin.name
1756
+ }
1757
+ )
2013
1758
  }
2014
1759
  );
2015
- const exportAction = canExport || !showSessionData ? exportMenu : /* @__PURE__ */ jsx(Tooltip, { label: t("homepage.export.disabledHint", "No sessions match the current filter."), children: /* @__PURE__ */ jsx("span", { children: exportMenu }) });
2016
- const analyticsLabel = t("homepage.links.analytics", "Analytics");
2017
- const settingsLabel = t("homepage.links.settings", "Settings");
2018
- const primaryAction = /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", justifyContent: "flex-end", children: [
2019
- isBelowSmall ? /* @__PURE__ */ jsx(IconButton, { tag: Link$1, to: ANALYTICS_PATH, label: analyticsLabel, variant: "tertiary", children: /* @__PURE__ */ jsx(ChartBubble, {}) }) : /* @__PURE__ */ jsx(
2020
- LinkButton,
2021
- {
2022
- tag: Link$1,
2023
- to: ANALYTICS_PATH,
2024
- variant: "tertiary",
2025
- size: "S",
2026
- startIcon: /* @__PURE__ */ jsx(ChartBubble, {}),
2027
- children: analyticsLabel
2028
- }
2029
- ),
2030
- isBelowSmall ? /* @__PURE__ */ jsx(IconButton, { tag: Link$1, to: CONFIGURATION_PATH, label: settingsLabel, variant: "tertiary", children: /* @__PURE__ */ jsx(Cog, {}) }) : /* @__PURE__ */ jsx(
2031
- LinkButton,
2032
- {
2033
- tag: Link$1,
2034
- to: CONFIGURATION_PATH,
2035
- variant: "tertiary",
2036
- size: "S",
2037
- startIcon: /* @__PURE__ */ jsx(Cog, {}),
2038
- children: settingsLabel
2039
- }
2040
- ),
2041
- exportAction
2042
- ] });
2043
- const filterSlot = isBelowMedium ? { flex: "1 1 auto", minWidth: 0 } : void 0;
2044
- const filterControls = /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", wrap: isBelowMedium ? "nowrap" : "wrap", shrink: 0, children: [
2045
- /* @__PURE__ */ jsx(Box, { ...filterSlot, children: /* @__PURE__ */ jsx(
2046
- SingleSelect,
2047
- {
2048
- size: "S",
2049
- "aria-label": t("homepage.filter.label", "Status"),
2050
- value: dashboard.status,
2051
- onChange: handleStatusChange,
2052
- children: SESSION_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsxs(SingleSelectOption, { value: option, children: [
2053
- option === "all" && t("homepage.filter.all", "All sessions"),
2054
- option === "open" && t("homepage.filter.open", "Open"),
2055
- option !== "all" && option !== "open" && formatters.statusLabel(option)
2056
- ] }, option))
2057
- }
2058
- ) }),
2059
- dashboard.status === "ended" ? /* @__PURE__ */ jsx(Box, { ...filterSlot, children: /* @__PURE__ */ jsx(
2060
- SingleSelect,
2061
- {
2062
- size: "S",
2063
- "aria-label": t("homepage.filter.reasonLabel", "End reason"),
2064
- value: dashboard.reason,
2065
- onChange: handleReasonChange,
2066
- children: END_REASON_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: option === "all" ? t("homepage.filter.allReasons", "All reasons") : formatters.endReasonLabel(option) }, option))
2067
- }
2068
- ) }) : null,
2069
- /* @__PURE__ */ jsx(
2070
- IconButton,
2071
- {
2072
- label: t("homepage.actions.refresh", "Refresh sessions"),
2073
- onClick: () => fetchSessions(),
2074
- children: /* @__PURE__ */ jsx(ArrowClockwise, {})
2075
- }
2076
- )
2077
- ] });
2078
- const toolbar = /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-session-toolbar": "", children: /* @__PURE__ */ jsxs(
1760
+ };
1761
+ const ContentActivityPanel = ({ admin }) => {
1762
+ const t = useT$3();
1763
+ const [action, setAction] = useState("all");
1764
+ const [contentType, setContentType] = useState("all");
1765
+ const [period, setPeriod] = useState("30");
1766
+ const params = useMemo(
1767
+ () => buildActivityParams({ adminId: admin.id, action, contentType, period }),
1768
+ [admin.id, action, contentType, period]
1769
+ );
1770
+ const list = useEventList({
1771
+ path: `/${pluginId}/admin-activity/content`,
1772
+ params,
1773
+ logKey: "adminPanel.activity.content"
1774
+ });
1775
+ const recording = list.meta?.recording;
1776
+ const types = Array.isArray(list.meta?.contentTypes) ? list.meta.contentTypes : [];
1777
+ const noAccess = list.meta?.contentManagerAccess === false;
1778
+ let notice = null;
1779
+ if (recording && !recording.contentActivity) {
1780
+ notice = /* @__PURE__ */ jsx(RecordingOff, { children: t(
1781
+ "adminPanel.activity.content.off",
1782
+ "Content Manager activity is not recorded. An admin can turn it on in the settings; inform your team first."
1783
+ ) });
1784
+ } else if (noAccess) {
1785
+ notice = /* @__PURE__ */ jsx(PersistentAlert, { variant: "neutral", children: t(
1786
+ "adminPanel.activity.content.noAccess",
1787
+ "{name} has no Content Manager access, so there is no activity to show.",
1788
+ { name: admin.name }
1789
+ ) });
1790
+ }
1791
+ return /* @__PURE__ */ jsx(
1792
+ EventList,
1793
+ {
1794
+ list,
1795
+ filters: /* @__PURE__ */ jsxs(Fragment, { children: [
1796
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
1797
+ SingleSelect,
1798
+ {
1799
+ size: "S",
1800
+ "aria-label": t("adminPanel.activity.filter.action", "Action"),
1801
+ value: action,
1802
+ onChange: (next) => setAction(String(next)),
1803
+ children: ACTIVITY_ACTION_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: t(
1804
+ ACTIVITY_ACTION_LABELS[option].messageId,
1805
+ ACTIVITY_ACTION_LABELS[option].defaultMessage
1806
+ ) }, option))
1807
+ }
1808
+ ) }),
1809
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsxs(
1810
+ SingleSelect,
1811
+ {
1812
+ size: "S",
1813
+ "aria-label": t("adminPanel.activity.filter.contentType", "Content type"),
1814
+ value: contentType,
1815
+ onChange: (next) => setContentType(String(next)),
1816
+ children: [
1817
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "all", children: t("adminPanel.activity.filter.allTypes", "All content types") }),
1818
+ types.map((type) => /* @__PURE__ */ jsx(SingleSelectOption, { value: type.uid, children: type.name }, type.uid))
1819
+ ]
1820
+ }
1821
+ ) }),
1822
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(PeriodSelect, { value: period, onChange: setPeriod }) })
1823
+ ] }),
1824
+ notice,
1825
+ empty: /* @__PURE__ */ jsx(EmptyText, { children: t("adminPanel.activity.content.empty", "No Content Manager activity in this period.") }),
1826
+ renderList: (rows) => /* @__PURE__ */ jsx(
1827
+ ActivityEventTable,
1828
+ {
1829
+ rows,
1830
+ busy: list.loading,
1831
+ label: t("adminPanel.activity.content.listLabel", "Content Manager activity of {name}", {
1832
+ name: admin.name
1833
+ })
1834
+ }
1835
+ ),
1836
+ toCsv: buildActivityCsv,
1837
+ fileName: "admin-content-activity",
1838
+ exportLabel: t(
1839
+ "adminPanel.activity.content.export",
1840
+ "Export the Content Manager activity of {name} as CSV",
1841
+ { name: admin.name }
1842
+ )
1843
+ }
1844
+ );
1845
+ };
1846
+ const RecentEvents = ({
1847
+ title,
1848
+ subtitle,
1849
+ showAllTo,
1850
+ emptyText,
1851
+ list,
1852
+ renderTable,
1853
+ dataKey
1854
+ }) => {
1855
+ const t = useT$3();
1856
+ const headingId = `recent-events-${useId().replace(/:/g, "")}`;
1857
+ return /* @__PURE__ */ jsxs(
2079
1858
  Flex,
2080
1859
  {
2081
- direction: { initial: "column", medium: "row" },
2082
- alignItems: { initial: "stretch", medium: "center" },
2083
- gap: 2,
1860
+ tag: "section",
1861
+ "aria-labelledby": headingId,
1862
+ direction: "column",
1863
+ alignItems: "stretch",
1864
+ gap: 4,
1865
+ minWidth: 0,
1866
+ ...{ [`data-${dataKey}`]: "" },
2084
1867
  children: [
2085
- /* @__PURE__ */ jsx(Flex, { flex: "1 1 auto", minWidth: 0, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsx(SessionSearch, { value: dashboard.search, onSearch: handleSearch }) }),
2086
- filterControls
1868
+ /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "flex-end", gap: 4, wrap: "wrap", children: [
1869
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, flex: "1 1 32rem", children: [
1870
+ /* @__PURE__ */ jsx(Typography, { id: headingId, variant: "delta", tag: "h2", textColor: "neutral800", children: title }),
1871
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: subtitle })
1872
+ ] }),
1873
+ /* @__PURE__ */ jsx(
1874
+ LinkButton,
1875
+ {
1876
+ tag: Link$1,
1877
+ to: showAllTo,
1878
+ variant: "tertiary",
1879
+ endIcon: /* @__PURE__ */ jsx(ArrowRight, {}),
1880
+ "data-show-all-activity": "",
1881
+ children: t("adminPanel.activity.recent.showAll", "Show all")
1882
+ }
1883
+ )
1884
+ ] }),
1885
+ list.loading && list.rows.length === 0 ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 2, children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("adminPanel.activity.loading", "Loading events") }) }) : null,
1886
+ !list.loading && list.error ? /* @__PURE__ */ jsx(
1887
+ PersistentAlert,
1888
+ {
1889
+ variant: "danger",
1890
+ action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: list.reload, children: t("common.tryAgain", "Try again") }),
1891
+ children: t("adminPanel.activity.error", "The events could not be loaded.")
1892
+ }
1893
+ ) : null,
1894
+ !list.loading && !list.error && list.rows.length === 0 ? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", "data-event-empty": "", children: emptyText }) : null,
1895
+ list.rows.length > 0 ? renderTable(title) : null
2087
1896
  ]
2088
1897
  }
2089
- ) });
2090
- const lastUpdatedLine = lastUpdated ? /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", wrap: "wrap", justifyContent: "flex-end", children: [
2091
- refreshing ? /* @__PURE__ */ jsx(Loader, { small: true, role: "status", "aria-live": "polite", children: t("homepage.refreshing", "Updating sessions") }) : null,
2092
- /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", "data-last-updated": "", children: t("homepage.lastUpdated", "Last updated {time}", {
2093
- time: formatters.formatRelativeTime(lastUpdated, now)
2094
- }) })
2095
- ] }) : null;
2096
- const listProps = {
2097
- sessions: pageResult.items,
2098
- labelledBy: listHeadingId,
2099
- busy: refreshing,
2100
- onView: handleSessionClick,
2101
- onEnd: handleTerminateSession,
2102
- onDelete: handleDeleteSession,
2103
- mutationPending,
2104
- getFocusFallback
2105
- };
2106
- const statusCard = (status) => ({
2107
- onClick: () => handleStatusChange(status),
2108
- pressed: dashboard.status === status
1898
+ );
1899
+ };
1900
+ const RecentSignInActivity = ({ onOpenAdmin }) => {
1901
+ const t = useT$3();
1902
+ const params = useMemo(() => buildSignInParams({ pageSize: RECENT_EVENT_LIMIT }), []);
1903
+ const list = useEventList({
1904
+ path: `/${pluginId}/admin-activity/sign-ins`,
1905
+ params,
1906
+ logKey: "adminPanel.activity.recent"
2109
1907
  });
1908
+ if (list.meta?.recording && !list.meta.recording.signIns) return null;
2110
1909
  return /* @__PURE__ */ jsx(
2111
- PageShell,
1910
+ RecentEvents,
2112
1911
  {
2113
- headingId: "magic-sessionmanager-dashboard-title",
2114
- title: t("homepage.title", "Sessions"),
1912
+ title: t("adminPanel.activity.recent.title", "Recent security activity"),
2115
1913
  subtitle: t(
2116
- "homepage.subtitle",
2117
- "Sign-ins of your app’s users (Users & Permissions). Strapi administrators are not listed."
1914
+ "adminPanel.activity.recent.subtitle",
1915
+ "The latest sign-ins, failed attempts, sign-outs and settings changes of all admins. Select an event for its details."
2118
1916
  ),
2119
- primaryAction,
2120
- children: /* @__PURE__ */ jsxs(
2121
- Flex,
1917
+ showAllTo: ADMIN_ACTIVITY_PAGE_PATH,
1918
+ emptyText: t("adminPanel.activity.recent.empty", "No events recorded yet."),
1919
+ list,
1920
+ dataKey: "recent-activity",
1921
+ renderTable: (title) => /* @__PURE__ */ jsx(
1922
+ SignInEventTable,
2122
1923
  {
2123
- ref: dashboardRef,
2124
- tabIndex: -1,
2125
- direction: "column",
2126
- alignItems: "stretch",
2127
- gap: 6,
2128
- minWidth: 0,
2129
- children: [
2130
- /* @__PURE__ */ jsx(SessionViewNav, { current: "users" }),
2131
- !loading && loadError ? /* @__PURE__ */ jsx(
2132
- PersistentAlert,
2133
- {
2134
- variant: "danger",
2135
- closeLabel: t("common.close", "Close"),
2136
- action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: fetchSessions, children: t("common.tryAgain", "Try again") }),
2137
- children: /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "span", children: t("homepage.error.load", "Sessions could not be loaded.") })
2138
- }
2139
- ) : null,
2140
- showSessionData && stats.nativeOnly > 0 ? /* @__PURE__ */ jsx(
2141
- UntrackedSessionsNotice,
2142
- {
2143
- stats,
2144
- onChanged: fetchSessions,
2145
- fallbackFocusRef: dashboardRef
2146
- }
2147
- ) : null,
2148
- loading ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 8, children: /* @__PURE__ */ jsx(Loader, { children: t("homepage.loading", "Loading sessions") }) }) : null,
2149
- showSessionData && stats.total > 0 ? /* @__PURE__ */ jsx(HowSessionsWork, {}) : null,
2150
- showSessionData && /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
2151
- /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx(Typography, { tag: "h2", children: t("homepage.stats.label", "Session statistics") }) }),
2152
- /* @__PURE__ */ jsxs(StatGrid, { label: t("homepage.stats.label", "Session statistics"), children: [
2153
- /* @__PURE__ */ jsx(
2154
- StatCard,
2155
- {
2156
- icon: Check,
2157
- tone: "success",
2158
- label: t("homepage.stats.active", "Active sessions"),
2159
- value: stats.active,
2160
- description: t(
2161
- "homepage.stats.usersOnline",
2162
- "{count, plural, one {# user online} other {# users online}}",
2163
- {
2164
- count: stats.usersOnline
2165
- }
2166
- ),
2167
- ...statusCard("active")
2168
- }
2169
- ),
2170
- /* @__PURE__ */ jsx(
2171
- StatCard,
2172
- {
2173
- icon: Clock,
2174
- tone: "warning",
2175
- label: t("homepage.stats.idle", "Idle sessions"),
2176
- value: stats.idle,
2177
- ...statusCard("idle")
2178
- }
2179
- ),
2180
- /* @__PURE__ */ jsx(
2181
- StatCard,
2182
- {
2183
- icon: Cross,
2184
- tone: "neutral",
2185
- label: t("homepage.stats.ended", "Ended sessions"),
2186
- value: stats.ended,
2187
- description: t(
2188
- "homepage.stats.endedBreakdown",
2189
- "{loggedOut, number} logged out · {timedOut, number} timed out · {other, number} other reasons",
2190
- {
2191
- loggedOut: stats.loggedOut,
2192
- timedOut: stats.timedOut,
2193
- other: stats.otherReasons
2194
- }
2195
- ),
2196
- ...statusCard("ended")
2197
- }
2198
- ),
2199
- /* @__PURE__ */ jsx(
2200
- StatCard,
2201
- {
2202
- icon: User,
2203
- tone: "primary",
2204
- label: t("homepage.stats.total", "All sessions"),
2205
- value: stats.total,
2206
- ...statusCard("all")
2207
- }
2208
- )
2209
- ] })
2210
- ] }),
2211
- showToolbar && /* @__PURE__ */ jsxs(Flex, { ref: listWidthRef, direction: "column", alignItems: "stretch", gap: 4, minWidth: 0, children: [
2212
- /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx(Typography, { variant: "delta", tag: "h2", children: t("homepage.list.heading", "Session list") }) }),
2213
- toolbar,
2214
- /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", gap: 4, wrap: "wrap", children: [
2215
- /* @__PURE__ */ jsx(
2216
- Typography,
2217
- {
2218
- id: listHeadingId,
2219
- ref: listHeadingRef,
2220
- tabIndex: -1,
2221
- variant: "pi",
2222
- textColor: "neutral600",
2223
- "aria-live": "polite",
2224
- "data-session-caption": "",
2225
- children: pageResult.total > 0 ? t(
2226
- "homepage.caption",
2227
- "{from, number}–{to, number} of {total, plural, one {# session} other {# sessions}}",
2228
- {
2229
- from: pageResult.startIndex,
2230
- to: pageResult.endIndex,
2231
- total: pageResult.total
2232
- }
2233
- ) : t("homepage.captionNone", "0 sessions")
2234
- }
2235
- ),
2236
- lastUpdatedLine
2237
- ] }),
2238
- pageResult.total > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
2239
- isBelowMedium ? /* @__PURE__ */ jsx(SessionCardList, { ...listProps }) : /* @__PURE__ */ jsx(
2240
- SessionTable,
2241
- {
2242
- ...listProps,
2243
- compact: shouldUseCompactTable(listWidth, isBelowLarge)
2244
- }
2245
- ),
2246
- /* @__PURE__ */ jsx(PaginationTargets$2, { children: /* @__PURE__ */ jsxs(
2247
- Pagination.Root,
2248
- {
2249
- pageCount: pageResult.pageCount,
2250
- total: pageResult.total,
2251
- defaultPageSize: Number(DEFAULT_PAGE_SIZE),
2252
- children: [
2253
- /* @__PURE__ */ jsx(Pagination.PageSize, { options: [...PAGE_SIZE_OPTIONS] }),
2254
- /* @__PURE__ */ jsx(Pagination.Links, {})
2255
- ]
2256
- }
2257
- ) })
2258
- ] }) : /* @__PURE__ */ jsx(
2259
- EmptyStateLayout,
2260
- {
2261
- icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem", "aria-hidden": "true" }),
2262
- content: t(
2263
- "homepage.noResults.description",
2264
- "No sessions match your search or filter."
2265
- ),
2266
- action: filtersActive ? /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: handleClearFilters, children: t("homepage.noResults.reset", "Clear filters") }) : null
2267
- }
2268
- )
2269
- ] }),
2270
- showSessionData && stats.total === 0 && /* @__PURE__ */ jsx(
2271
- EmptyStateLayout,
2272
- {
2273
- icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem", "aria-hidden": "true" }),
2274
- content: t(
2275
- "homepage.empty.description",
2276
- "No sessions yet. Sessions appear here when users of your app sign in."
2277
- )
2278
- }
2279
- ),
2280
- showDetailModal && selectedSession && /* @__PURE__ */ jsx(
2281
- SessionDetailModal,
2282
- {
2283
- session: selectedSession,
2284
- now,
2285
- onClose: handleModalClose,
2286
- onCloseAutoFocus: handleCloseAutoFocus,
2287
- onEndSession: handleTerminateSession
2288
- }
2289
- )
2290
- ]
1924
+ rows: list.rows,
1925
+ label: title,
1926
+ showAdmin: true,
1927
+ onOpenAdmin,
1928
+ busy: list.loading
2291
1929
  }
2292
1930
  )
2293
1931
  }
2294
1932
  );
2295
1933
  };
2296
- const ADMIN_FILTER_OPTIONS = Object.freeze(["all", "signed-in", "not-signed-in"]);
2297
- const ADMIN_PAGE_SIZE_OPTIONS = Object.freeze(["10", "25", "50", "100"]);
2298
- const ADMIN_DEFAULT_PAGE_SIZE = "25";
2299
- const ADMIN_MAX_SEARCH_LENGTH = 100;
2300
- function parseAdminPanelQuery(query = {}) {
2301
- const page = Number.parseInt(String(query?.page ?? ""), 10);
2302
- const pageSize = String(query?.pageSize ?? "");
2303
- const filter = String(query?.filter ?? "");
2304
- let search = "";
2305
- if (typeof query?.search === "string") {
2306
- try {
2307
- search = decodeURIComponent(query.search).trim();
2308
- } catch {
2309
- search = query.search.trim();
2310
- }
2311
- }
2312
- return {
2313
- page: Number.isInteger(page) && page >= 1 && page <= 1e6 ? page : 1,
2314
- pageSize: Number(
2315
- ADMIN_PAGE_SIZE_OPTIONS.includes(pageSize) ? pageSize : ADMIN_DEFAULT_PAGE_SIZE
2316
- ),
2317
- filter: ADMIN_FILTER_OPTIONS.includes(filter) ? filter : "all",
2318
- search: search.slice(0, ADMIN_MAX_SEARCH_LENGTH)
2319
- };
2320
- }
2321
- function buildAdminListParams(state) {
2322
- return {
2323
- page: state.page,
2324
- pageSize: state.pageSize,
2325
- filter: state.filter,
2326
- ...state.search ? { search: state.search } : {}
2327
- };
2328
- }
2329
- function hasAdminFilters(state) {
2330
- return state.filter !== "all" || Boolean(state.search);
2331
- }
2332
- function getAdminStatusPresentation(row) {
2333
- if (row?.account === "invited") {
2334
- return {
2335
- key: "invited",
2336
- tone: "secondary",
2337
- label: { messageId: "adminPanel.status.invited", defaultMessage: "Invited" },
2338
- detail: {
2339
- messageId: "adminPanel.status.invited.detail",
2340
- defaultMessage: "Invitation not accepted yet"
2341
- }
2342
- };
2343
- }
2344
- if (row?.account === "deactivated") {
2345
- return {
2346
- key: "deactivated",
2347
- tone: "neutral",
2348
- label: { messageId: "adminPanel.status.deactivated", defaultMessage: "Deactivated" },
2349
- detail: {
2350
- messageId: "adminPanel.status.deactivated.detail",
2351
- defaultMessage: "Cannot sign in"
2352
- }
2353
- };
2354
- }
2355
- const count = Number(row?.sessionCount) || 0;
2356
- if (count > 0) {
2357
- return {
2358
- key: "signed-in",
2359
- tone: "success",
2360
- label: { messageId: "adminPanel.status.signedIn", defaultMessage: "Signed in" },
2361
- detail: {
2362
- messageId: "adminPanel.status.signedIn.detail",
2363
- defaultMessage: "{count, plural, one {# session} other {# sessions}}",
2364
- values: { count }
2365
- }
2366
- };
2367
- }
2368
- return {
2369
- key: "not-signed-in",
2370
- tone: "neutral",
2371
- label: { messageId: "adminPanel.status.notSignedIn", defaultMessage: "Not signed in" },
2372
- detail: {
2373
- messageId: "adminPanel.status.notSignedIn.detail",
2374
- defaultMessage: "No open session"
1934
+ const RecentUserActivityList = () => {
1935
+ const { formatMessage } = useIntl();
1936
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
1937
+ const params = useMemo(() => buildUserActivityParams({ pageSize: RECENT_USER_EVENT_LIMIT }), []);
1938
+ const list = useEventList({
1939
+ path: USER_ACTIVITY_API_PATH,
1940
+ params,
1941
+ logKey: "userActivity.recent"
1942
+ });
1943
+ return /* @__PURE__ */ jsx(
1944
+ RecentEvents,
1945
+ {
1946
+ title: t("userActivity.recent.title", "Security activity"),
1947
+ subtitle: t(
1948
+ "userActivity.recent.subtitle",
1949
+ "The latest failed and refused sign-ins, lockouts, new devices, impossible travel and impersonations of your app’s users. Select an event for its details."
1950
+ ),
1951
+ showAllTo: USER_ACTIVITY_PAGE_PATH,
1952
+ emptyText: t("userActivity.recent.empty", "No security events of app users yet."),
1953
+ list,
1954
+ dataKey: "recent-user-activity",
1955
+ renderTable: (title) => /* @__PURE__ */ jsx(UserEventTable, { rows: list.rows, label: title, busy: list.loading })
2375
1956
  }
2376
- };
2377
- }
2378
- function splitDuration(seconds) {
2379
- const value = Number(seconds);
2380
- if (!Number.isFinite(value) || value <= 0) return null;
2381
- if (value % 86400 === 0) return { unit: "days", count: value / 86400 };
2382
- if (value % 3600 === 0) return { unit: "hours", count: value / 3600 };
2383
- return { unit: "minutes", count: Math.max(1, Math.round(value / 60)) };
2384
- }
2385
- function getSignOutErrorMessage(error) {
2386
- const response = (
2387
- /** @type {any} */
2388
- error?.response
2389
1957
  );
2390
- const status = Number(response?.status ?? /** @type {any} */
2391
- error?.status);
2392
- const reason = response?.data?.error?.details?.reason;
2393
- if (status === 403 && reason === "super-admin-protected") {
2394
- return {
2395
- messageId: "adminPanel.signOut.error.protected",
2396
- defaultMessage: "Only a Super Admin can sign out a Super Admin."
2397
- };
2398
- }
2399
- if (status === 403) {
2400
- return {
2401
- messageId: "adminPanel.signOut.error.forbidden",
2402
- defaultMessage: "You do not have permission to sign admins out."
2403
- };
1958
+ };
1959
+ const RecentUserActivity = () => {
1960
+ const {
1961
+ allowedActions: { canRead },
1962
+ isLoading
1963
+ } = useRBAC(pluginPermissions.userActivityRead);
1964
+ if (isLoading || !canRead) return null;
1965
+ return /* @__PURE__ */ jsx(RecentUserActivityList, {});
1966
+ };
1967
+ const CLOCK_TICK_MS = 30 * 1e3;
1968
+ const ANALYTICS_PATH = `/settings/${pluginId}/analytics`;
1969
+ const CONFIGURATION_PATH = `/settings/${pluginId}/general`;
1970
+ const PaginationTargets$3 = styled.div`
1971
+ nav a {
1972
+ min-width: 3.2rem;
2404
1973
  }
2405
- if (status === 404) {
2406
- return {
2407
- messageId: "adminPanel.signOut.error.gone",
2408
- defaultMessage: "This session has already ended. The list is up to date now."
2409
- };
1974
+
1975
+ & > div {
1976
+ flex-wrap: wrap;
1977
+ gap: ${({ theme }) => theme.spaces[2]} ${({ theme }) => theme.spaces[4]};
2410
1978
  }
2411
- if (status === 429) {
2412
- return {
2413
- messageId: "adminPanel.signOut.error.rateLimited",
2414
- defaultMessage: "Too many sign-outs in a short time. Wait a minute and try again."
2415
- };
1979
+
1980
+ & > div > div > span {
1981
+ white-space: nowrap;
2416
1982
  }
2417
- return {
2418
- messageId: "adminPanel.signOut.error.generic",
2419
- defaultMessage: "The admin could not be signed out. Try again."
2420
- };
2421
- }
2422
- function withIdentityPlaceholders(admin, placeholderName, identity) {
2423
- if (!admin || typeof admin !== "object") return admin;
2424
- const hidden = !admin.self && !admin.name;
2425
- return {
2426
- ...admin,
2427
- name: admin.name || placeholderName(admin.id),
2428
- identityHidden: hidden,
2429
- rolesHidden: hidden && identity?.roles === false
2430
- };
2431
- }
2432
- function withEventAdminNames(row, placeholderName) {
2433
- if (!row || typeof row !== "object") return row;
2434
- const fill = (admin) => admin && typeof admin === "object" && !admin.name ? { ...admin, name: placeholderName(admin.id), identityHidden: true } : admin;
2435
- return {
2436
- ...row,
2437
- ...row.admin !== void 0 ? { admin: fill(row.admin) } : {},
2438
- ...row.actor !== void 0 ? { actor: fill(row.actor) } : {}
2439
- };
2440
- }
2441
- const HIGHLIGHT_BADGE = { backgroundColor: "primary100", textColor: "neutral800" };
2442
- const offersPreview = (admin, canPreview) => Boolean(canPreview) && admin.self !== true && !(admin.roles || []).some((role) => role?.superAdmin === true);
2443
- const keepActionKeys = (event) => {
2444
- if (shouldIsolateActionKey(event.key, true)) event.stopPropagation();
1983
+ `;
1984
+ const downloadFile = (content, type, extension) => {
1985
+ const blob = new Blob([content], { type });
1986
+ const url = URL.createObjectURL(blob);
1987
+ const link = document.createElement("a");
1988
+ link.href = url;
1989
+ link.download = `sessions-export-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.${extension}`;
1990
+ link.click();
1991
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
2445
1992
  };
2446
- const SHRINKING_ADMIN_CELL = { maxWidth: 0, width: "34%" };
2447
- const SHRINKING_ROLES_CELL = { maxWidth: 0, width: "22%" };
2448
- const useT$4 = () => {
1993
+ const HomePage = () => {
2449
1994
  const { formatMessage } = useIntl();
2450
- return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
2451
- };
2452
- const AdminIdentity = ({ admin }) => {
2453
- const t = useT$4();
2454
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, minWidth: 0, children: [
2455
- /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", minWidth: 0, children: [
2456
- /* @__PURE__ */ jsx(
2457
- Typography,
2458
- {
2459
- variant: "omega",
2460
- fontWeight: "semiBold",
2461
- textColor: "neutral800",
2462
- ellipsis: true,
2463
- title: admin.name,
2464
- children: admin.name
2465
- }
2466
- ),
2467
- admin.self ? /* @__PURE__ */ jsx(Badge, { ...HIGHLIGHT_BADGE, shrink: 0, children: t("adminPanel.you", "You") }) : null
2468
- ] }),
2469
- admin.identityHidden ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("adminPanel.identity.emailHidden", "Email hidden (needs “Read” on Users)") }) : /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", ellipsis: true, title: admin.email, children: admin.email })
2470
- ] });
2471
- };
2472
- const AdminRoles = ({ admin }) => {
2473
- const t = useT$4();
2474
- const names = (admin.roles || []).map((role) => role.name).filter(Boolean);
2475
- const text = admin.rolesHidden ? t("adminPanel.roles.hidden", "Hidden (needs “Read” on Roles)") : names.length ? names.join(", ") : t("adminPanel.roles.none", "No role");
2476
- return /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", ellipsis: true, title: text, children: text });
2477
- };
2478
- const AdminStatus = ({ admin }) => {
2479
- const t = useT$4();
2480
- const status = getAdminStatusPresentation(admin);
2481
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, "data-admin-status": status.key, children: [
2482
- /* @__PURE__ */ jsx(Badge, { ...getBadgeColors(status.tone), children: t(status.label.messageId, status.label.defaultMessage) }),
2483
- /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(status.detail.messageId, status.detail.defaultMessage, status.detail.values) })
2484
- ] });
2485
- };
2486
- const AdminTable = ({
2487
- admins,
2488
- labelledBy,
2489
- canRevoke,
2490
- onView,
2491
- onSignOutEverywhere,
2492
- canPreview,
2493
- onPreview,
2494
- busy
2495
- }) => {
2496
- const t = useT$4();
2497
- return /* @__PURE__ */ jsx(Box, { background: "neutral0", hasRadius: true, shadow: "tableShadow", "data-admin-table": "", children: /* @__PURE__ */ jsxs(
2498
- Table,
2499
- {
2500
- colCount: 5,
2501
- rowCount: admins.length + 1,
2502
- "aria-labelledby": labelledBy,
2503
- "aria-busy": busy,
2504
- children: [
2505
- /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
2506
- /* @__PURE__ */ jsx(Th, { style: SHRINKING_ADMIN_CELL, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.admin", "Admin") }) }),
2507
- /* @__PURE__ */ jsx(Th, { style: SHRINKING_ROLES_CELL, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.roles", "Roles") }) }),
2508
- /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.status", "Status") }) }),
2509
- /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.lastActive", "Last active") }) }),
2510
- /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(VisuallyHidden, { children: t("adminPanel.table.actions", "Actions") }) })
2511
- ] }) }),
2512
- /* @__PURE__ */ jsx(Tbody, { children: admins.map((admin) => /* @__PURE__ */ jsxs(Tr, { "data-admin-row": admin.id, children: [
2513
- /* @__PURE__ */ jsx(Td, { style: SHRINKING_ADMIN_CELL, children: /* @__PURE__ */ jsx(AdminIdentity, { admin }) }),
2514
- /* @__PURE__ */ jsx(Td, { style: SHRINKING_ROLES_CELL, children: /* @__PURE__ */ jsx(AdminRoles, { admin }) }),
2515
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(AdminStatus, { admin }) }),
2516
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(LastActive, { value: admin.lastActiveAt }) }),
2517
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsxs(RowActions, { onKeyDown: keepActionKeys, children: [
2518
- /* @__PURE__ */ jsx(
2519
- IconButton,
2520
- {
2521
- label: t("adminPanel.actions.view", "View sessions of {name}", {
2522
- name: admin.name
2523
- }),
2524
- onClick: (event) => onView(admin, event.currentTarget),
2525
- children: /* @__PURE__ */ jsx(Eye, {})
2526
- }
2527
- ),
2528
- offersPreview(admin, canPreview) ? /* @__PURE__ */ jsx(
2529
- IconButton,
2530
- {
2531
- label: t("adminPanel.actions.viewAs", "View as {name}", {
2532
- name: admin.name || `#${admin.id}`
2533
- }),
2534
- onClick: (event) => onPreview?.(admin, event.currentTarget),
2535
- children: /* @__PURE__ */ jsx(User, {})
2536
- }
2537
- ) : null,
2538
- canRevoke && admin.canSignOut ? /* @__PURE__ */ jsx(
2539
- IconButton,
2540
- {
2541
- variant: "danger-light",
2542
- label: t(
2543
- "adminPanel.actions.signOutEverywhere",
2544
- "Sign out {name} everywhere",
2545
- {
2546
- name: admin.name
2547
- }
2548
- ),
2549
- onClick: (event) => onSignOutEverywhere(admin, event.currentTarget),
2550
- children: /* @__PURE__ */ jsx(SignOut, {})
2551
- }
2552
- ) : null
2553
- ] }) })
2554
- ] }, admin.id)) })
2555
- ]
1995
+ const { get, post, del } = useFetchClient();
1996
+ const { toggleNotification } = useNotification();
1997
+ const formatters = useSessionFormatters();
1998
+ const { isBelowSmall, isBelowMedium, isBelowLarge } = useBreakpoint();
1999
+ const [listWidthRef, listWidth] = useElementWidth();
2000
+ const [{ query }, setQuery] = useQueryParams();
2001
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
2002
+ const dashboard = parseDashboardQuery(query);
2003
+ const [sessions, setSessions] = useState([]);
2004
+ const [pagination, setPagination] = useState({ total: 0, pageCount: 1 });
2005
+ const [stats, setStats] = useState(EMPTY_SESSION_STATS);
2006
+ const [exporting, setExporting] = useState(false);
2007
+ const [loading, setLoading] = useState(true);
2008
+ const [refreshing, setRefreshing] = useState(false);
2009
+ const [loadError, setLoadError] = useState(false);
2010
+ const [hasData, setHasData] = useState(false);
2011
+ const [lastUpdated, setLastUpdated] = useState(null);
2012
+ const [now, setNow] = useState(() => Date.now());
2013
+ const [selectedSession, setSelectedSession] = useState(null);
2014
+ const [showDetailModal, setShowDetailModal] = useState(false);
2015
+ const [terminatingSessionId, setTerminatingSessionId] = useState(null);
2016
+ const [deletingSessionId, setDeletingSessionId] = useState(null);
2017
+ const openerRef = useRef(null);
2018
+ const dashboardRef = useRef(null);
2019
+ const listHeadingRef = useRef(null);
2020
+ const hasLoadedRef = useRef(false);
2021
+ const requestIdRef = useRef(0);
2022
+ const visibleIdsRef = useRef([]);
2023
+ const mutationSnapshotRef = useRef([]);
2024
+ const listHeadingId = `session-list-caption-${useId().replace(/:/g, "")}`;
2025
+ const mutationPending = Boolean(terminatingSessionId || deletingSessionId);
2026
+ const listQuery = useMemo(
2027
+ () => ({
2028
+ page: dashboard.page,
2029
+ pageSize: dashboard.pageSize,
2030
+ status: dashboard.status,
2031
+ reason: dashboard.reason,
2032
+ search: dashboard.search
2033
+ }),
2034
+ [dashboard.page, dashboard.pageSize, dashboard.status, dashboard.reason, dashboard.search]
2035
+ );
2036
+ useEffect(() => {
2037
+ const timer = setInterval(() => setNow(Date.now()), CLOCK_TICK_MS);
2038
+ return () => clearInterval(timer);
2039
+ }, []);
2040
+ const fetchSessions = useCallback(async () => {
2041
+ const requestId = requestIdRef.current + 1;
2042
+ requestIdRef.current = requestId;
2043
+ if (hasLoadedRef.current) setRefreshing(true);
2044
+ else setLoading(true);
2045
+ try {
2046
+ const [listResponse, statsResponse] = await Promise.all([
2047
+ get(`/${pluginId}/sessions`, { params: buildListParams(listQuery) }),
2048
+ get(`/${pluginId}/sessions/stats`)
2049
+ ]);
2050
+ const page = readSessionPage(listResponse.data);
2051
+ const nextStats = readSessionStats(statsResponse.data);
2052
+ if (requestId !== requestIdRef.current) return;
2053
+ setSessions(page.rows);
2054
+ setPagination(page.pagination);
2055
+ setStats(nextStats);
2056
+ setLoadError(false);
2057
+ setHasData(true);
2058
+ setLastUpdated(Date.now());
2059
+ setNow(Date.now());
2060
+ hasLoadedRef.current = true;
2061
+ } catch (err) {
2062
+ if (requestId !== requestIdRef.current || isCancelledRequest(err)) return;
2063
+ setLoadError(true);
2064
+ logSafeAdminError("dashboard.loadSessions", err);
2065
+ } finally {
2066
+ if (requestId === requestIdRef.current) {
2067
+ setLoading(false);
2068
+ setRefreshing(false);
2069
+ }
2556
2070
  }
2557
- ) });
2558
- };
2559
- const AdminCardList = ({
2560
- admins,
2561
- labelledBy,
2562
- canRevoke,
2563
- onView,
2564
- onSignOutEverywhere,
2565
- canPreview,
2566
- onPreview
2567
- }) => {
2568
- const t = useT$4();
2569
- return /* @__PURE__ */ jsx(
2570
- Flex,
2571
- {
2572
- tag: "ul",
2573
- direction: "column",
2574
- alignItems: "stretch",
2575
- gap: 3,
2576
- "aria-labelledby": labelledBy,
2577
- "data-admin-cards": "",
2578
- children: admins.map((admin) => /* @__PURE__ */ jsx(
2579
- Box,
2580
- {
2581
- tag: "li",
2582
- background: "neutral0",
2583
- hasRadius: true,
2584
- shadow: "tableShadow",
2585
- padding: 4,
2586
- "data-admin-row": admin.id,
2587
- children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 3, minWidth: 0, children: [
2588
- /* @__PURE__ */ jsx(AdminIdentity, { admin }),
2589
- /* @__PURE__ */ jsxs(Flex, { gap: 4, wrap: "wrap", alignItems: "flex-start", justifyContent: "space-between", children: [
2590
- /* @__PURE__ */ jsx(AdminStatus, { admin }),
2591
- /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
2592
- /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.lastActive", "Last active") }),
2593
- /* @__PURE__ */ jsx(LastActive, { value: admin.lastActiveAt })
2594
- ] })
2595
- ] }),
2596
- /* @__PURE__ */ jsx(AdminRoles, { admin }),
2597
- /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", children: [
2598
- /* @__PURE__ */ jsx(
2599
- Button,
2600
- {
2601
- variant: "secondary",
2602
- startIcon: /* @__PURE__ */ jsx(Eye, {}),
2603
- onClick: (event) => onView(admin, event.currentTarget),
2604
- "aria-label": t("adminPanel.actions.view", "View sessions of {name}", {
2605
- name: admin.name
2606
- }),
2607
- flex: "1 1 auto",
2608
- children: t("adminPanel.actions.viewShort", "View sessions")
2609
- }
2610
- ),
2611
- offersPreview(admin, canPreview) ? /* @__PURE__ */ jsx(
2612
- Button,
2613
- {
2614
- variant: "secondary",
2615
- startIcon: /* @__PURE__ */ jsx(User, {}),
2616
- onClick: (event) => onPreview?.(admin, event.currentTarget),
2617
- "aria-label": t("adminPanel.actions.viewAs", "View as {name}", {
2618
- name: admin.name || `#${admin.id}`
2619
- }),
2620
- flex: "1 1 auto",
2621
- children: t("adminPanel.actions.viewAsShort", "View as")
2622
- }
2623
- ) : null,
2624
- canRevoke && admin.canSignOut ? /* @__PURE__ */ jsx(
2625
- Button,
2626
- {
2627
- variant: "danger-light",
2628
- startIcon: /* @__PURE__ */ jsx(SignOut, {}),
2629
- onClick: (event) => onSignOutEverywhere(admin, event.currentTarget),
2630
- "aria-label": t(
2631
- "adminPanel.actions.signOutEverywhere",
2632
- "Sign out {name} everywhere",
2633
- {
2634
- name: admin.name
2635
- }
2636
- ),
2637
- flex: "1 1 auto",
2638
- children: t("adminPanel.actions.signOutEverywhereShort", "Sign out everywhere")
2639
- }
2640
- ) : null
2641
- ] })
2642
- ] })
2643
- },
2644
- admin.id
2645
- ))
2071
+ }, [get, listQuery]);
2072
+ useEffect(() => {
2073
+ fetchSessions();
2074
+ }, [fetchSessions]);
2075
+ useEffect(() => {
2076
+ if (showDetailModal || mutationPending) return void 0;
2077
+ const interval = setInterval(() => {
2078
+ fetchSessions();
2079
+ }, AUTO_REFRESH_INTERVAL_MS);
2080
+ return () => clearInterval(interval);
2081
+ }, [showDetailModal, mutationPending, fetchSessions]);
2082
+ const handleTerminateSession = async (session) => {
2083
+ if (terminatingSessionId || deletingSessionId) return;
2084
+ const sessionId = session.id;
2085
+ mutationSnapshotRef.current = visibleIdsRef.current;
2086
+ setTerminatingSessionId(sessionId);
2087
+ try {
2088
+ await post(`/${pluginId}/sessions/${sessionId}/terminate`);
2089
+ await fetchSessions();
2090
+ toggleNotification({
2091
+ type: "success",
2092
+ message: t("notifications.success.sessionEnded", "Session ended.")
2093
+ });
2094
+ } catch (err) {
2095
+ logSafeAdminError("dashboard.terminateSession", err);
2096
+ if (getErrorStatus(err) === 404) {
2097
+ await fetchSessions();
2098
+ toggleNotification({
2099
+ type: "warning",
2100
+ message: t(
2101
+ "notifications.error.sessionGone",
2102
+ "This session no longer exists. The list was refreshed."
2103
+ )
2104
+ });
2105
+ return;
2106
+ }
2107
+ toggleNotification({
2108
+ type: "danger",
2109
+ message: t(
2110
+ "notifications.error.endSession",
2111
+ "The session could not be ended. Please try again."
2112
+ )
2113
+ });
2114
+ throw err;
2115
+ } finally {
2116
+ setTerminatingSessionId(null);
2117
+ }
2118
+ };
2119
+ const handleDeleteSession = async (session) => {
2120
+ if (terminatingSessionId || deletingSessionId) return;
2121
+ const sessionId = session.id;
2122
+ mutationSnapshotRef.current = visibleIdsRef.current;
2123
+ setDeletingSessionId(sessionId);
2124
+ try {
2125
+ await del(`/${pluginId}/sessions/${sessionId}`);
2126
+ await fetchSessions();
2127
+ toggleNotification({
2128
+ type: "success",
2129
+ message: t(
2130
+ "notifications.success.recordDeleted",
2131
+ "Session record deleted. Its token stays revoked."
2132
+ )
2133
+ });
2134
+ } catch (err) {
2135
+ logSafeAdminError("dashboard.deleteSession", err);
2136
+ if (getErrorStatus(err) === 404) {
2137
+ await fetchSessions();
2138
+ toggleNotification({
2139
+ type: "warning",
2140
+ message: t(
2141
+ "notifications.error.sessionGone",
2142
+ "This session no longer exists. The list was refreshed."
2143
+ )
2144
+ });
2145
+ return;
2146
+ }
2147
+ toggleNotification({
2148
+ type: "danger",
2149
+ message: t(
2150
+ "notifications.error.deleteRecord",
2151
+ "The record could not be deleted. Please try again."
2152
+ )
2153
+ });
2154
+ throw err;
2155
+ } finally {
2156
+ setDeletingSessionId(null);
2646
2157
  }
2647
- );
2648
- };
2649
- const SIGN_IN_FILTER_OPTIONS = Object.freeze(["all", "succeeded", "failed", "signed-out"]);
2650
- const ALL_ADMINS_FILTER_OPTIONS = Object.freeze([...SIGN_IN_FILTER_OPTIONS, "changes"]);
2651
- const ACTIVITY_ACTION_OPTIONS = Object.freeze([
2652
- "all",
2653
- "view",
2654
- "create",
2655
- "update",
2656
- "publish",
2657
- "unpublish",
2658
- "discard",
2659
- "delete",
2660
- "clone"
2661
- ]);
2662
- const PERIOD_OPTIONS = Object.freeze(["1", "7", "30", "90", "all"]);
2663
- const EVENT_PAGE_SIZE = 20;
2664
- const MAX_EVENT_EXPORT_ROWS = 1e4;
2665
- function periodStart(period, now = /* @__PURE__ */ new Date()) {
2666
- const days = Number.parseInt(period, 10);
2667
- if (!Number.isInteger(days) || days <= 0) return void 0;
2668
- return new Date(now.getTime() - days * 24 * 60 * 60 * 1e3).toISOString();
2669
- }
2670
- function buildSignInParams(filters, now) {
2671
- const params = {
2672
- page: filters.page || 1,
2673
- pageSize: filters.pageSize || EVENT_PAGE_SIZE,
2674
- event: ALL_ADMINS_FILTER_OPTIONS.includes(filters.event) ? filters.event : "all"
2675
2158
  };
2676
- if (filters.adminId) params.adminId = String(filters.adminId);
2677
- const from = periodStart(filters.period || "all", now);
2678
- if (from) params.from = from;
2679
- return params;
2680
- }
2681
- function buildActivityParams(filters, now) {
2682
- const params = {
2683
- page: filters.page || 1,
2684
- pageSize: filters.pageSize || EVENT_PAGE_SIZE,
2685
- action: ACTIVITY_ACTION_OPTIONS.includes(filters.action) ? filters.action : "all"
2159
+ const pageSize = Number(dashboard.pageSize);
2160
+ const pageResult = {
2161
+ items: sessions,
2162
+ total: pagination.total,
2163
+ pageCount: pagination.pageCount,
2164
+ startIndex: pagination.total > 0 ? (dashboard.page - 1) * pageSize + 1 : 0,
2165
+ endIndex: pagination.total > 0 ? (dashboard.page - 1) * pageSize + sessions.length : 0
2686
2166
  };
2687
- if (filters.adminId) params.adminId = String(filters.adminId);
2688
- if (filters.contentType && filters.contentType !== "all")
2689
- params.contentType = filters.contentType;
2690
- const from = periodStart(filters.period || "all", now);
2691
- if (from) params.from = from;
2692
- return params;
2693
- }
2694
- function toExportParams(params, cursor) {
2695
- const { page: _page, pageSize: _pageSize, ...rest } = params;
2696
- return cursor ? { ...rest, cursor } : rest;
2697
- }
2698
- const message = (messageId, defaultMessage) => ({ messageId, defaultMessage });
2699
- const FAILURE_REASONS = Object.freeze({
2700
- invalid_credentials: message(
2701
- "adminPanel.activity.reason.invalidCredentials",
2702
- "Wrong email or password"
2703
- ),
2704
- account_inactive: message("adminPanel.activity.reason.accountInactive", "Account is deactivated"),
2705
- login_not_allowed: message("adminPanel.activity.reason.notAllowed", "Sign-in is not allowed"),
2706
- rate_limited: message("adminPanel.activity.reason.rateLimited", "Too many attempts")
2707
- });
2708
- const appUserEvent = (key, tone, icon, messageId, defaultMessage) => ({
2709
- key,
2710
- tone,
2711
- icon,
2712
- label: message(messageId, defaultMessage),
2713
- detail: null
2714
- });
2715
- function getSignInEventPresentation(row) {
2716
- switch (row?.event) {
2717
- case "admin.sign-in":
2718
- return {
2719
- key: "sign-in",
2720
- tone: "success",
2721
- icon: "signIn",
2722
- label: message("adminPanel.activity.event.signIn", "Signed in"),
2723
- detail: row.reason === "registration" ? message("adminPanel.activity.reason.registration", "First sign-in after registration") : row.reason === "password_reset" ? message(
2724
- "adminPanel.activity.reason.passwordReset",
2725
- "Signed in after a password reset"
2726
- ) : null
2727
- };
2728
- case "admin.sign-in.failed":
2729
- return {
2730
- key: "failed",
2731
- tone: "danger",
2732
- icon: "failed",
2733
- label: message("adminPanel.activity.event.failed", "Sign-in failed"),
2734
- detail: FAILURE_REASONS[row.reason] || null
2735
- };
2736
- case "admin.lockout":
2737
- return {
2738
- key: "lockout",
2739
- tone: "danger",
2740
- icon: "lockout",
2741
- label: message("adminPanel.activity.event.lockout", "Locked out"),
2742
- detail: FAILURE_REASONS.rate_limited
2743
- };
2744
- case "admin.sign-out":
2745
- return {
2746
- key: "sign-out",
2747
- tone: "neutral",
2748
- icon: "signOut",
2749
- label: message("adminPanel.activity.event.signOut", "Signed out"),
2750
- detail: null
2751
- };
2752
- case "admin.session.revoked":
2753
- return {
2754
- key: "revoked",
2755
- tone: "warning",
2756
- icon: "revoked",
2757
- label: message("adminPanel.activity.event.revoked", "Signed out by an admin"),
2758
- detail: row.scope === "one_browser" ? message("adminPanel.activity.scope.oneBrowser", "One browser") : message("adminPanel.activity.scope.everywhere", "Every browser")
2759
- };
2760
- case "settings.updated":
2761
- return {
2762
- key: "settings",
2763
- tone: "secondary",
2764
- icon: "settings",
2765
- label: message("adminPanel.activity.event.settings", "Settings changed"),
2766
- detail: row.change?.viaToken ? message("adminPanel.activity.via.token", "With an admin API token") : null
2767
- };
2768
- case "security-log.read":
2769
- return {
2770
- key: "log-read",
2771
- tone: "secondary",
2772
- icon: "logRead",
2773
- label: message("adminPanel.activity.event.logRead", "Log read with an API token"),
2774
- detail: row.read?.list === "content" ? row.read?.exported ? message(
2775
- "adminPanel.activity.read.contentExport",
2776
- "Content Manager activity exported"
2777
- ) : message("adminPanel.activity.read.content", "Content Manager activity listed") : row.read?.exported ? message("adminPanel.activity.read.signInsExport", "Sign-in history exported") : message("adminPanel.activity.read.signIns", "Sign-in history listed")
2778
- };
2779
- case "security-log.retention.purged":
2780
- return {
2781
- key: "purged",
2782
- tone: "neutral",
2783
- icon: "purged",
2784
- label: message("adminPanel.activity.event.purged", "Old events deleted"),
2785
- detail: null
2786
- };
2787
- // App-user events (4.17 / 4.18). The admin lists of this view do not return them
2788
- // today; they get their own label and colour so any list that does shows them clearly.
2789
- case "user.sign-in.failed":
2790
- return appUserEvent(
2791
- "user-failed",
2792
- "danger",
2793
- "failed",
2794
- "adminPanel.activity.event.userFailed",
2795
- "App user sign-in failed"
2796
- );
2797
- case "user.sign-in.refused":
2798
- return appUserEvent(
2799
- "user-refused",
2800
- "danger",
2801
- "refused",
2802
- "adminPanel.activity.event.userRefused",
2803
- "App user sign-in refused"
2804
- );
2805
- case "user.lockout":
2806
- return appUserEvent(
2807
- "user-lockout",
2808
- "danger",
2809
- "lockout",
2810
- "adminPanel.activity.event.userLockout",
2811
- "App user locked out"
2812
- );
2813
- case "user.lockout.lifted":
2814
- return appUserEvent(
2815
- "user-unlock",
2816
- "secondary",
2817
- "unlock",
2818
- "adminPanel.activity.event.userUnlock",
2819
- "Lockout lifted"
2820
- );
2821
- case "user.session.limit":
2822
- return appUserEvent(
2823
- "user-limit",
2824
- "warning",
2825
- "limit",
2826
- "adminPanel.activity.event.userLimit",
2827
- "Session limit reached"
2828
- );
2829
- case "user.password-change.ended-others":
2830
- return appUserEvent(
2831
- "user-password",
2832
- "warning",
2833
- "password",
2834
- "adminPanel.activity.event.userPassword",
2835
- "Signed out after a password change"
2836
- );
2837
- case "user.sign-in.new-device":
2838
- return appUserEvent(
2839
- "user-device",
2840
- "secondary",
2841
- "device",
2842
- "adminPanel.activity.event.userNewDevice",
2843
- "Sign-in from a new device"
2844
- );
2845
- case "user.sign-in.impossible-travel":
2846
- return appUserEvent(
2847
- "user-travel",
2848
- "danger",
2849
- "travel",
2850
- "adminPanel.activity.event.userTravel",
2851
- "Impossible travel"
2852
- );
2853
- case "user.not-me":
2854
- return appUserEvent(
2855
- "user-not-me",
2856
- "danger",
2857
- "notMe",
2858
- "adminPanel.activity.event.userNotMe",
2859
- 'Reported as "This wasn’t me"'
2860
- );
2861
- case "user.data.exported":
2862
- return appUserEvent(
2863
- "user-export",
2864
- "secondary",
2865
- "export",
2866
- "adminPanel.activity.event.userExport",
2867
- "Personal data exported"
2868
- );
2869
- default:
2870
- if (typeof row?.event === "string" && row.event.startsWith("impersonation.")) {
2871
- return appUserEvent(
2872
- "impersonation",
2873
- "warning",
2874
- "impersonation",
2875
- "adminPanel.activity.event.impersonation",
2876
- "Impersonation"
2877
- );
2167
+ const visibleIds = pageResult.items.map((session) => String(session.id));
2168
+ useLayoutEffect(() => {
2169
+ visibleIdsRef.current = visibleIds;
2170
+ });
2171
+ const fetchExportRows = async () => {
2172
+ const rows = [];
2173
+ let cursor = null;
2174
+ do {
2175
+ const { data } = await get(`/${pluginId}/sessions/export`, {
2176
+ params: buildExportParams(listQuery, cursor)
2177
+ });
2178
+ rows.push(...requireSessionList(data));
2179
+ cursor = typeof data?.meta?.nextCursor === "string" ? data.meta.nextCursor : null;
2180
+ } while (cursor && rows.length < MAX_EXPORT_ROWS);
2181
+ const capped = rows.length > MAX_EXPORT_ROWS || Boolean(cursor) && rows.length >= MAX_EXPORT_ROWS;
2182
+ return { rows: rows.slice(0, MAX_EXPORT_ROWS), capped };
2183
+ };
2184
+ const handleExport = async (format) => {
2185
+ if (exporting) return;
2186
+ setExporting(true);
2187
+ try {
2188
+ const { rows, capped } = await fetchExportRows();
2189
+ if (format === "csv") {
2190
+ const csvContent = buildSessionCsv(rows, {
2191
+ unavailableValue: "",
2192
+ getDeviceInfo: getExportDeviceInfo,
2193
+ getSessionStatus
2194
+ });
2195
+ downloadFile(csvContent, "text/csv;charset=utf-8;", "csv");
2196
+ } else {
2197
+ const jsonContent = buildSessionJson(rows, {
2198
+ filterStatus: dashboard.status,
2199
+ totalSessions: stats.total,
2200
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
2201
+ unavailableValue: "",
2202
+ getDeviceInfo: getExportDeviceInfo,
2203
+ getSessionStatus,
2204
+ truncated: capped
2205
+ });
2206
+ downloadFile(jsonContent, "application/json", "json");
2878
2207
  }
2879
- if (typeof row?.event === "string" && row.event.startsWith("webhook.")) {
2880
- return appUserEvent(
2881
- "webhook",
2882
- "neutral",
2883
- "webhook",
2884
- "adminPanel.activity.event.webhook",
2885
- "Webhook delivery"
2886
- );
2208
+ if (capped) {
2209
+ toggleNotification({
2210
+ type: "warning",
2211
+ message: t(
2212
+ "homepage.export.capped",
2213
+ "The export contains the newest {limit, number} sessions. Narrow the filter to export the rest.",
2214
+ { limit: MAX_EXPORT_ROWS }
2215
+ )
2216
+ });
2887
2217
  }
2888
- return {
2889
- key: "other",
2890
- tone: "neutral",
2891
- icon: "other",
2892
- label: message("adminPanel.activity.event.other", "Security event"),
2893
- detail: null
2894
- };
2895
- }
2896
- }
2897
- function getSessionStatePresentation(session) {
2898
- switch (session?.state) {
2899
- case "active":
2900
- return {
2901
- tone: "success",
2902
- label: message("adminPanel.activity.session.active", "Still signed in")
2903
- };
2904
- case "signed-out":
2905
- return {
2906
- tone: "neutral",
2907
- label: message("adminPanel.activity.session.signedOut", "Signed out")
2908
- };
2909
- case "ended":
2910
- return {
2911
- tone: "neutral",
2912
- label: message("adminPanel.activity.session.ended", "Session ended")
2913
- };
2914
- default:
2915
- return null;
2916
- }
2917
- }
2918
- const RECENT_EVENT_LIMIT = 8;
2919
- const ACTIVITY_PAGE_SIZE_OPTIONS = Object.freeze(["10", "20", "50", "100"]);
2920
- const EVENT_TABLE_MIN_WIDTH = Object.freeze({ withAdmin: 800, withoutAdmin: 740 });
2921
- const EVENT_TABLE_FULL_WIDTH = 1e3;
2922
- function getEventListLayout(width, { showAdmin = false } = {}) {
2923
- if (!width) return "full";
2924
- const min = showAdmin ? EVENT_TABLE_MIN_WIDTH.withAdmin : EVENT_TABLE_MIN_WIDTH.withoutAdmin;
2925
- if (width < min) return "stacked";
2926
- return width >= EVENT_TABLE_FULL_WIDTH ? "full" : "table";
2927
- }
2928
- function getEventPlace(row) {
2929
- return [row?.location?.city, row?.location?.country].filter(Boolean).join(", ");
2930
- }
2931
- function parseActivityPageQuery(query) {
2932
- const source = query || {};
2933
- const event = ALL_ADMINS_FILTER_OPTIONS.includes(String(source.event)) ? String(source.event) : "all";
2934
- const period = PERIOD_OPTIONS.includes(String(source.period)) ? String(source.period) : "30";
2935
- const adminId = /^[1-9][0-9]{0,11}$/.test(String(source.adminId ?? "")) ? Number(source.adminId) : null;
2936
- const page = Number.parseInt(String(source.page ?? ""), 10);
2937
- const pageSize = String(source.pageSize ?? "");
2938
- return {
2939
- event,
2940
- period,
2941
- adminId,
2942
- page: Number.isInteger(page) && page > 0 ? page : 1,
2943
- pageSize: ACTIVITY_PAGE_SIZE_OPTIONS.includes(pageSize) ? Number(pageSize) : EVENT_PAGE_SIZE
2944
- };
2945
- }
2946
- function hasActivityPageFilters(view) {
2947
- return view.event !== "all" || view.period !== "30" || view.adminId !== null;
2948
- }
2949
- function groupChangedSettings(keys) {
2950
- const list = Array.isArray(keys) ? keys.filter((key) => typeof key === "string" && key) : [];
2951
- const byTab = /* @__PURE__ */ new Map();
2952
- const unknown = [];
2953
- const seen = /* @__PURE__ */ new Set();
2954
- for (const key of list) {
2955
- const tab = SETTINGS_TAB_IDS.find((id) => SETTINGS_TAB_FIELDS[id]?.includes(key));
2956
- const entry = SETTINGS_FIELD_LABELS[key];
2957
- if (!tab || !entry) {
2958
- if (!seen.has(`raw:${key}`)) unknown.push({ key, label: null });
2959
- seen.add(`raw:${key}`);
2960
- continue;
2218
+ } catch (err) {
2219
+ if (isCancelledRequest(err)) return;
2220
+ logSafeAdminError(format === "csv" ? "dashboard.exportCsv" : "dashboard.exportJson", err);
2221
+ toggleNotification({
2222
+ type: "danger",
2223
+ message: t("notifications.error.exportFailed", "The export could not be created.")
2224
+ });
2225
+ } finally {
2226
+ setExporting(false);
2961
2227
  }
2962
- if (seen.has(`label:${entry[0]}`)) continue;
2963
- seen.add(`label:${entry[0]}`);
2964
- if (!byTab.has(tab)) byTab.set(tab, []);
2965
- byTab.get(tab).push({ key, label: message(entry[0], entry[1]) });
2966
- }
2967
- const groups = SETTINGS_TAB_IDS.filter((tab) => byTab.has(tab)).map((tab) => ({
2968
- tab,
2969
- label: message(SETTINGS_TAB_LABELS[tab][0], SETTINGS_TAB_LABELS[tab][1]),
2970
- fields: byTab.get(tab)
2971
- }));
2972
- if (unknown.length) groups.push({ tab: null, label: null, fields: unknown });
2973
- return groups;
2974
- }
2975
- const ACTIVITY_ACTION_LABELS = Object.freeze({
2976
- all: message("adminPanel.activity.action.all", "All actions"),
2977
- view: message("adminPanel.activity.action.view", "Opened"),
2978
- create: message("adminPanel.activity.action.create", "Created"),
2979
- update: message("adminPanel.activity.action.update", "Edited"),
2980
- publish: message("adminPanel.activity.action.publish", "Published"),
2981
- unpublish: message("adminPanel.activity.action.unpublish", "Unpublished"),
2982
- discard: message("adminPanel.activity.action.discard", "Discarded draft"),
2983
- delete: message("adminPanel.activity.action.delete", "Deleted"),
2984
- clone: message("adminPanel.activity.action.clone", "Duplicated")
2985
- });
2986
- function getActivityTone(action) {
2987
- if (action === "publish") return "success";
2988
- if (action === "delete") return "warning";
2989
- return "neutral";
2990
- }
2991
- function getEntryPath(row) {
2992
- const type = row?.contentType;
2993
- if (!type?.exists || row.action === "delete") return null;
2994
- const uid = encodeURIComponent(type.uid);
2995
- const locale = row.entry?.locale ? `?plugins[i18n][locale]=${encodeURIComponent(row.entry.locale)}` : "";
2996
- if (type.kind === "single") return `/content-manager/single-types/${uid}${locale}`;
2997
- if (!row.entry?.documentId) return null;
2998
- return `/content-manager/collection-types/${uid}/${encodeURIComponent(row.entry.documentId)}${locale}`;
2999
- }
3000
- const SIGN_IN_CSV_HEADERS = Object.freeze([
3001
- "Time",
3002
- "Event",
3003
- "Reason",
3004
- "Admin",
3005
- "Admin ID",
3006
- "IP Address",
3007
- "IP Anonymized",
3008
- "Country",
3009
- "City",
3010
- "Browser",
3011
- "OS",
3012
- "Device",
3013
- "Session",
3014
- "Signed Out By"
3015
- ]);
3016
- const ACTIVITY_CSV_HEADERS = Object.freeze([
3017
- "Time",
3018
- "Action",
3019
- "Admin",
3020
- "Admin ID",
3021
- "Content Type",
3022
- "Content Type UID",
3023
- "Document ID",
3024
- "Locale",
3025
- "Title",
3026
- "Entries"
3027
- ]);
3028
- const toCsv = (headers, rows) => [headers, ...rows].map((cells) => cells.map(escapeCsvValue).join(",")).join("\n");
3029
- function buildSignInCsv(rows) {
3030
- return toCsv(
3031
- SIGN_IN_CSV_HEADERS,
3032
- rows.map((row) => [
3033
- row.at || "",
3034
- row.event || "",
3035
- row.reason || row.scope || "",
3036
- row.admin?.name || "",
3037
- row.admin?.id ?? "",
3038
- row.ipAddress || "",
3039
- row.ipAnonymized ? "yes" : "no",
3040
- row.location?.country || "",
3041
- row.location?.city || "",
3042
- row.browser || "",
3043
- row.os || "",
3044
- row.deviceType || "",
3045
- row.session?.state || "",
3046
- row.actor?.name || ""
3047
- ])
2228
+ };
2229
+ const handleSessionClick = (session, opener) => {
2230
+ openerRef.current = opener;
2231
+ setSelectedSession(session);
2232
+ setShowDetailModal(true);
2233
+ };
2234
+ const handleModalClose = () => {
2235
+ setShowDetailModal(false);
2236
+ setSelectedSession(null);
2237
+ };
2238
+ const handleCloseAutoFocus = (event) => {
2239
+ restoreDialogFocus(event, openerRef.current, listHeadingRef.current || dashboardRef.current);
2240
+ };
2241
+ const getFocusFallback = useCallback(
2242
+ (sessionId) => ({
2243
+ get current() {
2244
+ const targetId = pickFocusSessionId(
2245
+ mutationSnapshotRef.current,
2246
+ visibleIdsRef.current,
2247
+ sessionId
2248
+ );
2249
+ const root = dashboardRef.current;
2250
+ if (targetId && root) {
2251
+ const escaped = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(targetId) : targetId;
2252
+ const button = root.querySelector(`[data-session-view="${escaped}"]`);
2253
+ if (button) return button;
2254
+ }
2255
+ return listHeadingRef.current;
2256
+ }
2257
+ }),
2258
+ []
3048
2259
  );
3049
- }
3050
- function buildActivityCsv(rows) {
3051
- return toCsv(
3052
- ACTIVITY_CSV_HEADERS,
3053
- rows.map((row) => [
3054
- row.at || "",
3055
- row.action || "",
3056
- row.admin?.name || "",
3057
- row.admin?.id ?? "",
3058
- row.contentType?.name || "",
3059
- row.contentType?.uid || "",
3060
- row.entry?.documentId || "",
3061
- row.entry?.locale || "",
3062
- row.entry?.title || "",
3063
- row.entry?.count ?? ""
3064
- ])
2260
+ useEffect(() => {
2261
+ if (!loading && !refreshing && dashboard.page > pageResult.pageCount) {
2262
+ setQuery({ page: String(pageResult.pageCount) }, "push", true);
2263
+ }
2264
+ }, [loading, refreshing, dashboard.page, pageResult.pageCount, setQuery]);
2265
+ const handleStatusChange = (value) => {
2266
+ const status = String(value);
2267
+ setQuery({ status: status === "all" ? void 0 : status, reason: void 0, page: "1" });
2268
+ };
2269
+ const handleReasonChange = (value) => {
2270
+ const reason = String(value);
2271
+ setQuery({ reason: reason === "all" ? void 0 : reason, page: "1" });
2272
+ };
2273
+ const handleSearch = useCallback(
2274
+ (value) => {
2275
+ setQuery({ search: encodeSearchQuery(value), _q: void 0, page: "1" }, "push", true);
2276
+ },
2277
+ [setQuery]
3065
2278
  );
3066
- }
3067
- const settingsGroupText = (t, group) => {
3068
- const fields = group.fields.map(
3069
- (field) => field.label ? t(field.label.messageId, field.label.defaultMessage) : field.key
3070
- ).join(", ");
3071
- return group.label ? t("adminPanel.activity.settingsGroup", "{tab}: {fields}", {
3072
- tab: t(group.label.messageId, group.label.defaultMessage),
3073
- fields
3074
- }) : fields;
3075
- };
3076
- const changedSettingsText = (t, keys, { limit } = {}) => {
3077
- const groups = groupChangedSettings(keys);
3078
- const total = groups.reduce((sum, group) => sum + group.fields.length, 0);
3079
- if (!total) return "";
3080
- let budget = limit && limit > 0 ? limit : total;
3081
- const shown = [];
3082
- for (const group of groups) {
3083
- if (budget <= 0) break;
3084
- shown.push({ ...group, fields: group.fields.slice(0, budget) });
3085
- budget -= Math.min(budget, group.fields.length);
3086
- }
3087
- const named = shown.reduce((sum, group) => sum + group.fields.length, 0);
3088
- const text = shown.map((group) => settingsGroupText(t, group)).join(" · ");
3089
- return named < total ? t("adminPanel.activity.settingsMore", "{names} and {count, number} more", {
3090
- names: text,
3091
- count: total - named
3092
- }) : text;
3093
- };
3094
- const changedSettingsLines = (t, keys) => groupChangedSettings(keys).map((group) => settingsGroupText(t, group));
3095
- const noAdminText = (t, row) => row?.event === "security-log.retention.purged" ? t("adminPanel.activity.system", "System") : t("adminPanel.activity.unknownAccount", "Unknown account");
3096
- const deviceText = (t, row) => {
3097
- if (row.browser && row.os) {
3098
- return t("adminPanel.activity.browserOnOs", "{browser} on {os}", {
3099
- browser: row.browser,
3100
- os: row.os
3101
- });
3102
- }
3103
- return row.browser || row.os || "";
3104
- };
3105
- const ipText = (t, row) => {
3106
- if (!row.ipAddress) return "";
3107
- return row.ipAnonymized ? t("adminPanel.activity.ipAnonymized", "{ip} (anonymised)", { ip: row.ipAddress }) : row.ipAddress;
3108
- };
3109
- const eventDetailText = (t, row, presentation, withActor) => {
3110
- const parts = [];
3111
- if (presentation.detail) {
3112
- parts.push(t(presentation.detail.messageId, presentation.detail.defaultMessage));
3113
- }
3114
- if (Number.isInteger(row.attempts) && row.attempts > 1) {
3115
- parts.push(
3116
- t(
3117
- "adminPanel.activity.attempts",
3118
- "{count, plural, one {# attempt} other {# attempts}} within 5 minutes",
3119
- { count: row.attempts }
3120
- )
3121
- );
3122
- }
3123
- const changed = changedSettingsText(t, row.change?.keys, { limit: 3 });
3124
- if (changed) parts.push(changed);
3125
- if (Number.isInteger(row.purge?.count)) {
3126
- parts.push(
3127
- Number.isInteger(row.purge?.retentionDays) ? t(
3128
- "adminPanel.activity.purgedDetail",
3129
- "{count, plural, one {# event} other {# events}}, older than {days, plural, one {# day} other {# days}}",
3130
- { count: row.purge.count, days: row.purge.retentionDays }
3131
- ) : t("adminPanel.activity.purgedCount", "{count, plural, one {# event} other {# events}}", {
3132
- count: row.purge.count
3133
- })
3134
- );
3135
- }
3136
- if (withActor && row.actor?.name) {
3137
- parts.push(t("adminPanel.activity.byAdmin", "by {name}", { name: row.actor.name }));
3138
- }
3139
- return parts.join(" · ");
3140
- };
3141
- const contentTypeText = (row) => [row.contentType?.name, row.entry?.locale].filter(Boolean).join(" · ");
3142
- const useT$3 = () => {
3143
- const { formatMessage } = useIntl();
3144
- return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
3145
- };
3146
- const SHORT_DATE = Object.freeze({ dateStyle: "medium", timeStyle: "short" });
3147
- const FULL_DATE = Object.freeze({ dateStyle: "full", timeStyle: "medium" });
3148
- const EVENT_ICONS = Object.freeze({
3149
- signIn: CheckCircle,
3150
- failed: CrossCircle,
3151
- lockout: Lock,
3152
- signOut: SignOut,
3153
- revoked: Shield,
3154
- settings: Cog,
3155
- logRead: Key,
3156
- purged: Trash,
3157
- refused: CrossCircle,
3158
- unlock: Lock,
3159
- limit: Stack,
3160
- password: Key,
3161
- device: Monitor,
3162
- travel: Earth,
3163
- notMe: WarningCircle,
3164
- export: Download,
3165
- impersonation: User,
3166
- webhook: Webhooks,
3167
- other: Information
3168
- });
3169
- const ICON_FILL = Object.freeze({
3170
- success: "success600",
3171
- danger: "danger600",
3172
- warning: "warning700",
3173
- secondary: "secondary600",
3174
- neutral: "neutral600"
3175
- });
3176
- const stopCellKeys = (event) => {
3177
- if (event.key === "Enter" || event.key === " " || event.key === "Spacebar") {
3178
- event.stopPropagation();
3179
- }
3180
- };
3181
- const ClickableRow = styled(Tr)`
3182
- cursor: pointer;
3183
- `;
3184
- const WrapCell = styled(Td)`
3185
- white-space: normal;
3186
- `;
3187
- const NoWrap = styled.span`
3188
- white-space: nowrap;
3189
- `;
3190
- const NameButton = styled(TextButton)`
3191
- min-height: 3.2rem;
3192
- text-align: start;
3193
- `;
3194
- const StackedList = styled.ul`
3195
- margin: 0;
3196
- padding: 0;
3197
- list-style: none;
3198
- border: 1px solid ${({ theme }) => theme.colors.neutral150};
3199
- border-radius: ${({ theme }) => theme.borderRadius};
3200
- background: ${({ theme }) => theme.colors.neutral0};
3201
- min-width: 0;
3202
-
3203
- & > li + li {
3204
- border-top: 1px solid ${({ theme }) => theme.colors.neutral150};
3205
- }
3206
- `;
3207
- const StackedItem = styled.li`
3208
- cursor: pointer;
3209
- min-width: 0;
3210
- `;
3211
- const BreakAnywhere = styled(Typography)`
3212
- overflow-wrap: anywhere;
3213
- `;
3214
- const getEventBadgeColors = (tone) => tone === "danger" ? { backgroundColor: "danger100", textColor: "danger700" } : getBadgeColors(tone);
3215
- const EventBadge = ({ presentation, nowrap = false }) => {
3216
- const t = useT$3();
3217
- const Icon = EVENT_ICONS[presentation.icon] || Information;
3218
- return /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", shrink: 0, "data-event-kind": presentation.key, children: [
3219
- /* @__PURE__ */ jsx(
3220
- Icon,
3221
- {
3222
- "aria-hidden": "true",
3223
- focusable: "false",
3224
- width: "1.6rem",
3225
- height: "1.6rem",
3226
- fill: ICON_FILL[presentation.tone] || ICON_FILL.neutral
3227
- }
3228
- ),
3229
- /* @__PURE__ */ jsx(Badge, { ...getEventBadgeColors(presentation.tone), "data-event-tone": presentation.tone, children: nowrap ? /* @__PURE__ */ jsx(NoWrap, { children: t(presentation.label.messageId, presentation.label.defaultMessage) }) : t(presentation.label.messageId, presentation.label.defaultMessage) })
3230
- ] });
3231
- };
3232
- const EventTime = ({ value, compact = false }) => {
3233
- const { formatDate, formatRelativeTime } = useSessionFormatters();
3234
- const date = toValidDate(value);
3235
- if (!date) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3236
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3237
- /* @__PURE__ */ jsx(
3238
- Typography,
3239
- {
3240
- tag: "time",
3241
- dateTime: date.toISOString(),
3242
- variant: compact ? "pi" : "omega",
3243
- textColor: "neutral800",
3244
- children: /* @__PURE__ */ jsx(NoWrap, { children: formatRelativeTime(date) })
3245
- }
3246
- ),
3247
- compact ? null : /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: /* @__PURE__ */ jsx(NoWrap, { children: formatDate(date, SHORT_DATE) }) })
3248
- ] });
3249
- };
3250
- const AdminName = ({ admin, row, onOpenAdmin }) => {
3251
- const t = useT$3();
3252
- if (!admin) {
3253
- return /* @__PURE__ */ jsx(Typography, { variant: onOpenAdmin ? "pi" : "omega", textColor: "neutral600", children: noAdminText(t, row) });
3254
- }
3255
- if (!onOpenAdmin) {
3256
- return /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: admin.name });
3257
- }
3258
- return /* @__PURE__ */ jsx(
3259
- NameButton,
2279
+ const handleClearFilters = () => {
2280
+ setQuery({ search: void 0, _q: void 0, status: void 0, reason: void 0, page: "1" });
2281
+ listHeadingRef.current?.focus();
2282
+ };
2283
+ const showSessionData = !loading && hasData;
2284
+ const showToolbar = showSessionData && stats.total > 0;
2285
+ const canExport = showSessionData && pageResult.total > 0 && !exporting;
2286
+ const filtersActive = hasActiveFilters(dashboard);
2287
+ const exportValues = { count: Math.min(pageResult.total, MAX_EXPORT_ROWS) };
2288
+ const exportMenu = /* @__PURE__ */ jsxs(
2289
+ SimpleMenu,
3260
2290
  {
3261
- onClick: (event) => {
3262
- event.stopPropagation();
3263
- onOpenAdmin(admin, event.currentTarget);
3264
- },
3265
- onKeyDown: stopCellKeys,
3266
- "aria-label": t("adminPanel.activity.openAdmin", "Open the details of {name}", {
3267
- name: admin.name
3268
- }),
3269
- children: admin.name
2291
+ label: t("homepage.export.label", "Export"),
2292
+ variant: "secondary",
2293
+ startIcon: /* @__PURE__ */ jsx(Download, {}),
2294
+ disabled: !canExport,
2295
+ children: [
2296
+ /* @__PURE__ */ jsx(MenuItem, { onSelect: () => void handleExport("csv"), children: t(
2297
+ "homepage.export.csv",
2298
+ "{count, plural, one {Export # session as CSV} other {Export # sessions as CSV}}",
2299
+ exportValues
2300
+ ) }),
2301
+ /* @__PURE__ */ jsx(MenuItem, { onSelect: () => void handleExport("json"), children: t(
2302
+ "homepage.export.json",
2303
+ "{count, plural, one {Export # session as JSON} other {Export # sessions as JSON}}",
2304
+ exportValues
2305
+ ) })
2306
+ ]
3270
2307
  }
3271
2308
  );
3272
- };
3273
- const SignInDetails = ({ row }) => {
3274
- const t = useT$3();
3275
- const ip = ipText(t, row);
3276
- const second = [getEventPlace(row), deviceText(t, row)].filter(Boolean).join(" · ");
3277
- if (!ip && !second) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3278
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3279
- ip ? /* @__PURE__ */ jsx(BreakAnywhere, { variant: "omega", textColor: "neutral800", children: ip }) : null,
3280
- second ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: second }) : null
3281
- ] });
3282
- };
3283
- const SessionState = ({ row }) => {
3284
- const t = useT$3();
3285
- const { formatRelativeTime } = useSessionFormatters();
3286
- const state = getSessionStatePresentation(row.session);
3287
- if (!state) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3288
- const endedAt = toValidDate(row.session?.endedAt);
3289
- const second = [
3290
- endedAt ? formatRelativeTime(endedAt) : "",
3291
- row.session?.endedBy?.name ? t("adminPanel.activity.byAdmin", "by {name}", { name: row.session.endedBy.name }) : ""
3292
- ].filter(Boolean).join(" · ");
3293
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3294
- /* @__PURE__ */ jsx(
3295
- Typography,
2309
+ const exportAction = canExport || !showSessionData ? exportMenu : /* @__PURE__ */ jsx(Tooltip, { label: t("homepage.export.disabledHint", "No sessions match the current filter."), children: /* @__PURE__ */ jsx("span", { children: exportMenu }) });
2310
+ const analyticsLabel = t("homepage.links.analytics", "Analytics");
2311
+ const settingsLabel = t("homepage.links.settings", "Settings");
2312
+ const primaryAction = /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", justifyContent: "flex-end", children: [
2313
+ isBelowSmall ? /* @__PURE__ */ jsx(IconButton, { tag: Link$1, to: ANALYTICS_PATH, label: analyticsLabel, variant: "tertiary", children: /* @__PURE__ */ jsx(ChartBubble, {}) }) : /* @__PURE__ */ jsx(
2314
+ LinkButton,
3296
2315
  {
3297
- variant: "omega",
3298
- fontWeight: state.tone === "success" ? "semiBold" : void 0,
3299
- textColor: state.tone === "success" ? "success600" : "neutral800",
3300
- "data-session-state": row.session?.state,
3301
- children: t(state.label.messageId, state.label.defaultMessage)
2316
+ tag: Link$1,
2317
+ to: ANALYTICS_PATH,
2318
+ variant: "tertiary",
2319
+ size: "S",
2320
+ startIcon: /* @__PURE__ */ jsx(ChartBubble, {}),
2321
+ children: analyticsLabel
3302
2322
  }
3303
2323
  ),
3304
- second ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: second }) : null
3305
- ] });
3306
- };
3307
- const HeaderCell = ({ children, hidden = false }) => /* @__PURE__ */ jsx(Th, { children: hidden ? /* @__PURE__ */ jsx(VisuallyHidden, { children }) : /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children }) });
3308
- const DetailsButton = ({ label, onOpen }) => /* @__PURE__ */ jsx(
3309
- IconButton,
3310
- {
3311
- variant: "ghost",
3312
- label,
3313
- withTooltip: false,
3314
- onClick: (event) => {
3315
- event.stopPropagation();
3316
- onOpen(event.currentTarget);
3317
- },
3318
- onKeyDown: stopCellKeys,
3319
- "data-event-details": "",
3320
- children: /* @__PURE__ */ jsx(Eye, {})
3321
- }
3322
- );
3323
- const ActivityEntry = ({ row }) => {
3324
- const t = useT$3();
3325
- const path = getEntryPath(row);
3326
- const name = row.entry?.count !== null && row.entry?.count !== void 0 ? t("adminPanel.activity.entries", "{count, plural, one {# entry} other {# entries}}", {
3327
- count: row.entry.count
3328
- }) : row.entry?.title || row.entry?.documentId || row.contentType?.name || "";
3329
- if (!name) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3330
- if (!path) {
3331
- return /* @__PURE__ */ jsx(BreakAnywhere, { variant: "omega", textColor: "neutral800", children: name });
3332
- }
3333
- return /* @__PURE__ */ jsx(
3334
- TargetLink$1,
3335
- {
3336
- tag: Link$1,
3337
- to: path,
3338
- onClick: (event) => event.stopPropagation(),
3339
- onKeyDown: stopCellKeys,
3340
- "aria-label": t("adminPanel.activity.openEntry", "Open {entry} in the Content Manager", {
3341
- entry: name
3342
- }),
3343
- children: name
3344
- }
3345
- );
3346
- };
3347
- const EventDetailsModal = ({ title, items, footerAction, onClose, onCloseAutoFocus }) => {
3348
- const t = useT$3();
3349
- return /* @__PURE__ */ jsx(Modal.Root, { open: true, onOpenChange: (open) => open ? null : onClose(), children: /* @__PURE__ */ jsxs(Modal.Content, { onCloseAutoFocus, "aria-describedby": void 0, children: [
3350
- /* @__PURE__ */ jsx(Modal.Header, { closeLabel: t("common.close", "Close"), children: /* @__PURE__ */ jsx(Modal.Title, { children: title }) }),
3351
- /* @__PURE__ */ jsx(Modal.Body, { children: /* @__PURE__ */ jsx(Box, { background: "neutral100", hasRadius: true, padding: { initial: 4, medium: 6 }, children: /* @__PURE__ */ jsx(PropertyList, { columns: 2, items }) }) }),
3352
- /* @__PURE__ */ jsxs(Modal.Footer, { children: [
3353
- /* @__PURE__ */ jsx(Modal.Close, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", children: t("common.close", "Close") }) }),
3354
- footerAction || null
3355
- ] })
3356
- ] }) });
3357
- };
3358
- const useEventDetails = () => {
3359
- const [selected, setSelected] = useState(null);
3360
- const [opener, setOpener] = useState(null);
3361
- const [container, setContainer] = useState(null);
3362
- return {
3363
- selected,
3364
- setContainer,
3365
- open: (row, trigger) => {
3366
- const button = trigger?.matches?.("[data-event-details]") ? trigger : trigger?.querySelector?.("[data-event-details]");
3367
- setOpener(button || null);
3368
- setSelected(row);
3369
- },
3370
- close: () => setSelected(null),
3371
- onCloseAutoFocus: (event) => restoreDialogFocus(event, opener, container)
3372
- };
3373
- };
3374
- const signInDetails = (t, formatDate, row) => {
3375
- const presentation = getSignInEventPresentation(row);
3376
- const label = t(presentation.label.messageId, presentation.label.defaultMessage);
3377
- const state = getSessionStatePresentation(row.session);
3378
- const revoked = presentation.key === "revoked";
3379
- const adminName = row.admin?.name || noAdminText(t, row);
3380
- const items = [
3381
- {
3382
- id: "event",
3383
- label: t("adminPanel.activity.column.event", "Event"),
3384
- render: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
3385
- /* @__PURE__ */ jsx(EventBadge, { presentation }),
3386
- presentation.detail ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(presentation.detail.messageId, presentation.detail.defaultMessage) }) : null
3387
- ] })
3388
- },
3389
- {
3390
- id: "time",
3391
- label: t("adminPanel.activity.details.exactTime", "Exact time"),
3392
- value: row.at ? formatDate(row.at, FULL_DATE) : null
3393
- },
3394
- { id: "admin", label: t("adminPanel.activity.column.admin", "Admin"), value: adminName }
3395
- ];
3396
- if (revoked) {
3397
- items.push(
2324
+ isBelowSmall ? /* @__PURE__ */ jsx(IconButton, { tag: Link$1, to: CONFIGURATION_PATH, label: settingsLabel, variant: "tertiary", children: /* @__PURE__ */ jsx(Cog, {}) }) : /* @__PURE__ */ jsx(
2325
+ LinkButton,
3398
2326
  {
3399
- id: "actor",
3400
- label: t("adminPanel.activity.column.doneBy", "Done by"),
3401
- value: row.actor?.name || null
3402
- },
2327
+ tag: Link$1,
2328
+ to: CONFIGURATION_PATH,
2329
+ variant: "tertiary",
2330
+ size: "S",
2331
+ startIcon: /* @__PURE__ */ jsx(Cog, {}),
2332
+ children: settingsLabel
2333
+ }
2334
+ ),
2335
+ exportAction
2336
+ ] });
2337
+ const filterSlot = isBelowMedium ? { flex: "1 1 auto", minWidth: 0 } : void 0;
2338
+ const filterControls = /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", wrap: isBelowMedium ? "nowrap" : "wrap", shrink: 0, children: [
2339
+ /* @__PURE__ */ jsx(Box, { ...filterSlot, children: /* @__PURE__ */ jsx(
2340
+ SingleSelect,
3403
2341
  {
3404
- id: "scope",
3405
- label: t("adminPanel.activity.details.signedOutOf", "Signed out of"),
3406
- value: Number.isInteger(row.sessionsEnded) && row.sessionsEnded >= 0 ? t(
3407
- "adminPanel.activity.details.scopeCount",
3408
- "{scope} ({count, plural, =0 {no open session} one {# session ended} other {# sessions ended}})",
3409
- {
3410
- scope: t(presentation.detail.messageId, presentation.detail.defaultMessage),
3411
- count: row.sessionsEnded
3412
- }
3413
- ) : t(presentation.detail.messageId, presentation.detail.defaultMessage)
2342
+ size: "S",
2343
+ "aria-label": t("homepage.filter.label", "Status"),
2344
+ value: dashboard.status,
2345
+ onChange: handleStatusChange,
2346
+ children: SESSION_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsxs(SingleSelectOption, { value: option, children: [
2347
+ option === "all" && t("homepage.filter.all", "All sessions"),
2348
+ option === "open" && t("homepage.filter.open", "Open"),
2349
+ option !== "all" && option !== "open" && formatters.statusLabel(option)
2350
+ ] }, option))
3414
2351
  }
3415
- );
3416
- }
3417
- if (state) {
3418
- const endedAt = toValidDate(row.session?.endedAt);
3419
- items.push({
3420
- id: "session",
3421
- label: t("adminPanel.activity.column.session", "Session"),
3422
- value: [
3423
- t(state.label.messageId, state.label.defaultMessage),
3424
- endedAt ? formatDate(endedAt, SHORT_DATE) : "",
3425
- row.session?.endedBy?.name ? t("adminPanel.activity.byAdmin", "by {name}", { name: row.session.endedBy.name }) : ""
3426
- ].filter(Boolean).join(" · ")
3427
- });
3428
- }
3429
- if (row.change) {
3430
- const lines = changedSettingsLines(t, row.change.keys);
3431
- items.push({
3432
- id: "settings",
3433
- label: t("adminPanel.activity.details.changedSettings", "Changed settings"),
3434
- ...lines.length ? {
3435
- render: /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "flex-start", gap: 1, "data-changed-settings": "", children: lines.map((line) => /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: line }, line)) })
3436
- } : { value: null },
3437
- fullWidth: true
3438
- });
3439
- }
3440
- if (row.purge) {
3441
- items.push(
2352
+ ) }),
2353
+ dashboard.status === "ended" ? /* @__PURE__ */ jsx(Box, { ...filterSlot, children: /* @__PURE__ */ jsx(
2354
+ SingleSelect,
3442
2355
  {
3443
- id: "purged",
3444
- label: t("adminPanel.activity.details.deleted", "Deleted events"),
3445
- value: Number.isInteger(row.purge.count) ? row.purge.count : null
3446
- },
2356
+ size: "S",
2357
+ "aria-label": t("homepage.filter.reasonLabel", "End reason"),
2358
+ value: dashboard.reason,
2359
+ onChange: handleReasonChange,
2360
+ children: END_REASON_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: option === "all" ? t("homepage.filter.allReasons", "All reasons") : formatters.endReasonLabel(option) }, option))
2361
+ }
2362
+ ) }) : null,
2363
+ /* @__PURE__ */ jsx(
2364
+ IconButton,
3447
2365
  {
3448
- id: "retention",
3449
- label: t("adminPanel.activity.details.retention", "Kept for"),
3450
- value: Number.isInteger(row.purge.retentionDays) ? t("adminPanel.duration.days", "{count, plural, one {# day} other {# days}}", {
3451
- count: row.purge.retentionDays
3452
- }) : null
2366
+ label: t("homepage.actions.refresh", "Refresh sessions"),
2367
+ onClick: () => fetchSessions(),
2368
+ children: /* @__PURE__ */ jsx(ArrowClockwise, {})
3453
2369
  }
3454
- );
3455
- }
3456
- if (Number.isInteger(row.attempts) && row.attempts > 1) {
3457
- items.push({
3458
- id: "attempts",
3459
- label: t("adminPanel.activity.details.attempts", "Attempts"),
3460
- value: row.attempts
3461
- });
3462
- }
3463
- items.push(
3464
- {
3465
- id: "ip",
3466
- label: t("adminPanel.activity.details.ip", "IP address"),
3467
- value: ipText(t, row) || null,
3468
- kind: "id"
3469
- },
3470
- {
3471
- id: "place",
3472
- label: t("adminPanel.activity.details.location", "Location"),
3473
- value: getEventPlace(row) || null
3474
- },
3475
- {
3476
- id: "browser",
3477
- label: t("adminPanel.activity.details.browser", "Browser"),
3478
- value: row.browser || null
3479
- },
3480
- {
3481
- id: "os",
3482
- label: t("adminPanel.activity.details.os", "Operating system"),
3483
- value: row.os || null
3484
- },
3485
- {
3486
- id: "userAgent",
3487
- label: t("adminPanel.activity.details.userAgent", "User agent"),
3488
- value: row.userAgent || null,
3489
- kind: "id",
3490
- fullWidth: true
3491
- },
2370
+ )
2371
+ ] });
2372
+ const toolbar = /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-session-toolbar": "", children: /* @__PURE__ */ jsxs(
2373
+ Flex,
3492
2374
  {
3493
- id: "eventId",
3494
- label: t("adminPanel.activity.details.eventId", "Event ID"),
3495
- value: row.id,
3496
- kind: "id"
2375
+ direction: { initial: "column", medium: "row" },
2376
+ alignItems: { initial: "stretch", medium: "center" },
2377
+ gap: 2,
2378
+ children: [
2379
+ /* @__PURE__ */ jsx(Flex, { flex: "1 1 auto", minWidth: 0, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsx(SessionSearch, { value: dashboard.search, onSearch: handleSearch }) }),
2380
+ filterControls
2381
+ ]
3497
2382
  }
3498
- );
3499
- const title = row.admin?.name ? t("adminPanel.activity.details.title", "{event}: {name}", { event: label, name: adminName }) : label;
3500
- const logEvent = ["settings", "log-read", "purged"].includes(presentation.key);
3501
- const deviceFields = /* @__PURE__ */ new Set(["ip", "place", "browser", "os", "userAgent"]);
3502
- return {
3503
- title,
3504
- items: logEvent ? items.filter(
3505
- (item) => !deviceFields.has(item.id) || item.value !== null && item.value !== ""
3506
- ) : items
3507
- };
3508
- };
3509
- const activityDetails = (t, formatDate, row) => {
3510
- const label = ACTIVITY_ACTION_LABELS[row.action] || ACTIVITY_ACTION_LABELS.view;
3511
- const action = t(label.messageId, label.defaultMessage);
3512
- return {
3513
- title: row.entry?.title ? t("adminPanel.activity.details.title", "{event}: {name}", {
3514
- event: action,
3515
- name: row.entry.title
3516
- }) : action,
3517
- items: [
3518
- {
3519
- id: "action",
3520
- label: t("adminPanel.activity.column.action", "Action"),
3521
- render: /* @__PURE__ */ jsx(Badge, { ...getBadgeColors(getActivityTone(row.action)), children: action })
3522
- },
3523
- {
3524
- id: "time",
3525
- label: t("adminPanel.activity.details.exactTime", "Exact time"),
3526
- value: row.at ? formatDate(row.at, FULL_DATE) : null
3527
- },
3528
- {
3529
- id: "entry",
3530
- label: t("adminPanel.activity.column.entry", "Entry"),
3531
- render: /* @__PURE__ */ jsx(ActivityEntry, { row })
3532
- },
3533
- {
3534
- id: "admin",
3535
- label: t("adminPanel.activity.column.admin", "Admin"),
3536
- value: row.admin?.name || null
3537
- },
3538
- {
3539
- id: "type",
3540
- label: t("adminPanel.activity.column.contentType", "Content type"),
3541
- value: row.contentType?.name || null
3542
- },
3543
- {
3544
- id: "uid",
3545
- label: t("adminPanel.activity.details.uid", "Content type UID"),
3546
- value: row.contentType?.uid || null,
3547
- kind: "id"
3548
- },
3549
- {
3550
- id: "documentId",
3551
- label: t("adminPanel.activity.details.documentId", "Document ID"),
3552
- value: row.entry?.documentId || null,
3553
- kind: "id"
3554
- },
3555
- {
3556
- id: "locale",
3557
- label: t("adminPanel.activity.details.locale", "Locale"),
3558
- value: row.entry?.locale || null
3559
- },
3560
- {
3561
- id: "eventId",
3562
- label: t("adminPanel.activity.details.eventId", "Event ID"),
3563
- value: row.id,
3564
- kind: "id"
3565
- }
3566
- ]
2383
+ ) });
2384
+ const lastUpdatedLine = lastUpdated ? /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", wrap: "wrap", justifyContent: "flex-end", children: [
2385
+ refreshing ? /* @__PURE__ */ jsx(Loader, { small: true, role: "status", "aria-live": "polite", children: t("homepage.refreshing", "Updating sessions") }) : null,
2386
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", "data-last-updated": "", children: t("homepage.lastUpdated", "Last updated {time}", {
2387
+ time: formatters.formatRelativeTime(lastUpdated, now)
2388
+ }) })
2389
+ ] }) : null;
2390
+ const listProps = {
2391
+ sessions: pageResult.items,
2392
+ labelledBy: listHeadingId,
2393
+ busy: refreshing,
2394
+ onView: handleSessionClick,
2395
+ onEnd: handleTerminateSession,
2396
+ onDelete: handleDeleteSession,
2397
+ mutationPending,
2398
+ getFocusFallback
3567
2399
  };
3568
- };
3569
- const SignInEventTable = ({
3570
- rows,
3571
- label,
3572
- showAdmin = false,
3573
- onOpenAdmin,
3574
- detailsAction,
3575
- busy = false
3576
- }) => {
3577
- const t = useT$3();
3578
- const { formatDate, formatRelativeTime } = useSessionFormatters();
3579
- const [measureRef, width] = useElementWidth();
3580
- const {
3581
- selected,
3582
- open: openDetails,
3583
- close: closeDetails,
3584
- onCloseAutoFocus,
3585
- setContainer
3586
- } = useEventDetails();
3587
- const layout = getEventListLayout(width, { showAdmin });
3588
- const showDoneBy = layout === "full";
3589
- const detailsLabel = (row, presentation) => t("adminPanel.activity.details.open", "Details of {event}, {time}", {
3590
- event: t(presentation.label.messageId, presentation.label.defaultMessage),
3591
- time: formatRelativeTime(row.at)
2400
+ const statusCard = (status) => ({
2401
+ onClick: () => handleStatusChange(status),
2402
+ pressed: dashboard.status === status
3592
2403
  });
3593
- let list;
3594
- if (layout === "stacked") {
3595
- list = /* @__PURE__ */ jsx(StackedList, { "aria-label": label, "data-event-list": "stacked", children: rows.map((row) => {
3596
- const presentation = getSignInEventPresentation(row);
3597
- const state = getSessionStatePresentation(row.session);
3598
- const second = [
3599
- eventDetailText(t, row, presentation, true),
3600
- ipText(t, row),
3601
- getEventPlace(row),
3602
- deviceText(t, row),
3603
- state ? t(state.label.messageId, state.label.defaultMessage) : ""
3604
- ].filter(Boolean).join(" · ");
3605
- return /* @__PURE__ */ jsx(
3606
- StackedItem,
2404
+ return /* @__PURE__ */ jsx(
2405
+ PageShell,
2406
+ {
2407
+ headingId: "magic-sessionmanager-dashboard-title",
2408
+ title: t("homepage.title", "Sessions"),
2409
+ subtitle: t(
2410
+ "homepage.subtitle",
2411
+ "Sign-ins of your app’s users (Users & Permissions). Strapi administrators are not listed."
2412
+ ),
2413
+ primaryAction,
2414
+ children: /* @__PURE__ */ jsxs(
2415
+ Flex,
3607
2416
  {
3608
- "data-event-row": presentation.key,
3609
- "data-event-id": row.id,
3610
- onClick: (event) => openDetails(row, event.currentTarget),
3611
- children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, padding: 3, minWidth: 0, children: [
3612
- /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", alignItems: "center", minWidth: 0, children: [
3613
- /* @__PURE__ */ jsx(EventBadge, { presentation }),
3614
- /* @__PURE__ */ jsxs(Flex, { gap: 1, alignItems: "center", marginLeft: "auto", children: [
3615
- /* @__PURE__ */ jsx(EventTime, { value: row.at, compact: true }),
2417
+ ref: dashboardRef,
2418
+ tabIndex: -1,
2419
+ direction: "column",
2420
+ alignItems: "stretch",
2421
+ gap: 6,
2422
+ minWidth: 0,
2423
+ children: [
2424
+ /* @__PURE__ */ jsx(SessionViewNav, { current: "users" }),
2425
+ !loading && loadError ? /* @__PURE__ */ jsx(
2426
+ PersistentAlert,
2427
+ {
2428
+ variant: "danger",
2429
+ closeLabel: t("common.close", "Close"),
2430
+ action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: fetchSessions, children: t("common.tryAgain", "Try again") }),
2431
+ children: /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "span", children: t("homepage.error.load", "Sessions could not be loaded.") })
2432
+ }
2433
+ ) : null,
2434
+ showSessionData && stats.nativeOnly > 0 ? /* @__PURE__ */ jsx(
2435
+ UntrackedSessionsNotice,
2436
+ {
2437
+ stats,
2438
+ onChanged: fetchSessions,
2439
+ fallbackFocusRef: dashboardRef
2440
+ }
2441
+ ) : null,
2442
+ loading ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 8, children: /* @__PURE__ */ jsx(Loader, { children: t("homepage.loading", "Loading sessions") }) }) : null,
2443
+ showSessionData && stats.total > 0 ? /* @__PURE__ */ jsx(HowSessionsWork, {}) : null,
2444
+ showSessionData && /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
2445
+ /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx(Typography, { tag: "h2", children: t("homepage.stats.label", "Session statistics") }) }),
2446
+ /* @__PURE__ */ jsxs(StatGrid, { label: t("homepage.stats.label", "Session statistics"), children: [
2447
+ /* @__PURE__ */ jsx(
2448
+ StatCard,
2449
+ {
2450
+ icon: Check,
2451
+ tone: "success",
2452
+ label: t("homepage.stats.active", "Active sessions"),
2453
+ value: stats.active,
2454
+ description: t(
2455
+ "homepage.stats.usersOnline",
2456
+ "{count, plural, one {# user online} other {# users online}}",
2457
+ {
2458
+ count: stats.usersOnline
2459
+ }
2460
+ ),
2461
+ ...statusCard("active")
2462
+ }
2463
+ ),
2464
+ /* @__PURE__ */ jsx(
2465
+ StatCard,
2466
+ {
2467
+ icon: Clock,
2468
+ tone: "warning",
2469
+ label: t("homepage.stats.idle", "Idle sessions"),
2470
+ value: stats.idle,
2471
+ ...statusCard("idle")
2472
+ }
2473
+ ),
2474
+ /* @__PURE__ */ jsx(
2475
+ StatCard,
2476
+ {
2477
+ icon: Cross,
2478
+ tone: "neutral",
2479
+ label: t("homepage.stats.ended", "Ended sessions"),
2480
+ value: stats.ended,
2481
+ description: t(
2482
+ "homepage.stats.endedBreakdown",
2483
+ "{loggedOut, number} logged out · {timedOut, number} timed out · {other, number} other reasons",
2484
+ {
2485
+ loggedOut: stats.loggedOut,
2486
+ timedOut: stats.timedOut,
2487
+ other: stats.otherReasons
2488
+ }
2489
+ ),
2490
+ ...statusCard("ended")
2491
+ }
2492
+ ),
3616
2493
  /* @__PURE__ */ jsx(
3617
- DetailsButton,
2494
+ StatCard,
3618
2495
  {
3619
- label: detailsLabel(row, presentation),
3620
- onOpen: (trigger) => openDetails(row, trigger)
2496
+ icon: User,
2497
+ tone: "primary",
2498
+ label: t("homepage.stats.total", "All sessions"),
2499
+ value: stats.total,
2500
+ ...statusCard("all")
3621
2501
  }
3622
2502
  )
3623
2503
  ] })
3624
2504
  ] }),
3625
- showAdmin ? /* @__PURE__ */ jsx(Flex, { minWidth: 0, children: /* @__PURE__ */ jsx(AdminName, { admin: row.admin, row, onOpenAdmin }) }) : null,
3626
- second ? /* @__PURE__ */ jsx(BreakAnywhere, { variant: "pi", textColor: "neutral600", children: second }) : null
3627
- ] })
3628
- },
3629
- row.id
3630
- );
3631
- }) });
3632
- } else {
3633
- const colCount = 5 + (showAdmin ? 1 : 0) + (showDoneBy ? 1 : 0);
3634
- list = /* @__PURE__ */ jsx(Box, { background: "neutral0", hasRadius: true, shadow: "tableShadow", "data-event-list": layout, children: /* @__PURE__ */ jsxs(Table, { colCount, rowCount: rows.length + 1, "aria-label": label, "aria-busy": busy, children: [
3635
- /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
3636
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.time", "Time") }),
3637
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.event", "Event") }),
3638
- showAdmin ? /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.admin", "Admin") }) : null,
3639
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.details", "IP address and device") }),
3640
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.session", "Session") }),
3641
- showDoneBy ? /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.doneBy", "Done by") }) : null,
3642
- /* @__PURE__ */ jsx(HeaderCell, { hidden: true, children: t("adminPanel.table.actions", "Actions") })
3643
- ] }) }),
3644
- /* @__PURE__ */ jsx(Tbody, { children: rows.map((row) => {
3645
- const presentation = getSignInEventPresentation(row);
3646
- const eventDetail = eventDetailText(t, row, presentation, !showDoneBy);
3647
- return /* @__PURE__ */ jsxs(
3648
- ClickableRow,
3649
- {
3650
- "data-event-row": presentation.key,
3651
- "data-event-id": row.id,
3652
- onClick: (event) => openDetails(row, event.currentTarget),
3653
- children: [
3654
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(EventTime, { value: row.at }) }),
3655
- /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3656
- /* @__PURE__ */ jsx(EventBadge, { presentation, nowrap: true }),
3657
- eventDetail ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: eventDetail }) : null
3658
- ] }) }),
3659
- showAdmin ? /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsx(AdminName, { admin: row.admin, row, onOpenAdmin }) }) : null,
3660
- /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsx(SignInDetails, { row }) }),
3661
- /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsx(SessionState, { row }) }),
3662
- showDoneBy ? /* @__PURE__ */ jsx(WrapCell, { children: row.actor?.name ? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: row.actor.name }) : /* @__PURE__ */ jsx(MissingValue, { variant: "omega" }) }) : null,
3663
- /* @__PURE__ */ jsx(Td, { onClick: (event) => event.stopPropagation(), children: /* @__PURE__ */ jsx(Flex, { justifyContent: "flex-end", gap: 1, onKeyDown: stopCellKeys, children: /* @__PURE__ */ jsx(
3664
- DetailsButton,
3665
- {
3666
- label: detailsLabel(row, presentation),
3667
- onOpen: (trigger) => openDetails(row, trigger)
3668
- }
3669
- ) }) })
3670
- ]
3671
- },
3672
- row.id
3673
- );
3674
- }) })
3675
- ] }) });
3676
- }
3677
- const content = selected ? signInDetails(t, formatDate, selected) : null;
3678
- return /* @__PURE__ */ jsxs(Box, { ref: measureRef, minWidth: 0, width: "100%", children: [
3679
- /* @__PURE__ */ jsx(Box, { ref: setContainer, tabIndex: -1, minWidth: 0, children: list }),
3680
- content ? /* @__PURE__ */ jsx(
3681
- EventDetailsModal,
3682
- {
3683
- title: content.title,
3684
- items: content.items,
3685
- footerAction: detailsAction ? detailsAction(selected, closeDetails) : null,
3686
- onClose: closeDetails,
3687
- onCloseAutoFocus
3688
- }
3689
- ) : null
3690
- ] });
3691
- };
3692
- const ActivityEventTable = ({ rows, label, showAdmin = false, busy = false }) => {
3693
- const t = useT$3();
3694
- const { formatDate, formatRelativeTime } = useSessionFormatters();
3695
- const [measureRef, width] = useElementWidth();
3696
- const {
3697
- selected,
3698
- open: openDetails,
3699
- close: closeDetails,
3700
- onCloseAutoFocus,
3701
- setContainer
3702
- } = useEventDetails();
3703
- const layout = getEventListLayout(width, { showAdmin });
3704
- const actionOf = (row) => {
3705
- const entry = ACTIVITY_ACTION_LABELS[row.action] || ACTIVITY_ACTION_LABELS.view;
3706
- return t(entry.messageId, entry.defaultMessage);
3707
- };
3708
- const detailsLabel = (row) => t("adminPanel.activity.details.open", "Details of {event}, {time}", {
3709
- event: actionOf(row),
3710
- time: formatRelativeTime(row.at)
3711
- });
3712
- const badge = (row) => /* @__PURE__ */ jsx(
3713
- Badge,
3714
- {
3715
- ...getBadgeColors(getActivityTone(row.action)),
3716
- "data-event-tone": getActivityTone(row.action),
3717
- children: actionOf(row)
3718
- }
3719
- );
3720
- let list;
3721
- if (layout === "stacked") {
3722
- list = /* @__PURE__ */ jsx(StackedList, { "aria-label": label, "data-event-list": "stacked", children: rows.map((row) => /* @__PURE__ */ jsx(
3723
- StackedItem,
3724
- {
3725
- "data-event-row": row.action,
3726
- "data-event-id": row.id,
3727
- onClick: (event) => openDetails(row, event.currentTarget),
3728
- children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, padding: 3, minWidth: 0, children: [
3729
- /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", alignItems: "center", minWidth: 0, children: [
3730
- badge(row),
3731
- /* @__PURE__ */ jsxs(Flex, { gap: 1, alignItems: "center", marginLeft: "auto", children: [
3732
- /* @__PURE__ */ jsx(EventTime, { value: row.at, compact: true }),
3733
- /* @__PURE__ */ jsx(
3734
- DetailsButton,
2505
+ showToolbar && /* @__PURE__ */ jsxs(Flex, { ref: listWidthRef, direction: "column", alignItems: "stretch", gap: 4, minWidth: 0, children: [
2506
+ /* @__PURE__ */ jsx(VisuallyHidden, { children: /* @__PURE__ */ jsx(Typography, { variant: "delta", tag: "h2", children: t("homepage.list.heading", "Session list") }) }),
2507
+ toolbar,
2508
+ /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", gap: 4, wrap: "wrap", children: [
2509
+ /* @__PURE__ */ jsx(
2510
+ Typography,
2511
+ {
2512
+ id: listHeadingId,
2513
+ ref: listHeadingRef,
2514
+ tabIndex: -1,
2515
+ variant: "pi",
2516
+ textColor: "neutral600",
2517
+ "aria-live": "polite",
2518
+ "data-session-caption": "",
2519
+ children: pageResult.total > 0 ? t(
2520
+ "homepage.caption",
2521
+ "{from, number}–{to, number} of {total, plural, one {# session} other {# sessions}}",
2522
+ {
2523
+ from: pageResult.startIndex,
2524
+ to: pageResult.endIndex,
2525
+ total: pageResult.total
2526
+ }
2527
+ ) : t("homepage.captionNone", "0 sessions")
2528
+ }
2529
+ ),
2530
+ lastUpdatedLine
2531
+ ] }),
2532
+ pageResult.total > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
2533
+ isBelowMedium ? /* @__PURE__ */ jsx(SessionCardList, { ...listProps }) : /* @__PURE__ */ jsx(
2534
+ SessionTable,
2535
+ {
2536
+ ...listProps,
2537
+ compact: shouldUseCompactTable(listWidth, isBelowLarge)
2538
+ }
2539
+ ),
2540
+ /* @__PURE__ */ jsx(PaginationTargets$3, { children: /* @__PURE__ */ jsxs(
2541
+ Pagination.Root,
2542
+ {
2543
+ pageCount: pageResult.pageCount,
2544
+ total: pageResult.total,
2545
+ defaultPageSize: Number(DEFAULT_PAGE_SIZE),
2546
+ children: [
2547
+ /* @__PURE__ */ jsx(Pagination.PageSize, { options: [...PAGE_SIZE_OPTIONS] }),
2548
+ /* @__PURE__ */ jsx(Pagination.Links, {})
2549
+ ]
2550
+ }
2551
+ ) })
2552
+ ] }) : /* @__PURE__ */ jsx(
2553
+ EmptyStateLayout,
3735
2554
  {
3736
- label: detailsLabel(row),
3737
- onOpen: (trigger) => openDetails(row, trigger)
2555
+ icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem", "aria-hidden": "true" }),
2556
+ content: t(
2557
+ "homepage.noResults.description",
2558
+ "No sessions match your search or filter."
2559
+ ),
2560
+ action: filtersActive ? /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: handleClearFilters, children: t("homepage.noResults.reset", "Clear filters") }) : null
3738
2561
  }
3739
2562
  )
3740
- ] })
3741
- ] }),
3742
- /* @__PURE__ */ jsx(Flex, { minWidth: 0, children: /* @__PURE__ */ jsx(ActivityEntry, { row }) }),
3743
- contentTypeText(row) || showAdmin && row.admin?.name ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: [contentTypeText(row), showAdmin ? row.admin?.name : ""].filter(Boolean).join(" · ") }) : null
3744
- ] })
3745
- },
3746
- row.id
3747
- )) });
3748
- } else {
3749
- const colCount = 5 + (showAdmin ? 1 : 0);
3750
- list = /* @__PURE__ */ jsx(Box, { background: "neutral0", hasRadius: true, shadow: "tableShadow", "data-event-list": layout, children: /* @__PURE__ */ jsxs(Table, { colCount, rowCount: rows.length + 1, "aria-label": label, "aria-busy": busy, children: [
3751
- /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
3752
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.time", "Time") }),
3753
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.action", "Action") }),
3754
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.entry", "Entry") }),
3755
- /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.contentType", "Content type") }),
3756
- showAdmin ? /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.admin", "Admin") }) : null,
3757
- /* @__PURE__ */ jsx(HeaderCell, { hidden: true, children: t("adminPanel.table.actions", "Actions") })
3758
- ] }) }),
3759
- /* @__PURE__ */ jsx(Tbody, { children: rows.map((row) => /* @__PURE__ */ jsxs(
3760
- ClickableRow,
3761
- {
3762
- "data-event-row": row.action,
3763
- "data-event-id": row.id,
3764
- onClick: (event) => openDetails(row, event.currentTarget),
3765
- children: [
3766
- /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(EventTime, { value: row.at }) }),
3767
- /* @__PURE__ */ jsx(Td, { children: badge(row) }),
3768
- /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsx(ActivityEntry, { row }) }),
3769
- /* @__PURE__ */ jsx(WrapCell, { children: contentTypeText(row) ? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: contentTypeText(row) }) : /* @__PURE__ */ jsx(MissingValue, { variant: "omega" }) }),
3770
- showAdmin ? /* @__PURE__ */ jsx(WrapCell, { children: /* @__PURE__ */ jsx(AdminName, { admin: row.admin }) }) : null,
3771
- /* @__PURE__ */ jsx(Td, { onClick: (event) => event.stopPropagation(), children: /* @__PURE__ */ jsx(Flex, { justifyContent: "flex-end", gap: 1, onKeyDown: stopCellKeys, children: /* @__PURE__ */ jsx(
3772
- DetailsButton,
2563
+ ] }),
2564
+ showSessionData && stats.total === 0 && /* @__PURE__ */ jsx(
2565
+ EmptyStateLayout,
2566
+ {
2567
+ icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem", "aria-hidden": "true" }),
2568
+ content: t(
2569
+ "homepage.empty.description",
2570
+ "No sessions yet. Sessions appear here when users of your app sign in."
2571
+ )
2572
+ }
2573
+ ),
2574
+ /* @__PURE__ */ jsx(RecentUserActivity, {}),
2575
+ showDetailModal && selectedSession && /* @__PURE__ */ jsx(
2576
+ SessionDetailModal,
3773
2577
  {
3774
- label: detailsLabel(row),
3775
- onOpen: (trigger) => openDetails(row, trigger)
2578
+ session: selectedSession,
2579
+ now,
2580
+ onClose: handleModalClose,
2581
+ onCloseAutoFocus: handleCloseAutoFocus,
2582
+ onEndSession: handleTerminateSession
3776
2583
  }
3777
- ) }) })
2584
+ )
3778
2585
  ]
3779
- },
3780
- row.id
3781
- )) })
3782
- ] }) });
3783
- }
3784
- const content = selected ? activityDetails(t, formatDate, selected) : null;
3785
- return /* @__PURE__ */ jsxs(Box, { ref: measureRef, minWidth: 0, width: "100%", children: [
3786
- /* @__PURE__ */ jsx(Box, { ref: setContainer, tabIndex: -1, minWidth: 0, children: list }),
3787
- content ? /* @__PURE__ */ jsx(
3788
- EventDetailsModal,
3789
- {
3790
- title: content.title,
3791
- items: content.items,
3792
- onClose: closeDetails,
3793
- onCloseAutoFocus
3794
- }
3795
- ) : null
3796
- ] });
3797
- };
3798
- function useEventList({ path, params, logKey }) {
3799
- const { get } = useFetchClient();
3800
- const { formatMessage } = useIntl();
3801
- const fillNames = useCallback(
3802
- (list) => list.map(
3803
- (row) => withEventAdminNames(
3804
- row,
3805
- (id) => formatMessage(
3806
- {
3807
- id: getTranslation("adminPanel.identity.placeholder"),
3808
- defaultMessage: "Admin #{id}"
3809
- },
3810
- { id }
3811
- )
3812
- )
3813
- ),
3814
- [formatMessage]
3815
- );
3816
- const [rows, setRows] = useState([]);
3817
- const [meta, setMeta] = useState(null);
3818
- const [page, setPage] = useState(1);
3819
- const [loading, setLoading] = useState(true);
3820
- const [loadingMore, setLoadingMore] = useState(false);
3821
- const [error, setError] = useState(false);
3822
- const requestRef = useRef(0);
3823
- const key = JSON.stringify(params);
3824
- const firstPage = Number(params?.page) > 0 ? Number(params.page) : 1;
3825
- const load = useCallback(
3826
- async (nextPage) => {
3827
- const requestId = requestRef.current + 1;
3828
- requestRef.current = requestId;
3829
- if (nextPage === firstPage) setLoading(true);
3830
- else setLoadingMore(true);
3831
- try {
3832
- const response = await get(path, { params: { ...JSON.parse(key), page: nextPage } });
3833
- if (requestId !== requestRef.current) return;
3834
- const body = response?.data || {};
3835
- const data = fillNames(Array.isArray(body.data) ? body.data : []);
3836
- setRows((current) => nextPage === firstPage ? data : [...current, ...data]);
3837
- setMeta(body.meta || null);
3838
- setPage(nextPage);
3839
- setError(false);
3840
- } catch (err) {
3841
- if (requestId !== requestRef.current || isCancelledRequest(err)) return;
3842
- setError(true);
3843
- logSafeAdminError(logKey, err);
3844
- } finally {
3845
- if (requestId === requestRef.current) {
3846
- setLoading(false);
3847
- setLoadingMore(false);
3848
- }
3849
- }
3850
- },
3851
- [get, path, key, logKey, fillNames, firstPage]
3852
- );
3853
- useEffect(() => {
3854
- load(firstPage);
3855
- return () => {
3856
- requestRef.current += 1;
3857
- };
3858
- }, [load, firstPage]);
3859
- const pagination = meta?.pagination;
3860
- const hasMore = Boolean(pagination && page < pagination.pageCount);
3861
- const exportAll = useCallback(async () => {
3862
- const all = [];
3863
- let cursor = null;
3864
- do {
3865
- const response = await get(`${path}/export`, {
3866
- params: toExportParams(JSON.parse(key), cursor)
3867
- });
3868
- const body = response?.data || {};
3869
- if (!Array.isArray(body.data)) throw new Error("Invalid export response");
3870
- all.push(...fillNames(body.data));
3871
- cursor = typeof body.meta?.nextCursor === "string" ? body.meta.nextCursor : null;
3872
- } while (cursor && all.length < MAX_EVENT_EXPORT_ROWS);
3873
- return {
3874
- rows: all.slice(0, MAX_EVENT_EXPORT_ROWS),
3875
- capped: all.length > MAX_EVENT_EXPORT_ROWS || Boolean(cursor)
3876
- };
3877
- }, [get, path, key, fillNames]);
3878
- return {
3879
- rows,
3880
- meta,
3881
- loading,
3882
- loadingMore,
3883
- error,
3884
- hasMore,
3885
- loadMore: () => load(page + 1),
3886
- reload: () => load(firstPage),
3887
- exportAll
3888
- };
3889
- }
3890
- function downloadCsv(content, name) {
3891
- const blob = new Blob([content], { type: "text/csv;charset=utf-8;" });
3892
- const url = URL.createObjectURL(blob);
3893
- const link = document.createElement("a");
3894
- link.href = url;
3895
- link.download = `${name}-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.csv`;
3896
- link.click();
3897
- window.setTimeout(() => URL.revokeObjectURL(url), 0);
3898
- }
3899
- const ADMIN_ACTIVITY_SETTINGS_PATH = `/settings/${pluginId}/general?tab=admin-activity`;
3900
- const ADMIN_ACTIVITY_PAGE_PATH = `/plugins/${pluginId}/admin-panel/activity`;
3901
- const useT$2 = () => {
3902
- const { formatMessage } = useIntl();
3903
- return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
3904
- };
3905
- const PeriodSelect = ({ value, onChange }) => {
3906
- const t = useT$2();
3907
- const labels = {
3908
- 1: t("adminPanel.activity.period.day", "Last 24 hours"),
3909
- 7: t("adminPanel.activity.period.week", "Last 7 days"),
3910
- 30: t("adminPanel.activity.period.month", "Last 30 days"),
3911
- 90: t("adminPanel.activity.period.quarter", "Last 90 days"),
3912
- all: t("adminPanel.activity.period.all", "All kept events")
3913
- };
3914
- return /* @__PURE__ */ jsx(
3915
- SingleSelect,
3916
- {
3917
- size: "S",
3918
- "aria-label": t("adminPanel.activity.period.label", "Period"),
3919
- value,
3920
- onChange: (next) => onChange(String(next)),
3921
- children: PERIOD_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: labels[option] }, option))
3922
- }
3923
- );
3924
- };
3925
- const FilterSlot = ({ children }) => /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", minWidth: 0, flex: "1 1 18rem", children });
3926
- const EmptyText = ({ children }) => /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", "data-event-empty": "", children });
3927
- const EventList = ({
3928
- filters,
3929
- notice,
3930
- list,
3931
- empty,
3932
- renderList,
3933
- toCsv: toCsv2,
3934
- fileName,
3935
- exportLabel,
3936
- footer
3937
- }) => {
3938
- const t = useT$2();
3939
- const { toggleNotification } = useNotification();
3940
- const [exporting, setExporting] = useState(false);
3941
- const total = list.meta?.pagination?.total ?? 0;
3942
- const handleExport = async () => {
3943
- if (exporting) return;
3944
- setExporting(true);
3945
- try {
3946
- const { rows, capped } = await list.exportAll();
3947
- downloadCsv(toCsv2(rows), fileName);
3948
- if (capped) {
3949
- toggleNotification({
3950
- type: "warning",
3951
- message: t(
3952
- "adminPanel.activity.export.capped",
3953
- "The export contains the newest {limit, number} events. Narrow the filter to export the rest.",
3954
- { limit: MAX_EVENT_EXPORT_ROWS }
3955
- )
3956
- });
3957
- }
3958
- } catch (err) {
3959
- if (isCancelledRequest(err)) return;
3960
- logSafeAdminError("adminPanel.activity.export", err);
3961
- toggleNotification({
3962
- type: "danger",
3963
- message: t("adminPanel.activity.export.error", "The export could not be created.")
3964
- });
3965
- } finally {
3966
- setExporting(false);
3967
- }
3968
- };
3969
- return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, minWidth: 0, children: [
3970
- /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", alignItems: "center", justifyContent: "space-between", children: [
3971
- /* @__PURE__ */ jsx(Flex, { gap: 2, wrap: "wrap", alignItems: "center", flex: "1 1 auto", minWidth: 0, children: filters }),
3972
- /* @__PURE__ */ jsx(
3973
- Button,
3974
- {
3975
- size: "S",
3976
- variant: "tertiary",
3977
- startIcon: /* @__PURE__ */ jsx(Download, {}),
3978
- onClick: handleExport,
3979
- loading: exporting,
3980
- disabled: list.loading || total === 0,
3981
- "aria-label": exportLabel,
3982
- children: t("adminPanel.activity.export.csv", "Export CSV")
3983
2586
  }
3984
- )
3985
- ] }),
3986
- notice,
3987
- list.loading ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 4, children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("adminPanel.activity.loading", "Loading events") }) }) : null,
3988
- !list.loading && list.error ? /* @__PURE__ */ jsx(
3989
- PersistentAlert,
3990
- {
3991
- variant: "danger",
3992
- action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: list.reload, children: t("common.tryAgain", "Try again") }),
3993
- children: t("adminPanel.activity.error", "The events could not be loaded.")
3994
- }
3995
- ) : null,
3996
- !list.loading && !list.error && list.rows.length === 0 ? empty : null,
3997
- list.rows.length > 0 ? renderList(list.rows) : null,
3998
- footer !== void 0 ? list.rows.length > 0 ? footer : null : list.hasMore ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", children: /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: list.loadMore, loading: list.loadingMore, children: t("adminPanel.activity.showMore", "Show more") }) }) : null
3999
- ] });
4000
- };
4001
- const RecordingOff = ({ children }) => {
4002
- const t = useT$2();
4003
- return /* @__PURE__ */ jsx(
4004
- PersistentAlert,
4005
- {
4006
- variant: "neutral",
4007
- action: /* @__PURE__ */ jsx(Link, { tag: Link$1, to: ADMIN_ACTIVITY_SETTINGS_PATH, children: t("adminPanel.activity.openSettings", "Open settings") }),
4008
- children
2587
+ )
4009
2588
  }
4010
2589
  );
4011
2590
  };
4012
- const SignInHistoryPanel = ({ admin }) => {
2591
+ const HIGHLIGHT_BADGE = { backgroundColor: "primary100", textColor: "neutral800" };
2592
+ const offersPreview = (admin, canPreview) => Boolean(canPreview) && admin.self !== true && !(admin.roles || []).some((role) => role?.superAdmin === true);
2593
+ const keepActionKeys = (event) => {
2594
+ if (shouldIsolateActionKey(event.key, true)) event.stopPropagation();
2595
+ };
2596
+ const SHRINKING_ADMIN_CELL = { maxWidth: 0, width: "34%" };
2597
+ const SHRINKING_ROLES_CELL = { maxWidth: 0, width: "22%" };
2598
+ const useT$2 = () => {
2599
+ const { formatMessage } = useIntl();
2600
+ return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
2601
+ };
2602
+ const AdminIdentity = ({ admin }) => {
4013
2603
  const t = useT$2();
4014
- const [event, setEvent] = useState("all");
4015
- const [period, setPeriod] = useState("30");
4016
- const params = useMemo(
4017
- () => buildSignInParams({ adminId: admin.id, event, period }),
4018
- [admin.id, event, period]
4019
- );
4020
- const list = useEventList({
4021
- path: `/${pluginId}/admin-activity/sign-ins`,
4022
- params,
4023
- logKey: "adminPanel.activity.signIns"
4024
- });
4025
- const recording = list.meta?.recording;
4026
- const labels = {
4027
- all: t("adminPanel.activity.filter.allEvents", "All events"),
4028
- succeeded: t("adminPanel.activity.filter.succeeded", "Sign-ins"),
4029
- failed: t("adminPanel.activity.filter.failed", "Failed and locked out"),
4030
- "signed-out": t("adminPanel.activity.filter.signedOut", "Sign-outs")
4031
- };
4032
- return /* @__PURE__ */ jsx(
4033
- EventList,
4034
- {
4035
- list,
4036
- filters: /* @__PURE__ */ jsxs(Fragment, { children: [
4037
- /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
4038
- SingleSelect,
4039
- {
4040
- size: "S",
4041
- "aria-label": t("adminPanel.activity.filter.event", "Event"),
4042
- value: event,
4043
- onChange: (next) => setEvent(String(next)),
4044
- children: SIGN_IN_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: labels[option] }, option))
4045
- }
4046
- ) }),
4047
- /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(PeriodSelect, { value: period, onChange: setPeriod }) })
4048
- ] }),
4049
- notice: recording && !recording.signIns ? /* @__PURE__ */ jsx(RecordingOff, { children: t(
4050
- "adminPanel.activity.signIns.off",
4051
- "Sign-in history is turned off. New sign-ins are not recorded."
4052
- ) }) : null,
4053
- empty: /* @__PURE__ */ jsx(EmptyText, { children: t("adminPanel.activity.signIns.empty", "No sign-in events in this period.") }),
4054
- renderList: (rows) => /* @__PURE__ */ jsx(
4055
- SignInEventTable,
2604
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, minWidth: 0, children: [
2605
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", minWidth: 0, children: [
2606
+ /* @__PURE__ */ jsx(
2607
+ Typography,
4056
2608
  {
4057
- rows,
4058
- busy: list.loading,
4059
- label: t("adminPanel.activity.signIns.listLabel", "Sign-in history of {name}", {
4060
- name: admin.name
4061
- })
2609
+ variant: "omega",
2610
+ fontWeight: "semiBold",
2611
+ textColor: "neutral800",
2612
+ ellipsis: true,
2613
+ title: admin.name,
2614
+ children: admin.name
4062
2615
  }
4063
2616
  ),
4064
- toCsv: buildSignInCsv,
4065
- fileName: "admin-sign-in-history",
4066
- exportLabel: t(
4067
- "adminPanel.activity.signIns.export",
4068
- "Export the sign-in history of {name} as CSV",
4069
- {
4070
- name: admin.name
4071
- }
4072
- )
4073
- }
4074
- );
2617
+ admin.self ? /* @__PURE__ */ jsx(Badge, { ...HIGHLIGHT_BADGE, shrink: 0, children: t("adminPanel.you", "You") }) : null
2618
+ ] }),
2619
+ admin.identityHidden ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("adminPanel.identity.emailHidden", "Email hidden (needs “Read” on Users)") }) : /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", ellipsis: true, title: admin.email, children: admin.email })
2620
+ ] });
4075
2621
  };
4076
- const ContentActivityPanel = ({ admin }) => {
2622
+ const AdminRoles = ({ admin }) => {
4077
2623
  const t = useT$2();
4078
- const [action, setAction] = useState("all");
4079
- const [contentType, setContentType] = useState("all");
4080
- const [period, setPeriod] = useState("30");
4081
- const params = useMemo(
4082
- () => buildActivityParams({ adminId: admin.id, action, contentType, period }),
4083
- [admin.id, action, contentType, period]
4084
- );
4085
- const list = useEventList({
4086
- path: `/${pluginId}/admin-activity/content`,
4087
- params,
4088
- logKey: "adminPanel.activity.content"
4089
- });
4090
- const recording = list.meta?.recording;
4091
- const types = Array.isArray(list.meta?.contentTypes) ? list.meta.contentTypes : [];
4092
- const noAccess = list.meta?.contentManagerAccess === false;
4093
- let notice = null;
4094
- if (recording && !recording.contentActivity) {
4095
- notice = /* @__PURE__ */ jsx(RecordingOff, { children: t(
4096
- "adminPanel.activity.content.off",
4097
- "Content Manager activity is not recorded. An admin can turn it on in the settings; inform your team first."
4098
- ) });
4099
- } else if (noAccess) {
4100
- notice = /* @__PURE__ */ jsx(PersistentAlert, { variant: "neutral", children: t(
4101
- "adminPanel.activity.content.noAccess",
4102
- "{name} has no Content Manager access, so there is no activity to show.",
4103
- { name: admin.name }
4104
- ) });
4105
- }
4106
- return /* @__PURE__ */ jsx(
4107
- EventList,
2624
+ const names = (admin.roles || []).map((role) => role.name).filter(Boolean);
2625
+ const text = admin.rolesHidden ? t("adminPanel.roles.hidden", "Hidden (needs “Read” on Roles)") : names.length ? names.join(", ") : t("adminPanel.roles.none", "No role");
2626
+ return /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", ellipsis: true, title: text, children: text });
2627
+ };
2628
+ const AdminStatus = ({ admin }) => {
2629
+ const t = useT$2();
2630
+ const status = getAdminStatusPresentation(admin);
2631
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, "data-admin-status": status.key, children: [
2632
+ /* @__PURE__ */ jsx(Badge, { ...getBadgeColors(status.tone), children: t(status.label.messageId, status.label.defaultMessage) }),
2633
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(status.detail.messageId, status.detail.defaultMessage, status.detail.values) })
2634
+ ] });
2635
+ };
2636
+ const AdminTable = ({
2637
+ admins,
2638
+ labelledBy,
2639
+ canRevoke,
2640
+ onView,
2641
+ onSignOutEverywhere,
2642
+ canPreview,
2643
+ onPreview,
2644
+ busy
2645
+ }) => {
2646
+ const t = useT$2();
2647
+ return /* @__PURE__ */ jsx(Box, { background: "neutral0", hasRadius: true, shadow: "tableShadow", "data-admin-table": "", children: /* @__PURE__ */ jsxs(
2648
+ Table,
4108
2649
  {
4109
- list,
4110
- filters: /* @__PURE__ */ jsxs(Fragment, { children: [
4111
- /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
4112
- SingleSelect,
4113
- {
4114
- size: "S",
4115
- "aria-label": t("adminPanel.activity.filter.action", "Action"),
4116
- value: action,
4117
- onChange: (next) => setAction(String(next)),
4118
- children: ACTIVITY_ACTION_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: t(
4119
- ACTIVITY_ACTION_LABELS[option].messageId,
4120
- ACTIVITY_ACTION_LABELS[option].defaultMessage
4121
- ) }, option))
4122
- }
4123
- ) }),
4124
- /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsxs(
4125
- SingleSelect,
4126
- {
4127
- size: "S",
4128
- "aria-label": t("adminPanel.activity.filter.contentType", "Content type"),
4129
- value: contentType,
4130
- onChange: (next) => setContentType(String(next)),
4131
- children: [
4132
- /* @__PURE__ */ jsx(SingleSelectOption, { value: "all", children: t("adminPanel.activity.filter.allTypes", "All content types") }),
4133
- types.map((type) => /* @__PURE__ */ jsx(SingleSelectOption, { value: type.uid, children: type.name }, type.uid))
4134
- ]
4135
- }
4136
- ) }),
4137
- /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(PeriodSelect, { value: period, onChange: setPeriod }) })
4138
- ] }),
4139
- notice,
4140
- empty: /* @__PURE__ */ jsx(EmptyText, { children: t("adminPanel.activity.content.empty", "No Content Manager activity in this period.") }),
4141
- renderList: (rows) => /* @__PURE__ */ jsx(
4142
- ActivityEventTable,
4143
- {
4144
- rows,
4145
- busy: list.loading,
4146
- label: t("adminPanel.activity.content.listLabel", "Content Manager activity of {name}", {
4147
- name: admin.name
4148
- })
4149
- }
4150
- ),
4151
- toCsv: buildActivityCsv,
4152
- fileName: "admin-content-activity",
4153
- exportLabel: t(
4154
- "adminPanel.activity.content.export",
4155
- "Export the Content Manager activity of {name} as CSV",
4156
- { name: admin.name }
4157
- )
2650
+ colCount: 5,
2651
+ rowCount: admins.length + 1,
2652
+ "aria-labelledby": labelledBy,
2653
+ "aria-busy": busy,
2654
+ children: [
2655
+ /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
2656
+ /* @__PURE__ */ jsx(Th, { style: SHRINKING_ADMIN_CELL, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.admin", "Admin") }) }),
2657
+ /* @__PURE__ */ jsx(Th, { style: SHRINKING_ROLES_CELL, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.roles", "Roles") }) }),
2658
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.status", "Status") }) }),
2659
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.lastActive", "Last active") }) }),
2660
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(VisuallyHidden, { children: t("adminPanel.table.actions", "Actions") }) })
2661
+ ] }) }),
2662
+ /* @__PURE__ */ jsx(Tbody, { children: admins.map((admin) => /* @__PURE__ */ jsxs(Tr, { "data-admin-row": admin.id, children: [
2663
+ /* @__PURE__ */ jsx(Td, { style: SHRINKING_ADMIN_CELL, children: /* @__PURE__ */ jsx(AdminIdentity, { admin }) }),
2664
+ /* @__PURE__ */ jsx(Td, { style: SHRINKING_ROLES_CELL, children: /* @__PURE__ */ jsx(AdminRoles, { admin }) }),
2665
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(AdminStatus, { admin }) }),
2666
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(LastActive, { value: admin.lastActiveAt }) }),
2667
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsxs(RowActions, { onKeyDown: keepActionKeys, children: [
2668
+ /* @__PURE__ */ jsx(
2669
+ IconButton,
2670
+ {
2671
+ label: t("adminPanel.actions.view", "View sessions of {name}", {
2672
+ name: admin.name
2673
+ }),
2674
+ onClick: (event) => onView(admin, event.currentTarget),
2675
+ children: /* @__PURE__ */ jsx(Eye, {})
2676
+ }
2677
+ ),
2678
+ offersPreview(admin, canPreview) ? /* @__PURE__ */ jsx(
2679
+ IconButton,
2680
+ {
2681
+ label: t("adminPanel.actions.viewAs", "View as {name}", {
2682
+ name: admin.name || `#${admin.id}`
2683
+ }),
2684
+ onClick: (event) => onPreview?.(admin, event.currentTarget),
2685
+ children: /* @__PURE__ */ jsx(User, {})
2686
+ }
2687
+ ) : null,
2688
+ canRevoke && admin.canSignOut ? /* @__PURE__ */ jsx(
2689
+ IconButton,
2690
+ {
2691
+ variant: "danger-light",
2692
+ label: t(
2693
+ "adminPanel.actions.signOutEverywhere",
2694
+ "Sign out {name} everywhere",
2695
+ {
2696
+ name: admin.name
2697
+ }
2698
+ ),
2699
+ onClick: (event) => onSignOutEverywhere(admin, event.currentTarget),
2700
+ children: /* @__PURE__ */ jsx(SignOut, {})
2701
+ }
2702
+ ) : null
2703
+ ] }) })
2704
+ ] }, admin.id)) })
2705
+ ]
4158
2706
  }
4159
- );
2707
+ ) });
4160
2708
  };
4161
- const RecentSignInActivity = ({ onOpenAdmin }) => {
2709
+ const AdminCardList = ({
2710
+ admins,
2711
+ labelledBy,
2712
+ canRevoke,
2713
+ onView,
2714
+ onSignOutEverywhere,
2715
+ canPreview,
2716
+ onPreview
2717
+ }) => {
4162
2718
  const t = useT$2();
4163
- const headingId = `recent-sign-in-activity-${useId().replace(/:/g, "")}`;
4164
- const params = useMemo(() => buildSignInParams({ pageSize: RECENT_EVENT_LIMIT }), []);
4165
- const list = useEventList({
4166
- path: `/${pluginId}/admin-activity/sign-ins`,
4167
- params,
4168
- logKey: "adminPanel.activity.recent"
4169
- });
4170
- if (list.meta?.recording && !list.meta.recording.signIns) return null;
4171
- const title = t("adminPanel.activity.recent.title", "Recent security activity");
4172
- return /* @__PURE__ */ jsxs(
2719
+ return /* @__PURE__ */ jsx(
4173
2720
  Flex,
4174
2721
  {
4175
- tag: "section",
4176
- "aria-labelledby": headingId,
2722
+ tag: "ul",
4177
2723
  direction: "column",
4178
2724
  alignItems: "stretch",
4179
- gap: 4,
4180
- minWidth: 0,
4181
- "data-recent-activity": "",
4182
- children: [
4183
- /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "flex-end", gap: 4, wrap: "wrap", children: [
4184
- /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, flex: "1 1 32rem", children: [
4185
- /* @__PURE__ */ jsx(Typography, { id: headingId, variant: "delta", tag: "h2", textColor: "neutral800", children: title }),
4186
- /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(
4187
- "adminPanel.activity.recent.subtitle",
4188
- "The latest sign-ins, failed attempts, sign-outs and settings changes of all admins. Select an event for its details."
4189
- ) })
4190
- ] }),
4191
- /* @__PURE__ */ jsx(
4192
- LinkButton,
4193
- {
4194
- tag: Link$1,
4195
- to: ADMIN_ACTIVITY_PAGE_PATH,
4196
- variant: "tertiary",
4197
- endIcon: /* @__PURE__ */ jsx(ArrowRight, {}),
4198
- "data-show-all-activity": "",
4199
- children: t("adminPanel.activity.recent.showAll", "Show all")
4200
- }
4201
- )
4202
- ] }),
4203
- list.loading && list.rows.length === 0 ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 2, children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("adminPanel.activity.loading", "Loading events") }) }) : null,
4204
- !list.loading && list.error ? /* @__PURE__ */ jsx(
4205
- PersistentAlert,
4206
- {
4207
- variant: "danger",
4208
- action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: list.reload, children: t("common.tryAgain", "Try again") }),
4209
- children: t("adminPanel.activity.error", "The events could not be loaded.")
4210
- }
4211
- ) : null,
4212
- !list.loading && !list.error && list.rows.length === 0 ? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", children: t("adminPanel.activity.recent.empty", "No events recorded yet.") }) : null,
4213
- list.rows.length > 0 ? /* @__PURE__ */ jsx(
4214
- SignInEventTable,
4215
- {
4216
- rows: list.rows,
4217
- label: title,
4218
- showAdmin: true,
4219
- onOpenAdmin,
4220
- busy: list.loading
4221
- }
4222
- ) : null
4223
- ]
2725
+ gap: 3,
2726
+ "aria-labelledby": labelledBy,
2727
+ "data-admin-cards": "",
2728
+ children: admins.map((admin) => /* @__PURE__ */ jsx(
2729
+ Box,
2730
+ {
2731
+ tag: "li",
2732
+ background: "neutral0",
2733
+ hasRadius: true,
2734
+ shadow: "tableShadow",
2735
+ padding: 4,
2736
+ "data-admin-row": admin.id,
2737
+ children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 3, minWidth: 0, children: [
2738
+ /* @__PURE__ */ jsx(AdminIdentity, { admin }),
2739
+ /* @__PURE__ */ jsxs(Flex, { gap: 4, wrap: "wrap", alignItems: "flex-start", justifyContent: "space-between", children: [
2740
+ /* @__PURE__ */ jsx(AdminStatus, { admin }),
2741
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
2742
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("adminPanel.table.lastActive", "Last active") }),
2743
+ /* @__PURE__ */ jsx(LastActive, { value: admin.lastActiveAt })
2744
+ ] })
2745
+ ] }),
2746
+ /* @__PURE__ */ jsx(AdminRoles, { admin }),
2747
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", children: [
2748
+ /* @__PURE__ */ jsx(
2749
+ Button,
2750
+ {
2751
+ variant: "secondary",
2752
+ startIcon: /* @__PURE__ */ jsx(Eye, {}),
2753
+ onClick: (event) => onView(admin, event.currentTarget),
2754
+ "aria-label": t("adminPanel.actions.view", "View sessions of {name}", {
2755
+ name: admin.name
2756
+ }),
2757
+ flex: "1 1 auto",
2758
+ children: t("adminPanel.actions.viewShort", "View sessions")
2759
+ }
2760
+ ),
2761
+ offersPreview(admin, canPreview) ? /* @__PURE__ */ jsx(
2762
+ Button,
2763
+ {
2764
+ variant: "secondary",
2765
+ startIcon: /* @__PURE__ */ jsx(User, {}),
2766
+ onClick: (event) => onPreview?.(admin, event.currentTarget),
2767
+ "aria-label": t("adminPanel.actions.viewAs", "View as {name}", {
2768
+ name: admin.name || `#${admin.id}`
2769
+ }),
2770
+ flex: "1 1 auto",
2771
+ children: t("adminPanel.actions.viewAsShort", "View as")
2772
+ }
2773
+ ) : null,
2774
+ canRevoke && admin.canSignOut ? /* @__PURE__ */ jsx(
2775
+ Button,
2776
+ {
2777
+ variant: "danger-light",
2778
+ startIcon: /* @__PURE__ */ jsx(SignOut, {}),
2779
+ onClick: (event) => onSignOutEverywhere(admin, event.currentTarget),
2780
+ "aria-label": t(
2781
+ "adminPanel.actions.signOutEverywhere",
2782
+ "Sign out {name} everywhere",
2783
+ {
2784
+ name: admin.name
2785
+ }
2786
+ ),
2787
+ flex: "1 1 auto",
2788
+ children: t("adminPanel.actions.signOutEverywhereShort", "Sign out everywhere")
2789
+ }
2790
+ ) : null
2791
+ ] })
2792
+ ] })
2793
+ },
2794
+ admin.id
2795
+ ))
4224
2796
  }
4225
2797
  );
4226
2798
  };
@@ -4707,7 +3279,7 @@ const PreviewAdminModal = ({ admin, onClose, onCloseAutoFocus, onChanged }) => {
4707
3279
  ] }) });
4708
3280
  };
4709
3281
  const SETTINGS_USERS_PATH = "/settings/users";
4710
- const PaginationTargets$1 = styled.div`
3282
+ const PaginationTargets$2 = styled.div`
4711
3283
  nav a {
4712
3284
  min-width: 3.2rem;
4713
3285
  }
@@ -4916,10 +3488,10 @@ const AdminPanelPage = () => {
4916
3488
  await Promise.all([fetchAdmins(), selected ? fetchDialogSessions(selected) : null]);
4917
3489
  } catch (err) {
4918
3490
  logSafeAdminError("adminPanel.signOut", err);
4919
- const message2 = getSignOutErrorMessage(err);
3491
+ const message = getSignOutErrorMessage(err);
4920
3492
  toggleNotification({
4921
3493
  type: getErrorStatus(err) === 404 ? "warning" : "danger",
4922
- message: t(message2.messageId, message2.defaultMessage)
3494
+ message: t(message.messageId, message.defaultMessage)
4923
3495
  });
4924
3496
  if (getErrorStatus(err) === 404) {
4925
3497
  await Promise.all([fetchAdmins(), selected ? fetchDialogSessions(selected) : null]);
@@ -5200,7 +3772,7 @@ const AdminPanelPage = () => {
5200
3772
  ] }),
5201
3773
  admins.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
5202
3774
  isBelowMedium ? /* @__PURE__ */ jsx(AdminCardList, { ...listProps }) : /* @__PURE__ */ jsx(AdminTable, { ...listProps }),
5203
- /* @__PURE__ */ jsx(PaginationTargets$1, { children: /* @__PURE__ */ jsxs(
3775
+ /* @__PURE__ */ jsx(PaginationTargets$2, { children: /* @__PURE__ */ jsxs(
5204
3776
  Pagination.Root,
5205
3777
  {
5206
3778
  pageCount: pagination.pageCount,
@@ -5274,7 +3846,7 @@ const AdminPanelPage = () => {
5274
3846
  }
5275
3847
  );
5276
3848
  };
5277
- const PaginationTargets = styled.div`
3849
+ const PaginationTargets$1 = styled.div`
5278
3850
  nav a {
5279
3851
  min-width: 3.2rem;
5280
3852
  }
@@ -5368,11 +3940,10 @@ const AdminActivityPage = () => {
5368
3940
  }
5369
3941
  ) }),
5370
3942
  view.adminId !== null ? /* @__PURE__ */ jsx(
5371
- Tag,
3943
+ FilterTag,
5372
3944
  {
5373
- icon: /* @__PURE__ */ jsx(Cross, { "aria-hidden": "true" }),
5374
3945
  label: t("adminPanel.activity.page.removeAdmin", "Show all admins again"),
5375
- onClick: () => setFilters({ adminId: void 0 }),
3946
+ onRemove: () => setFilters({ adminId: void 0 }),
5376
3947
  "data-admin-filter": view.adminId,
5377
3948
  children: t("adminPanel.activity.page.adminFilter", "Admin: {name}", { name: adminName })
5378
3949
  }
@@ -5436,6 +4007,173 @@ const AdminActivityPage = () => {
5436
4007
  "adminPanel.activity.page.export",
5437
4008
  "Export the security activity with these filters as CSV"
5438
4009
  ),
4010
+ footer: /* @__PURE__ */ jsx(PaginationTargets$1, { children: /* @__PURE__ */ jsxs(
4011
+ Pagination.Root,
4012
+ {
4013
+ pageCount: pagination.pageCount,
4014
+ total: pagination.total,
4015
+ defaultPageSize: EVENT_PAGE_SIZE,
4016
+ children: [
4017
+ /* @__PURE__ */ jsx(Pagination.PageSize, { options: [...ACTIVITY_PAGE_SIZE_OPTIONS] }),
4018
+ /* @__PURE__ */ jsx(Pagination.Links, {})
4019
+ ]
4020
+ }
4021
+ ) })
4022
+ }
4023
+ )
4024
+ }
4025
+ );
4026
+ };
4027
+ const PaginationTargets = styled.div`
4028
+ nav a {
4029
+ min-width: 3.2rem;
4030
+ }
4031
+
4032
+ & > div {
4033
+ flex-wrap: wrap;
4034
+ gap: ${({ theme }) => theme.spaces[2]} ${({ theme }) => theme.spaces[4]};
4035
+ }
4036
+
4037
+ & > div > div > span {
4038
+ white-space: nowrap;
4039
+ }
4040
+ `;
4041
+ const UserActivityPage = () => {
4042
+ const { formatMessage } = useIntl();
4043
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
4044
+ const [{ query }, setQuery] = useQueryParams();
4045
+ const view = parseUserActivityQuery(query);
4046
+ const captionRef = useRef(null);
4047
+ const params = useMemo(
4048
+ () => buildUserActivityParams({
4049
+ userId: view.userId,
4050
+ event: view.event,
4051
+ period: view.period,
4052
+ page: view.page,
4053
+ pageSize: view.pageSize
4054
+ }),
4055
+ [view.userId, view.event, view.period, view.page, view.pageSize]
4056
+ );
4057
+ const list = useEventList({
4058
+ path: USER_ACTIVITY_API_PATH,
4059
+ params,
4060
+ logKey: "userActivity.page"
4061
+ });
4062
+ const pagination = list.meta?.pagination || { pageCount: 1, total: 0 };
4063
+ useEffect(() => {
4064
+ if (!list.loading && list.meta && view.page > pagination.pageCount) {
4065
+ setQuery({ page: String(pagination.pageCount) }, "push", true);
4066
+ }
4067
+ }, [list.loading, list.meta, view.page, pagination.pageCount, setQuery]);
4068
+ const filtered = hasUserActivityFilters(view);
4069
+ const filteredUser = view.userId !== null ? list.rows.find((row) => row.user?.documentId === view.userId) : null;
4070
+ const userName = filteredUser ? userText(t, filteredUser) : t("userActivity.page.selectedUser", "Selected user");
4071
+ const setFilters = (next) => setQuery({ ...next, page: "1" });
4072
+ const clearFilters = () => {
4073
+ setQuery({ event: void 0, period: void 0, userId: void 0, page: "1" });
4074
+ captionRef.current?.focus();
4075
+ };
4076
+ const title = t("userActivity.page.title", "Security activity of app users");
4077
+ const recordingOff = list.meta?.recording && list.meta.recording.userSignIns === false;
4078
+ return /* @__PURE__ */ jsx(
4079
+ PageShell,
4080
+ {
4081
+ headingId: "magic-sessionmanager-user-activity-title",
4082
+ title,
4083
+ subtitle: t(
4084
+ "userActivity.page.subtitle",
4085
+ "Failed and refused sign-ins, lockouts, session limits, new devices, impossible travel, “This wasn’t me” reports, data exports and impersonations of your app’s users. Newest first."
4086
+ ),
4087
+ navigationAction: /* @__PURE__ */ jsx(BackButton, { fallback: SESSION_VIEW_PATHS.users }),
4088
+ children: /* @__PURE__ */ jsx(
4089
+ EventList,
4090
+ {
4091
+ list,
4092
+ filters: /* @__PURE__ */ jsxs(Fragment, { children: [
4093
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
4094
+ SingleSelect,
4095
+ {
4096
+ size: "S",
4097
+ "aria-label": t("adminPanel.activity.filter.event", "Event"),
4098
+ value: view.event,
4099
+ onChange: (next) => setFilters({ event: String(next) === "all" ? void 0 : String(next) }),
4100
+ children: USER_ACTIVITY_FILTER_OPTIONS.map((option) => /* @__PURE__ */ jsx(SingleSelectOption, { value: option, children: t(...USER_ACTIVITY_FILTER_LABELS[option]) }, option))
4101
+ }
4102
+ ) }),
4103
+ /* @__PURE__ */ jsx(FilterSlot, { children: /* @__PURE__ */ jsx(
4104
+ PeriodSelect,
4105
+ {
4106
+ value: view.period,
4107
+ onChange: (next) => setFilters({ period: next === "30" ? void 0 : next })
4108
+ }
4109
+ ) }),
4110
+ view.userId !== null ? /* @__PURE__ */ jsx(
4111
+ FilterTag,
4112
+ {
4113
+ label: t("userActivity.page.removeUser", "Show all users again"),
4114
+ onRemove: () => setFilters({ userId: void 0 }),
4115
+ "data-user-filter": view.userId,
4116
+ children: t("userActivity.page.userFilter", "User: {name}", { name: userName })
4117
+ }
4118
+ ) : null
4119
+ ] }),
4120
+ notice: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
4121
+ recordingOff ? /* @__PURE__ */ jsx(RecordingOff, { to: USER_ACTIVITY_SETTINGS_PATH, children: t(
4122
+ "userActivity.page.recordingOff",
4123
+ "Failed and refused sign-ins are not recorded. The other events still are."
4124
+ ) }) : null,
4125
+ /* @__PURE__ */ jsx(
4126
+ Typography,
4127
+ {
4128
+ ref: captionRef,
4129
+ tabIndex: -1,
4130
+ variant: "pi",
4131
+ textColor: "neutral600",
4132
+ "aria-live": "polite",
4133
+ "data-activity-caption": "",
4134
+ children: t(
4135
+ "adminPanel.activity.page.caption",
4136
+ "{total, plural, =0 {No events} one {# event} other {# events}}",
4137
+ { total: pagination.total }
4138
+ )
4139
+ }
4140
+ )
4141
+ ] }),
4142
+ empty: /* @__PURE__ */ jsx(
4143
+ EmptyStateLayout,
4144
+ {
4145
+ icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem", "aria-hidden": "true" }),
4146
+ content: filtered ? t("adminPanel.activity.page.noResults", "No events match these filters.") : t("userActivity.recent.empty", "No security events of app users yet."),
4147
+ action: filtered ? /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: clearFilters, children: t("adminPanel.noResults.reset", "Clear filters") }) : null
4148
+ }
4149
+ ),
4150
+ renderList: (rows) => /* @__PURE__ */ jsx(
4151
+ UserEventTable,
4152
+ {
4153
+ rows,
4154
+ label: title,
4155
+ busy: list.loading,
4156
+ detailsAction: (row, close) => row.user?.documentId && row.user.documentId !== view.userId ? /* @__PURE__ */ jsx(
4157
+ Button,
4158
+ {
4159
+ variant: "secondary",
4160
+ onClick: () => {
4161
+ close();
4162
+ setFilters({ userId: row.user.documentId });
4163
+ },
4164
+ children: t("userActivity.page.onlyUser", "Show only events of {name}", {
4165
+ name: userText(t, row)
4166
+ })
4167
+ }
4168
+ ) : null
4169
+ }
4170
+ ),
4171
+ toCsv: buildUserActivityCsv,
4172
+ fileName: "app-user-security-activity",
4173
+ exportLabel: t(
4174
+ "userActivity.page.export",
4175
+ "Export the security activity of app users with these filters as CSV"
4176
+ ),
5439
4177
  footer: /* @__PURE__ */ jsx(PaginationTargets, { children: /* @__PURE__ */ jsxs(
5440
4178
  Pagination.Root,
5441
4179
  {
@@ -5470,6 +4208,13 @@ const App = () => {
5470
4208
  element: /* @__PURE__ */ jsx(Page.Protect, { permissions: pluginPermissions.adminSessionsRead, children: /* @__PURE__ */ jsx(Page.Protect, { permissions: pluginPermissions.adminActivityRead, children: /* @__PURE__ */ jsx(AdminActivityPage, {}) }) })
5471
4209
  }
5472
4210
  ),
4211
+ /* @__PURE__ */ jsx(
4212
+ Route,
4213
+ {
4214
+ path: "app-users/activity",
4215
+ element: /* @__PURE__ */ jsx(Page.Protect, { permissions: pluginPermissions.userActivityRead, children: /* @__PURE__ */ jsx(UserActivityPage, {}) })
4216
+ }
4217
+ ),
5473
4218
  /* @__PURE__ */ jsx(Route, { path: "*", element: /* @__PURE__ */ jsx(HomePage, {}) })
5474
4219
  ] }) });
5475
4220
  };