Skip to content

Your favorite shift management application!

feat(admin): bundle routine sync audit-log entries (#209)

panteLe847ecbb897c
diff --git a/CLAUDE.md b/CLAUDE.md
index 2ee775a..cf053ab 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -28,7 +28,7 @@ There is no unit-test framework here — "tests" means the lint/build/i18n pipel
## Workflow
-Commits follow Conventional Commits (`type(scope): summary`, e.g. `feat(ui):`, `fix(auth):`, `chore:`, `perf:`; `!` before the colon for breaking changes). `scripts/changelog.sh`, called from `.github/workflows/release.yml`, builds the release changelog straight from `git log --pretty=%s --no-merges` between tags — grouped by that prefix, with `refactor|ci|style|test|build` dropped as internal-only. It reads commit subjects, not the PR title or body, so **multi-commit PRs must merge via "Rebase and merge", not Squash** — squashing collapses every commit into one line under the merge commit's message and the per-commit changelog entries are lost. A single-commit PR can go either way since there's nothing to collapse.
+Commits follow Conventional Commits (`type(scope): summary`, e.g. `feat(ui):`, `fix(auth):`, `chore:`, `perf:`; `!` before the colon for breaking changes). `scripts/changelog.sh`, called from `.github/workflows/release.yml`, builds the release changelog straight from `git log --pretty=%s --no-merges` between tags — grouped by that prefix, with `refactor|ci|style|test|build` dropped as internal-only.
## Architecture
diff --git a/app/admin/logs/page.tsx b/app/admin/logs/page.tsx
index d3c4386..dc1b091 100644
--- a/app/admin/logs/page.tsx
+++ b/app/admin/logs/page.tsx
@@ -6,6 +6,7 @@ import { format } from "date-fns";
import { ChevronRight, SlidersHorizontal, Trash2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
+import { Switch } from "@/components/ui/switch";
import {
AdminMobileCard,
AdminPageHeader,
@@ -18,6 +19,7 @@ import {
import { SortHeader, nextSort, type SortState } from "@/components/admin/admin-table-controls";
import { AuditLogDetailsDialog } from "@/components/admin/audit-log-details-dialog";
import { AuditLogDeleteDialog } from "@/components/admin/audit-log-delete-dialog";
+import { RoutineBundleRow, RoutineBundleMobileCard } from "@/components/admin/audit-log-routine-bundle";
import {
AuditFilterBar,
AuditFilterChips,
@@ -27,7 +29,12 @@ import {
type AuditFilterValues,
} from "@/components/admin/audit-log-filters";
import { useAuditDescription } from "@/components/admin/audit-describe";
-import { useAdminAuditLogs, type AuditLog, type AuditLogFilters } from "@/hooks/useAdminAuditLogs";
+import {
+ useAdminAuditLogs,
+ type AuditLog,
+ type AuditLogFilters,
+ type RoutineAuditLogBundle,
+} from "@/hooks/useAdminAuditLogs";
import { useIsSuperAdmin } from "@/hooks/useAdminAccess";
import { useDebouncedSearch, useResettableState } from "@/hooks/useAdminList";
import { getDateLocale } from "@/lib/locales";
@@ -39,7 +46,9 @@ const PAGE_SIZE = 25;
// Stable identities so the resettable state falls back to the same value
const EMPTY_ROWS: Set<string> = new Set();
const EMPTY_IDS: string[] = [];
+const EMPTY_BUNDLE_ENTRIES: Record<string, AuditLog[] | "loading"> = {};
const COLUMNS = "18px 160px 180px minmax(0,140px) 96px minmax(0,1fr) 118px 64px";
+const BUNDLE_PREVIEW_LIMIT = 20;
const stop = (e: MouseEvent | KeyboardEvent) => e.stopPropagation();
@@ -53,6 +62,7 @@ export default function AdminAuditLogsPage() {
const search = useDebouncedSearch(500);
const [filterValues, setFilterValues] = useState<AuditFilterValues>(EMPTY_AUDIT_FILTERS);
const [sort, setSort] = useState<SortState<SortColumn>>({ column: "timestamp", direction: "desc" });
+ const [bundleRoutine, setBundleRoutine] = useState(true);
// Any change to search or filters starts over on the first page, with nothing selected
const listKey = [search.query, filterValues.action, filterValues.severity, filterValues.startDate, filterValues.endDate].join("|");
@@ -67,6 +77,11 @@ export default function AdminAuditLogsPage() {
const [showDetailsDialog, setShowDetailsDialog] = useState(false);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const [showFilterSheet, setShowFilterSheet] = useState(false);
+ const [expandedBundles, setExpandedBundles] = useResettableState<Set<string>>(listKey, EMPTY_ROWS);
+ const [bundleEntriesById, setBundleEntriesById] = useResettableState<Record<string, AuditLog[] | "loading">>(
+ listKey,
+ EMPTY_BUNDLE_ENTRIES
+ );
const filters = useMemo<AuditLogFilters>(
() => ({
@@ -82,7 +97,15 @@ export default function AdminAuditLogsPage() {
const sortParams = useMemo(() => ({ field: sort.column, direction: sort.direction }), [sort]);
const pagination = useMemo(() => ({ limit: PAGE_SIZE, offset: page * PAGE_SIZE }), [page]);
- const { logs, total, isLoading } = useAdminAuditLogs(filters, sortParams, pagination);
+ const { logs, total, isLoading, routineBundles, fetchAuditLogs } = useAdminAuditLogs(
+ filters,
+ sortParams,
+ pagination,
+ { bundleRoutine }
+ );
+ // Only page 0 shows the bundle summaries; pagination otherwise iterates non-routine rows only
+ const showRoutineBundles = bundleRoutine && page === 0 && routineBundles.length > 0;
+ const routineTotal = routineBundles.reduce((sum, bundle) => sum + bundle.count, 0);
const updateFilters = (patch: Partial<AuditFilterValues>) => {
setFilterValues((prev) => ({ ...prev, ...patch }));
@@ -102,6 +125,23 @@ export default function AdminAuditLogsPage() {
});
};
+ const toggleBundle = async (bundle: RoutineAuditLogBundle) => {
+ setExpandedBundles((prev) => {
+ const next = new Set(prev);
+ if (next.has(bundle.resourceId)) next.delete(bundle.resourceId);
+ else next.add(bundle.resourceId);
+ return next;
+ });
+ if (bundleEntriesById[bundle.resourceId]) return;
+ setBundleEntriesById((prev) => ({ ...prev, [bundle.resourceId]: "loading" }));
+ const result = await fetchAuditLogs(
+ { action: "sync.executed", resourceId: bundle.resourceId, isUserVisible: false },
+ { field: "timestamp", direction: "desc" },
+ { limit: BUNDLE_PREVIEW_LIMIT, offset: 0 }
+ );
+ setBundleEntriesById((prev) => ({ ...prev, [bundle.resourceId]: result?.logs || [] }));
+ };
+
const toggleLogSelection = (logId: string) => {
setSelectedLogIds((prev) => (prev.includes(logId) ? prev.filter((id) => id !== logId) : [...prev, logId]));
};
@@ -168,7 +208,11 @@ export default function AdminAuditLogsPage() {
<div className="flex flex-col gap-3 lg:gap-4">
<AdminPageHeader
title={t("admin.auditLogs")}
- subtitle={t("adminAudit.subtitle", { count: total })}
+ subtitle={
+ routineTotal > 0
+ ? t("adminAudit.subtitleWithRoutine", { total: total + routineTotal, nonRoutine: total })
+ : t("adminAudit.subtitle", { count: total })
+ }
actions={
isSuperAdmin && (
<Button
@@ -220,6 +264,10 @@ export default function AdminAuditLogsPage() {
/>
<div className="hidden flex-wrap items-center gap-[9px] lg:flex">
<AuditFilterBar filters={filterValues} onChange={updateFilters} onClear={clearFilters} />
+ <label className="flex h-9 items-center gap-2 rounded-[9px] border border-line bg-surface-card px-3 text-[13.5px] text-fg-body">
+ <Switch checked={bundleRoutine} onCheckedChange={setBundleRoutine} />
+ {t("adminAudit.bundleRoutine")}
+ </label>
</div>
</div>
<AuditFilterChips filters={filterValues} onOpen={() => setShowFilterSheet(true)} />
@@ -246,9 +294,16 @@ export default function AdminAuditLogsPage() {
<AdminTableCard
className="hidden lg:block"
footer={
- total > 0 && (
+ (total > 0 || showRoutineBundles) && (
<>
- <span>{showing}</span>
+ <div className="flex flex-col gap-0.5">
+ <span>{showing}</span>
+ {showRoutineBundles && (
+ <span className="text-fg-tertiary">
+ {t("adminAudit.routineBundledFooter", { count: routineTotal })}
+ </span>
+ )}
+ </div>
{pager}
</>
)
@@ -277,98 +332,126 @@ export default function AdminAuditLogsPage() {
"",
]}
/>
- {logs.length === 0 ? (
+ {logs.length === 0 && !showRoutineBundles ? (
<div className="px-4 py-10 text-center text-[13px] text-fg-tertiary">{emptyText}</div>
) : (
- logs.map((log) => {
- const expanded = expandedRows.has(log.id);
- return (
- <Fragment key={log.id}>
- <AdminTableRow template={template} onClick={() => toggleRow(log.id)}>
- {isSuperAdmin && (
- <div onClick={stop} onKeyDown={stop} className="flex">
- <Checkbox
- checked={selectedIds.includes(log.id)}
- onCheckedChange={() => toggleLogSelection(log.id)}
- aria-label={t("adminAudit.selectEntry")}
- />
- </div>
- )}
- <ChevronRight
- className={cn(
- "size-[15px] transition-transform",
- expanded ? "rotate-90 text-fg-secondary" : "text-fg-faint"
- )}
- />
- <span className="font-mono text-[12.5px] text-fg-body">{formatTimestamp(log.timestamp)}</span>
- <span className="max-w-full justify-self-start truncate rounded-[6px] bg-surface-sunken px-2 py-[3px] font-mono text-[12px] font-medium text-fg-body">
- {log.action}
- </span>
- <span className={cn("truncate text-[13px]", log.userId ? "text-fg-body" : "text-fg-tertiary")}>
- {userLabel(log)}
- </span>
- <span className="justify-self-start">
- <SeverityPill severity={log.severity} />
- </span>
- <span className="truncate text-[12.5px] text-fg-tertiary">{describe(log)}</span>
- <span className="truncate font-mono text-[12px] text-fg-tertiary">{log.ipAddress || "—"}</span>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- openDetails(log);
- }}
- onKeyDown={stop}
- className="justify-self-end text-[12.5px] font-semibold text-brand-ink hover:underline"
- >
- {t("adminAudit.details")}
- </button>
- </AdminTableRow>
- {expanded && (
- <div className="flex flex-col gap-2 border-b border-line-subtle bg-surface-panel px-4 py-3">
- <div className="eyebrow">{t("admin.metadata")}</div>
- <pre className="max-h-72 overflow-auto rounded-lg border border-line bg-background p-3 font-mono text-[12px] text-fg-body">
- {JSON.stringify(log.metadata, null, 2)}
- </pre>
- {log.userAgent && (
- <div className="text-[12px] text-fg-tertiary">
- <span className="font-semibold text-fg-secondary">{t("admin.userAgent")}:</span>{" "}
- {log.userAgent}
+ <>
+ {showRoutineBundles &&
+ routineBundles.map((bundle) => (
+ <RoutineBundleRow
+ key={bundle.resourceId}
+ bundle={bundle}
+ expanded={expandedBundles.has(bundle.resourceId)}
+ entries={bundleEntriesById[bundle.resourceId]}
+ onToggle={() => toggleBundle(bundle)}
+ onOpenDetails={openDetails}
+ template={template}
+ isSuperAdmin={isSuperAdmin}
+ />
+ ))}
+ {logs.map((log) => {
+ const expanded = expandedRows.has(log.id);
+ return (
+ <Fragment key={log.id}>
+ <AdminTableRow template={template} onClick={() => toggleRow(log.id)}>
+ {isSuperAdmin && (
+ <div onClick={stop} onKeyDown={stop} className="flex">
+ <Checkbox
+ checked={selectedIds.includes(log.id)}
+ onCheckedChange={() => toggleLogSelection(log.id)}
+ aria-label={t("adminAudit.selectEntry")}
+ />
</div>
)}
- </div>
- )}
- </Fragment>
- );
- })
+ <ChevronRight
+ className={cn(
+ "size-[15px] transition-transform",
+ expanded ? "rotate-90 text-fg-secondary" : "text-fg-faint"
+ )}
+ />
+ <span className="font-mono text-[12.5px] text-fg-body">{formatTimestamp(log.timestamp)}</span>
+ <span className="max-w-full justify-self-start truncate rounded-[6px] bg-surface-sunken px-2 py-[3px] font-mono text-[12px] font-medium text-fg-body">
+ {log.action}
+ </span>
+ <span className={cn("truncate text-[13px]", log.userId ? "text-fg-body" : "text-fg-tertiary")}>
+ {userLabel(log)}
+ </span>
+ <span className="justify-self-start">
+ <SeverityPill severity={log.severity} />
+ </span>
+ <span className="truncate text-[12.5px] text-fg-tertiary">{describe(log)}</span>
+ <span className="truncate font-mono text-[12px] text-fg-tertiary">{log.ipAddress || "—"}</span>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ openDetails(log);
+ }}
+ onKeyDown={stop}
+ className="justify-self-end text-[12.5px] font-semibold text-brand-ink hover:underline"
+ >
+ {t("adminAudit.details")}
+ </button>
+ </AdminTableRow>
+ {expanded && (
+ <div className="flex flex-col gap-2 border-b border-line-subtle bg-surface-panel px-4 py-3">
+ <div className="eyebrow">{t("admin.metadata")}</div>
+ <pre className="max-h-72 overflow-auto rounded-lg border border-line bg-background p-3 font-mono text-[12px] text-fg-body">
+ {JSON.stringify(log.metadata, null, 2)}
+ </pre>
+ {log.userAgent && (
+ <div className="text-[12px] text-fg-tertiary">
+ <span className="font-semibold text-fg-secondary">{t("admin.userAgent")}:</span>{" "}
+ {log.userAgent}
+ </div>
+ )}
+ </div>
+ )}
+ </Fragment>
+ );
+ })}
+ </>
)}
</AdminTableCard>
{/* Phone cards */}
<div className="flex flex-col gap-[9px] lg:hidden">
- {logs.length === 0 ? (
+ {logs.length === 0 && !showRoutineBundles ? (
<div className="rounded-[11px] border border-line px-4 py-8 text-center text-[13px] text-fg-tertiary">
{emptyText}
</div>
) : (
- logs.map((log) => (
- <AdminMobileCard key={log.id} onClick={() => openDetails(log)}>
- <div className="flex w-full items-center gap-2">
- <span className="min-w-0 truncate rounded-[6px] bg-surface-sunken px-2 py-[3px] font-mono text-[12px] font-medium text-fg-body">
- {log.action}
- </span>
- <span className="flex-1" />
- <SeverityPill severity={log.severity} />
- <ChevronRight className="size-4 shrink-0 text-fg-faint" />
- </div>
- <div className="text-[13.5px] leading-snug text-fg-body">{describe(log)}</div>
- <div className="flex min-w-0 items-center gap-1.5 text-[12px] text-fg-tertiary">
- <span className="truncate">{userLabel(log)}</span>
- <span className="text-fg-faint">·</span>
- <span className="shrink-0 font-mono">{formatTimestamp(log.timestamp)}</span>
- </div>
- </AdminMobileCard>
- ))
+ <>
+ {showRoutineBundles &&
+ routineBundles.map((bundle) => (
+ <RoutineBundleMobileCard
+ key={bundle.resourceId}
+ bundle={bundle}
+ expanded={expandedBundles.has(bundle.resourceId)}
+ entries={bundleEntriesById[bundle.resourceId]}
+ onToggle={() => toggleBundle(bundle)}
+ onOpenDetails={openDetails}
+ />
+ ))}
+ {logs.map((log) => (
+ <AdminMobileCard key={log.id} onClick={() => openDetails(log)}>
+ <div className="flex w-full items-center gap-2">
+ <span className="min-w-0 truncate rounded-[6px] bg-surface-sunken px-2 py-[3px] font-mono text-[12px] font-medium text-fg-body">
+ {log.action}
+ </span>
+ <span className="flex-1" />
+ <SeverityPill severity={log.severity} />
+ <ChevronRight className="size-4 shrink-0 text-fg-faint" />
+ </div>
+ <div className="text-[13.5px] leading-snug text-fg-body">{describe(log)}</div>
+ <div className="flex min-w-0 items-center gap-1.5 text-[12px] text-fg-tertiary">
+ <span className="truncate">{userLabel(log)}</span>
+ <span className="text-fg-faint">·</span>
+ <span className="shrink-0 font-mono">{formatTimestamp(log.timestamp)}</span>
+ </div>
+ </AdminMobileCard>
+ ))}
+ </>
)}
{total > PAGE_SIZE && (
<div className="flex items-center justify-between gap-3 pt-1 text-[12px] text-fg-tertiary">
@@ -398,6 +481,8 @@ export default function AdminAuditLogsPage() {
filters={filterValues}
onChange={updateFilters}
onClear={clearFilters}
+ bundleRoutine={bundleRoutine}
+ onBundleRoutineChange={setBundleRoutine}
/>
</div>
);
diff --git a/app/api/admin/audit-logs/route.ts b/app/api/admin/audit-logs/route.ts
index 975b230..7ab69fb 100644
--- a/app/api/admin/audit-logs/route.ts
+++ b/app/api/admin/audit-logs/route.ts
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { auditLogs, user } from "@/lib/db/schema";
-import { sql, eq, desc, and, or, lt, inArray } from "drizzle-orm";
+import { sql, eq, desc, and, or, lt, inArray, not } from "drizzle-orm";
import { requireAdmin } from "@/lib/auth/admin";
import {
getValidatedAdminUser,
@@ -25,10 +25,14 @@ import { parseLocalDate } from "@/lib/date-utils";
* - search: Search in action, resourceType, or metadata (case-insensitive)
* - startDate: Filter logs from this local day on (YYYY-MM-DD, inclusive)
* - endDate: Filter logs up to this local day (YYYY-MM-DD, inclusive)
+ * - isUserVisible: Filter by the isUserVisible flag ("true"/"false")
* - sortBy: Sort field (timestamp, action, severity)
* - sortOrder: Sort direction (asc, desc)
* - limit: Number of logs to return (default: 50, max: 500)
* - offset: Pagination offset
+ * - bundleRoutine: When "true", excludes routine `sync.executed` entries (the
+ * automatic scheduler's runs, i.e. isUserVisible=false) from `logs`/`pagination.total`
+ * and instead returns them grouped per external sync in `routineBundles`.
*
* Permission: Admin or Superadmin only
*/
@@ -49,6 +53,8 @@ export async function GET(request: NextRequest) {
const searchQuery = searchParams.get("search");
const startDate = searchParams.get("startDate");
const endDate = searchParams.get("endDate");
+ const isUserVisibleFilter = searchParams.get("isUserVisible");
+ const bundleRoutine = searchParams.get("bundleRoutine") === "true";
const sortBy = searchParams.get("sortBy") || "timestamp";
const sortOrder = searchParams.get("sortOrder") || "desc";
const limit = Math.min(
@@ -134,6 +140,24 @@ export async function GET(request: NextRequest) {
conditions.push(sql`${auditLogs.timestamp} <= ${unixTimestamp}`);
}
+ // isUserVisible filter
+ if (isUserVisibleFilter === "true" || isUserVisibleFilter === "false") {
+ conditions.push(eq(auditLogs.isUserVisible, isUserVisibleFilter === "true"));
+ }
+
+ // Snapshot before the routine-bundling exclusion below, so the bundle
+ // query can reapply the same filters intersected with the routine condition
+ const filterConditions = [...conditions];
+
+ // Routine entries: automatic-scheduler sync runs, bundled separately below
+ const routineCondition = and(
+ eq(auditLogs.action, "sync.executed"),
+ eq(auditLogs.isUserVisible, false)
+ )!;
+ if (bundleRoutine) {
+ conditions.push(not(routineCondition));
+ }
+
// Apply sorting
let orderByClause;
@@ -203,6 +227,10 @@ export async function GET(request: NextRequest) {
timestamp: log.timestamp.toISOString(),
}));
+ const routineBundles = bundleRoutine
+ ? await getRoutineBundles([...filterConditions, routineCondition])
+ : [];
+
return NextResponse.json({
logs: logsWithParsedMetadata,
pagination: {
@@ -211,6 +239,7 @@ export async function GET(request: NextRequest) {
offset,
hasMore: offset + limit < total,
},
+ routineBundles,
});
} catch (error) {
console.error("[Admin Audit Logs] Error fetching logs:", error);
@@ -361,3 +390,49 @@ function tryParseJSON(jsonString: string): unknown {
return jsonString; // Return as string if parsing fails
}
}
+
+function metadataField(metadata: unknown, key: string): string {
+ const value =
+ metadata && typeof metadata === "object" ? (metadata as Record<string, unknown>)[key] : undefined;
+ return typeof value === "string" ? value : "";
+}
+
+/**
+ * Groups routine (auto-scheduler) sync.executed entries per external sync,
+ * one summary row each, so a busy instance's audit log isn't dominated by them.
+ */
+async function getRoutineBundles(conditions: ReturnType<typeof and>[]) {
+ const stats = await db
+ .select({
+ resourceId: auditLogs.resourceId,
+ count: sql<number>`COUNT(*)`,
+ firstTimestamp: sql<number>`MIN(${auditLogs.timestamp})`,
+ lastTimestamp: sql<number>`MAX(${auditLogs.timestamp})`,
+ })
+ .from(auditLogs)
+ .where(and(...conditions))
+ .groupBy(auditLogs.resourceId);
+
+ return Promise.all(
+ stats
+ .filter((row): row is typeof row & { resourceId: string } => !!row.resourceId)
+ .map(async (row) => {
+ const [latest] = await db
+ .select({ metadata: auditLogs.metadata })
+ .from(auditLogs)
+ .where(and(...conditions, eq(auditLogs.resourceId, row.resourceId)))
+ .orderBy(desc(auditLogs.timestamp))
+ .limit(1);
+ const metadata = latest?.metadata ? tryParseJSON(latest.metadata) : null;
+
+ return {
+ resourceId: row.resourceId,
+ count: Number(row.count),
+ firstTimestamp: new Date(Number(row.firstTimestamp) * 1000).toISOString(),
+ lastTimestamp: new Date(Number(row.lastTimestamp) * 1000).toISOString(),
+ syncName: metadataField(metadata, "syncName"),
+ calendarName: metadataField(metadata, "calendarName"),
+ };
+ })
+ );
+}
diff --git a/components/admin/audit-log-filters.tsx b/components/admin/audit-log-filters.tsx
index 41aed16..f3733c0 100644
--- a/components/admin/audit-log-filters.tsx
+++ b/components/admin/audit-log-filters.tsx
@@ -8,7 +8,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { ChoiceChips, Field, inputClass } from "@/components/form-kit";
+import { ChoiceChips, Field, inputClass, ToggleRow } from "@/components/form-kit";
import { PanelDialog } from "@/components/panel-dialog";
import { parseLocalDate } from "@/lib/date-utils";
import { getDateLocale } from "@/lib/locales";
@@ -232,12 +232,16 @@ export function AuditFilterSheet({
filters,
onChange,
onClear,
+ bundleRoutine,
+ onBundleRoutineChange,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
filters: AuditFilterValues;
onChange: (patch: Partial<AuditFilterValues>) => void;
onClear: () => void;
+ bundleRoutine: boolean;
+ onBundleRoutineChange: (value: boolean) => void;
}) {
const t = useTranslations();
const { actions, severities } = useFilterOptions();
@@ -281,6 +285,12 @@ export function AuditFilterSheet({
/>
</Field>
<DateInputs filters={filters} onChange={onChange} />
+ <ToggleRow
+ title={t("adminAudit.bundleRoutine")}
+ description={t("adminAudit.bundleRoutineDescription")}
+ checked={bundleRoutine}
+ onCheckedChange={onBundleRoutineChange}
+ />
</PanelDialog>
);
}
diff --git a/components/admin/audit-log-routine-bundle.tsx b/components/admin/audit-log-routine-bundle.tsx
new file mode 100644
index 0000000..9b37c52
--- /dev/null
+++ b/components/admin/audit-log-routine-bundle.tsx
@@ -0,0 +1,146 @@
+"use client";
+
+import { useLocale, useTranslations } from "next-intl";
+import { format } from "date-fns";
+import { ChevronRight } from "lucide-react";
+import { AdminMobileCard, AdminTableRow, SeverityPill } from "@/components/admin/admin-kit";
+import { useAuditDescription } from "@/components/admin/audit-describe";
+import type { AuditLog, RoutineAuditLogBundle } from "@/hooks/useAdminAuditLogs";
+import { getDateLocale } from "@/lib/locales";
+import { cn } from "@/lib/utils";
+
+interface RoutineBundleProps {
+ bundle: RoutineAuditLogBundle;
+ expanded: boolean;
+ /** undefined = not fetched yet, "loading" = in flight */
+ entries: AuditLog[] | "loading" | undefined;
+ onToggle: () => void;
+ onOpenDetails: (log: AuditLog) => void;
+}
+
+function useBundleDisplay(bundle: RoutineAuditLogBundle) {
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const dateRange = `${format(bundle.firstTimestamp, "PP", { locale: dateLocale })} – ${format(bundle.lastTimestamp, "PP", { locale: dateLocale })}`;
+ const badge = `sync.executed ×${new Intl.NumberFormat(locale).format(bundle.count)}`;
+ return { dateRange, badge };
+}
+
+function RoutineEntriesList({
+ bundle,
+ entries,
+ onOpenDetails,
+}: {
+ bundle: RoutineAuditLogBundle;
+ entries: AuditLog[] | "loading" | undefined;
+ onOpenDetails: (log: AuditLog) => void;
+}) {
+ const t = useTranslations();
+ const locale = useLocale();
+ const dateLocale = getDateLocale(locale);
+ const describe = useAuditDescription();
+ const formatTimestamp = (date: Date) => format(date, "PP p", { locale: dateLocale });
+
+ if (entries === "loading") {
+ return <div className="text-[12.5px] text-fg-tertiary">{t("common.loading")}</div>;
+ }
+
+ const shown = entries ?? [];
+ const remaining = bundle.count - shown.length;
+
+ return (
+ <>
+ <div className="eyebrow">{t("adminAudit.routineEntries")}</div>
+ {shown.map((entry) => (
+ <div key={entry.id} className="flex items-center gap-3 text-[12.5px]">
+ <span className="shrink-0 font-mono text-fg-tertiary">{formatTimestamp(entry.timestamp)}</span>
+ <span className="min-w-0 flex-1 truncate text-fg-body">{describe(entry)}</span>
+ <button
+ type="button"
+ onClick={() => onOpenDetails(entry)}
+ className="shrink-0 font-semibold text-brand-ink hover:underline"
+ >
+ {t("adminAudit.details")}
+ </button>
+ </div>
+ ))}
+ {remaining > 0 && (
+ <div className="text-[12px] text-fg-faint">{t("adminAudit.routineEntriesMore", { count: remaining })}</div>
+ )}
+ </>
+ );
+}
+
+/** Desktop table row(s) standing in for every routine run of one external sync (13g). */
+export function RoutineBundleRow({
+ bundle,
+ expanded,
+ entries,
+ onToggle,
+ onOpenDetails,
+ template,
+ isSuperAdmin,
+}: RoutineBundleProps & { template: string; isSuperAdmin: boolean }) {
+ const t = useTranslations();
+ const { dateRange, badge } = useBundleDisplay(bundle);
+
+ return (
+ <>
+ <AdminTableRow template={template} onClick={onToggle}>
+ {isSuperAdmin && <span />}
+ <ChevronRight
+ className={cn("size-[15px] transition-transform", expanded ? "rotate-90 text-fg-secondary" : "text-fg-faint")}
+ />
+ <span className="font-mono text-[12.5px] text-fg-body">{dateRange}</span>
+ <span className="max-w-full justify-self-start truncate rounded-[6px] bg-surface-sunken px-2 py-[3px] font-mono text-[12px] font-medium text-fg-body">
+ {badge}
+ </span>
+ <span className="truncate text-[13px] text-fg-tertiary">{t("admin.systemAction")}</span>
+ <span className="justify-self-start">
+ <SeverityPill severity="info" />
+ </span>
+ <span className="truncate text-[12.5px] text-fg-tertiary">
+ {t("adminAudit.routineBundleSummary", { sync: bundle.syncName, calendar: bundle.calendarName })}
+ </span>
+ <span className="truncate font-mono text-[12px] text-fg-tertiary">—</span>
+ <span />
+ </AdminTableRow>
+ {expanded && (
+ <div className="flex flex-col gap-2 border-b border-line-subtle bg-surface-panel px-4 py-3">
+ <RoutineEntriesList bundle={bundle} entries={entries} onOpenDetails={onOpenDetails} />
+ </div>
+ )}
+ </>
+ );
+}
+
+/** Phone card standing in for every routine run of one external sync. */
+export function RoutineBundleMobileCard({ bundle, expanded, entries, onToggle, onOpenDetails }: RoutineBundleProps) {
+ const t = useTranslations();
+ const { dateRange, badge } = useBundleDisplay(bundle);
+
+ return (
+ <>
+ <AdminMobileCard onClick={onToggle} muted>
+ <div className="flex w-full items-center gap-2">
+ <span className="min-w-0 truncate rounded-[6px] bg-surface-sunken px-2 py-[3px] font-mono text-[12px] font-medium text-fg-body">
+ {badge}
+ </span>
+ <span className="flex-1" />
+ <ChevronRight
+ className={cn("size-4 shrink-0 transition-transform", expanded ? "rotate-90 text-fg-secondary" : "text-fg-faint")}
+ />
+ </div>
+ <div className="text-[13.5px] leading-snug text-fg-body">
+ {t("adminAudit.routineBundleSummary", { sync: bundle.syncName, calendar: bundle.calendarName })}
+ </div>
+ <div className="text-[12px] text-fg-tertiary">{dateRange}</div>
+ </AdminMobileCard>
+ {expanded && (
+ <div className="flex flex-col gap-2 rounded-[11px] border border-line-subtle bg-surface-panel px-3.5 py-3">
+ <RoutineEntriesList bundle={bundle} entries={entries} onOpenDetails={onOpenDetails} />
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/hooks/useAdminAuditLogs.ts b/hooks/useAdminAuditLogs.ts
index 02ee1ee..7efdc71 100644
--- a/hooks/useAdminAuditLogs.ts
+++ b/hooks/useAdminAuditLogs.ts
@@ -35,6 +35,17 @@ export interface AuditLogFilters {
search?: string;
startDate?: string;
endDate?: string;
+ isUserVisible?: boolean;
+}
+
+/** One collapsed row standing in for every routine (auto-scheduler) run of one external sync. */
+export interface RoutineAuditLogBundle {
+ resourceId: string;
+ count: number;
+ firstTimestamp: Date;
+ lastTimestamp: Date;
+ syncName: string;
+ calendarName: string;
}
export interface AuditLogSort {
@@ -52,6 +63,7 @@ export interface AuditLogsResponse {
total: number;
limit: number;
offset: number;
+ routineBundles: RoutineAuditLogBundle[];
}
/**
@@ -62,6 +74,7 @@ async function fetchAuditLogsApi(
sort: AuditLogSort,
pagination: AuditLogPagination,
t: ReturnType<typeof useTranslations>,
+ bundleRoutine = false,
): Promise<AuditLogsResponse> {
const params = new URLSearchParams();
@@ -73,11 +86,13 @@ async function fetchAuditLogsApi(
if (filters.search) params.set("search", filters.search);
if (filters.startDate) params.set("startDate", filters.startDate);
if (filters.endDate) params.set("endDate", filters.endDate);
+ if (filters.isUserVisible !== undefined) params.set("isUserVisible", String(filters.isUserVisible));
params.set("sortBy", sort.field);
params.set("sortOrder", sort.direction);
params.set("limit", pagination.limit.toString());
params.set("offset", pagination.offset.toString());
+ if (bundleRoutine) params.set("bundleRoutine", "true");
const response = await fetch(`/api/admin/audit-logs?${params.toString()}`, {
method: "GET",
@@ -100,12 +115,18 @@ async function fetchAuditLogsApi(
...log,
timestamp: new Date(log.timestamp as string),
}));
+ const routineBundles = (data.routineBundles ?? []).map((bundle: Record<string, unknown>) => ({
+ ...bundle,
+ firstTimestamp: new Date(bundle.firstTimestamp as string),
+ lastTimestamp: new Date(bundle.lastTimestamp as string),
+ }));
return {
logs,
total: data.pagination.total,
limit: data.pagination.limit,
offset: data.pagination.offset,
+ routineBundles,
};
}
@@ -180,7 +201,7 @@ export function useAdminAuditLogs(
sort: AuditLogSort = { field: "timestamp", direction: "desc" },
pagination: AuditLogPagination = { limit: 25, offset: 0 },
/** Callers that only need the delete actions skip the polling list query */
- { listEnabled = true }: { listEnabled?: boolean } = {},
+ { listEnabled = true, bundleRoutine = false }: { listEnabled?: boolean; bundleRoutine?: boolean } = {},
) {
const t = useTranslations();
const queryClient = useQueryClient();
@@ -192,8 +213,8 @@ export function useAdminAuditLogs(
error,
refetch,
} = useQuery({
- queryKey: queryKeys.admin.auditLogs({ filters, sort, pagination, t }),
- queryFn: () => fetchAuditLogsApi(filters, sort, pagination, t),
+ queryKey: queryKeys.admin.auditLogs({ filters, sort, pagination, bundleRoutine, t }),
+ queryFn: () => fetchAuditLogsApi(filters, sort, pagination, t, bundleRoutine),
enabled: listEnabled,
refetchInterval: BACKGROUND_REFETCH_INTERVAL,
});
@@ -203,15 +224,15 @@ export function useAdminAuditLogs(
mutationFn: (logIds: string[]) => deleteLogsByIdsApi(logIds, t),
onMutate: async (logIds) => {
await queryClient.cancelQueries({
- queryKey: queryKeys.admin.auditLogs({ filters, sort, pagination }),
+ queryKey: queryKeys.admin.auditLogs({ filters, sort, pagination, bundleRoutine }),
});
const previous = queryClient.getQueryData(
- queryKeys.admin.auditLogs({ filters, sort, pagination }),
+ queryKeys.admin.auditLogs({ filters, sort, pagination, bundleRoutine }),
);
// Optimistic update
queryClient.setQueryData(
- queryKeys.admin.auditLogs({ filters, sort, pagination }),
+ queryKeys.admin.auditLogs({ filters, sort, pagination, bundleRoutine }),
(old: AuditLogsResponse | undefined) => {
if (!old) return old;
return {
@@ -226,7 +247,7 @@ export function useAdminAuditLogs(
},
onError: (err, logIds, context) => {
queryClient.setQueryData(
- queryKeys.admin.auditLogs({ filters, sort, pagination }),
+ queryKeys.admin.auditLogs({ filters, sort, pagination, bundleRoutine }),
context?.previous,
);
toast.error(
@@ -269,6 +290,7 @@ export function useAdminAuditLogs(
total: logsData?.total || 0,
limit: logsData?.limit || pagination.limit,
offset: logsData?.offset || pagination.offset,
+ routineBundles: logsData?.routineBundles || [],
isLoading: isLoading || deleteByIdsMutation.isPending || deleteByDateMutation.isPending,
error,
diff --git a/messages/cs.json b/messages/cs.json
index 4e25e82..dc9f739 100644
--- a/messages/cs.json
+++ b/messages/cs.json
@@ -998,6 +998,13 @@
"severityShort": "Závažnost",
"whatHappened": "Co se stalo",
"details": "Podrobnosti",
+ "bundleRoutine": "Sloučit rutinní",
+ "bundleRoutineDescription": "Sloučit automatické synchronizace do jednoho řádku na synchronizaci",
+ "subtitleWithRoutine": "{total, plural, one {# záznam} few {# záznamy} other {# záznamů}} · {nonRoutine, plural, one {# není rutinní} few {# nejsou rutinní} other {# není rutinní}}",
+ "routineBundledFooter": "{count, plural, one {# rutinní záznam sloučen} few {# rutinní záznamy sloučeny} other {# rutinních záznamů sloučeno}}",
+ "routineEntries": "Jednotlivé běhy",
+ "routineEntriesMore": "{count, plural, one {a # další} few {a # další} other {a # dalších}}",
+ "routineBundleSummary": "„{sync}“ ({calendar})",
"describe": {
"userBanned": "{user} zablokován",
"userBannedPermanently": "{user} trvale zablokován",
diff --git a/messages/de.json b/messages/de.json
index 5874e54..23da259 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -998,6 +998,13 @@
"severityShort": "Schwere",
"whatHappened": "Was passiert ist",
"details": "Details",
+ "bundleRoutine": "Routine bündeln",
+ "bundleRoutineDescription": "Automatische Synchronisierungs-Läufe zu einer Zeile pro Synchronisierung zusammenfassen",
+ "subtitleWithRoutine": "{total, plural, one {# Eintrag} other {# Einträge}} · {nonRoutine, plural, one {# nicht routine} other {# nicht routine}}",
+ "routineBundledFooter": "{count, plural, one {# Routine-Eintrag gebündelt} other {# Routine-Einträge gebündelt}}",
+ "routineEntries": "Einzelne Läufe",
+ "routineEntriesMore": "{count, plural, one {und # weiterer} other {und # weitere}}",
+ "routineBundleSummary": "„{sync}“ ({calendar})",
"describe": {
"userBanned": "{user} gesperrt",
"userBannedPermanently": "{user} dauerhaft gesperrt",
diff --git a/messages/en.json b/messages/en.json
index a3da5f4..ffbc01e 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -998,6 +998,13 @@
"severityShort": "Severity",
"whatHappened": "What happened",
"details": "Details",
+ "bundleRoutine": "Bundle routine",
+ "bundleRoutineDescription": "Collapse automatic sync runs into one row per sync",
+ "subtitleWithRoutine": "{total, plural, one {# entry} other {# entries}} · {nonRoutine, plural, one {# not routine} other {# not routine}}",
+ "routineBundledFooter": "{count, plural, one {# routine entry bundled} other {# routine entries bundled}}",
+ "routineEntries": "Individual runs",
+ "routineEntriesMore": "{count, plural, one {and # more} other {and # more}}",
+ "routineBundleSummary": "“{sync}” ({calendar})",
"describe": {
"userBanned": "{user} banned",
"userBannedPermanently": "{user} banned permanently",
diff --git a/messages/es.json b/messages/es.json
index 1b1814e..2cbe46c 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -998,6 +998,13 @@
"severityShort": "Gravedad",
"whatHappened": "Qué ha pasado",
"details": "Detalles",
+ "bundleRoutine": "Agrupar rutina",
+ "bundleRoutineDescription": "Agrupar las sincronizaciones automáticas en una fila por sincronización",
+ "subtitleWithRoutine": "{total, plural, one {# entrada} other {# entradas}} · {nonRoutine, plural, one {# no rutinaria} other {# no rutinarias}}",
+ "routineBundledFooter": "{count, plural, one {# entrada rutinaria agrupada} other {# entradas rutinarias agrupadas}}",
+ "routineEntries": "Ejecuciones individuales",
+ "routineEntriesMore": "{count, plural, one {y # más} other {y # más}}",
+ "routineBundleSummary": "«{sync}» ({calendar})",
"describe": {
"userBanned": "{user} bloqueado",
"userBannedPermanently": "{user} bloqueado permanentemente",
diff --git a/messages/fr.json b/messages/fr.json
index cf2375c..3af219e 100755
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -998,6 +998,13 @@
"severityShort": "Gravité",
"whatHappened": "Ce qui s’est passé",
"details": "Détails",
+ "bundleRoutine": "Regrouper la routine",
+ "bundleRoutineDescription": "Regrouper les synchronisations automatiques en une seule ligne par synchronisation",
+ "subtitleWithRoutine": "{total, plural, one {# entrée} other {# entrées}} · {nonRoutine, plural, one {# non routinière} other {# non routinières}}",
+ "routineBundledFooter": "{count, plural, one {# entrée de routine regroupée} other {# entrées de routine regroupées}}",
+ "routineEntries": "Exécutions individuelles",
+ "routineEntriesMore": "{count, plural, one {et # de plus} other {et # de plus}}",
+ "routineBundleSummary": "« {sync} » ({calendar})",
"describe": {
"userBanned": "{user} bloqué",
"userBannedPermanently": "{user} bloqué définitivement",
diff --git a/messages/it.json b/messages/it.json
index d8d4cd4..0becc9e 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -998,6 +998,13 @@
"severityShort": "Gravità",
"whatHappened": "Cosa è successo",
"details": "Dettagli",
+ "bundleRoutine": "Raggruppa routine",
+ "bundleRoutineDescription": "Raggruppa le sincronizzazioni automatiche in una riga per sincronizzazione",
+ "subtitleWithRoutine": "{total, plural, one {# voce} other {# voci}} · {nonRoutine, plural, one {# non di routine} other {# non di routine}}",
+ "routineBundledFooter": "{count, plural, one {# voce di routine raggruppata} other {# voci di routine raggruppate}}",
+ "routineEntries": "Esecuzioni singole",
+ "routineEntriesMore": "{count, plural, one {e # in più} other {e # in più}}",
+ "routineBundleSummary": "«{sync}» ({calendar})",
"describe": {
"userBanned": "{user} bloccato",
"userBannedPermanently": "{user} bloccato in modo permanente",