fix(ui): address review on logs-tabs url state

Keep ?tab=deleted-teams while org memberships load so org admins keep
their deep link, stop the hidden Audit Logs panel and failed requests
from clamping the page keys, drop an audit_log_id that is not on the
settled page, keep the drawer close animation, keep the current page
when Deleted Keys/Teams headers are clicked, derive the sort allow-lists
from the column definitions and make table sorting controlled only.
This commit is contained in:
ryan-crabbe-berri 2026-09-16 09:25:35 -07:00
parent d3beb57d22
commit 5111442dab
14 changed files with 458 additions and 105 deletions

View file

@ -1,8 +1,10 @@
import { screen, waitFor, within } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { OnUrlUpdateFunction } from "nuqs/adapters/testing";
import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing";
import type { ReactElement } from "react";
import { vi, it, expect, beforeEach, MockedFunction, type Mock } from "vitest";
import { renderWithProviders } from "../../../tests/test-utils";
import { chooseSelectOption, renderWithProviders, testQueryClient } from "../../../tests/test-utils";
import DeletedKeysPage from "./DeletedKeysPage";
import { useDeletedKeys, DeletedKeyResponse } from "@/app/(dashboard)/hooks/keys/useKeys";
@ -154,6 +156,20 @@ const rowAliases = (aliases: string[]) =>
const lastUrl = (onUrlUpdate: Mock<OnUrlUpdateFunction>) => onUrlUpdate.mock.calls.at(-1)?.[0].searchParams;
const renderKeepingUrlWrites = (ui: ReactElement, searchParams: string, onUrlUpdate: OnUrlUpdateFunction) =>
render(
<NuqsTestingAdapter
searchParams={searchParams}
onUrlUpdate={onUrlUpdate}
hasMemory
resetUrlUpdateQueueOnMount={false}
>
<QueryClientProvider client={testQueryClient}>{ui}</QueryClientProvider>
</NuqsTestingAdapter>,
);
const flushUrlWrites = () => new Promise((resolve) => setTimeout(resolve, 150));
it("requests the page and page size named by the deleted_keys_ URL keys", () => {
renderWithProviders(<DeletedKeysPage />, { searchParams: { deleted_keys_page: "3", deleted_keys_page_size: "25" } });
@ -179,6 +195,34 @@ it("writes deleted_keys_page when the next page is requested", async () => {
expect(mockUseDeletedKeys).toHaveBeenLastCalledWith(2, 50);
});
it("writes deleted_keys_page_size when the page size changes", async () => {
const user = userEvent.setup();
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
mockUseDeletedKeys.mockReturnValue(deletedKeysResult([mockDeletedKey], 120));
renderWithProviders(<DeletedKeysPage />, { onUrlUpdate });
await chooseSelectOption(user, screen.getByTestId("pagination-page-size"), "100");
await waitFor(() => expect(lastUrl(onUrlUpdate)?.get("deleted_keys_page_size")).toBe("100"));
expect(lastUrl(onUrlUpdate)?.has("page_size")).toBe(false);
expect(mockUseDeletedKeys).toHaveBeenLastCalledWith(1, 100);
});
it("keeps ?deleted_keys_page= when the deleted keys request fails", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
mockUseDeletedKeys.mockReturnValue({
data: undefined,
isLoading: false,
isError: true,
} as unknown as ReturnType<typeof useDeletedKeys>);
renderKeepingUrlWrites(<DeletedKeysPage />, "?deleted_keys_page=3", onUrlUpdate);
await flushUrlWrites();
expect(onUrlUpdate).not.toHaveBeenCalled();
expect(mockUseDeletedKeys).toHaveBeenLastCalledWith(3, 50);
});
it.each([
["asc", ["cheap-key", "pricey-key"]],
["desc", ["pricey-key", "cheap-key"]],
@ -192,24 +236,36 @@ it.each([
});
it("falls back to deleted_at descending when deleted_keys_sort_by is not a sortable column", () => {
mockUseDeletedKeys.mockReturnValue(deletedKeysResult(SORT_KEYS, 2));
mockUseDeletedKeys.mockReturnValue(deletedKeysResult([...SORT_KEYS].reverse(), 2));
renderWithProviders(<DeletedKeysPage />, { searchParams: { deleted_keys_sort_by: "key_alias" } });
expect(rowAliases(["cheap-key", "pricey-key"])).toEqual(["cheap-key", "pricey-key"]);
});
it("writes deleted_keys_sort_by and a direction that matches the rendered order when a header is clicked", async () => {
it("writes deleted_keys_sort_by and deleted_keys_sort_order when a sorted header is clicked again", async () => {
const user = userEvent.setup();
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
mockUseDeletedKeys.mockReturnValue(deletedKeysResult(SORT_KEYS, 2));
renderWithProviders(<DeletedKeysPage />, { onUrlUpdate });
renderWithProviders(<DeletedKeysPage />, { searchParams: { deleted_keys_sort_by: "spend" }, onUrlUpdate });
expect(rowAliases(["cheap-key", "pricey-key"])).toEqual(["pricey-key", "cheap-key"]);
await user.click(screen.getByTestId("sort-header-spend"));
await waitFor(() => expect(lastUrl(onUrlUpdate)?.get("deleted_keys_sort_order")).toBe("asc"));
expect(lastUrl(onUrlUpdate)?.get("deleted_keys_sort_by")).toBe("spend");
expect(lastUrl(onUrlUpdate)?.has("sort_by")).toBe(false);
expect(rowAliases(["cheap-key", "pricey-key"])).toEqual(["cheap-key", "pricey-key"]);
});
it("stays on the current page when a header is clicked, since sorting only reorders the loaded page", async () => {
const user = userEvent.setup();
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
mockUseDeletedKeys.mockReturnValue(deletedKeysResult(SORT_KEYS, 120));
renderWithProviders(<DeletedKeysPage />, { searchParams: { deleted_keys_page: "3" }, onUrlUpdate });
await user.click(screen.getByTestId("sort-header-spend"));
await waitFor(() => expect(lastUrl(onUrlUpdate)?.get("deleted_keys_sort_by")).toBe("spend"));
const ascending = lastUrl(onUrlUpdate)?.get("deleted_keys_sort_order") === "asc";
expect(rowAliases(["cheap-key", "pricey-key"])).toEqual(
ascending ? ["cheap-key", "pricey-key"] : ["pricey-key", "cheap-key"],
);
expect(lastUrl(onUrlUpdate)?.has("sort_by")).toBe(false);
expect(lastUrl(onUrlUpdate)?.get("deleted_keys_page")).toBe("3");
expect(mockUseDeletedKeys).toHaveBeenLastCalledWith(3, 50);
});

View file

@ -1,4 +1,6 @@
"use client";
import { useCallback } from "react";
import { OnChangeFn, SortingState } from "@tanstack/react-table";
import { Info } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/shared/Alert";
import { useUrlTableState, type UrlTableStateOptions } from "@/components/shared/DataTable";
@ -18,6 +20,13 @@ const TABLE_STATE_OPTIONS: UrlTableStateOptions<never> = {
export default function DeletedKeysPage() {
const { premiumUser } = useAuthorized();
const { sorting, onSortingChange, pagination, onPaginationChange } = useUrlTableState(TABLE_STATE_OPTIONS);
const sortLoadedPage = useCallback<OnChangeFn<SortingState>>(
(updater) => {
onSortingChange(updater);
onPaginationChange(pagination);
},
[onSortingChange, onPaginationChange, pagination],
);
const { data: keysData, isLoading, isError } = useDeletedKeys(pagination.pageIndex + 1, pagination.pageSize);
@ -38,7 +47,7 @@ export default function DeletedKeysPage() {
isLoading={isLoading}
isError={isError}
sorting={sorting}
onSortingChange={onSortingChange}
onSortingChange={sortLoadedPage}
pagination={pagination}
onPaginationChange={onPaginationChange}
/>

View file

@ -1,3 +1,4 @@
import { functionalUpdate, type SortingState, type Updater } from "@tanstack/react-table";
import { screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { vi, it, expect, beforeEach } from "vitest";
@ -29,10 +30,14 @@ const makeDeletedKey = (overrides: Partial<DeletedKeyResponse> = {}): DeletedKey
...overrides,
}) as DeletedKeyResponse;
const DELETED_AT_DESC: SortingState = [{ id: "deleted_at", desc: true }];
const defaultProps = {
keys: [makeDeletedKey()],
totalCount: 1,
isLoading: false,
sorting: DELETED_AT_DESC,
onSortingChange: vi.fn(),
pagination: { pageIndex: 0, pageSize: 50 },
onPaginationChange: vi.fn(),
};
@ -65,7 +70,7 @@ it("should propagate pagination changes when the next page button is clicked", a
expect(defaultProps.onPaginationChange).toHaveBeenCalled();
});
it("should sort the current page by deleted_at descending by default", () => {
it("sorts the current page by the deleted_at descending sorting it is given", () => {
const keys = [
makeDeletedKey({ token: "sk-older", key_alias: "older-key", deleted_at: "2024-01-01T10:00:00Z" }),
makeDeletedKey({ token: "sk-newer", key_alias: "newer-key", deleted_at: "2024-06-01T10:00:00Z" }),
@ -107,7 +112,7 @@ it("leaves the default_user_id placeholder unlinked", () => {
it("sorts by the controlled sorting prop and reports header clicks through onSortingChange", async () => {
const user = userEvent.setup();
const onSortingChange = vi.fn();
const onSortingChange = vi.fn<(updater: Updater<SortingState>) => void>();
const keys = [
makeDeletedKey({ token: "sk-cheap", key_alias: "cheap-key", spend: 1 }),
makeDeletedKey({ token: "sk-pricey", key_alias: "pricey-key", spend: 9 }),
@ -129,4 +134,6 @@ it("sorts by the controlled sorting prop and reports header clicks through onSor
await user.click(screen.getByTestId("sort-header-deleted_at"));
expect(onSortingChange).toHaveBeenCalledTimes(1);
const [next] = functionalUpdate(onSortingChange.mock.calls[0][0], [{ id: "spend", desc: true }]);
expect(next?.id).toBe("deleted_at");
});

View file

@ -2,7 +2,7 @@
import { OnChangeFn, PaginationState, SortingState } from "@tanstack/react-table";
import { Inbox } from "lucide-react";
import { useMemo, useState } from "react";
import { useMemo } from "react";
import { DataTable } from "@/components/shared/DataTable";
import { DeletedKeyResponse } from "@/app/(dashboard)/hooks/keys/useKeys";
@ -14,14 +14,12 @@ interface DeletedKeysTableProps {
totalCount: number;
isLoading: boolean;
isError?: boolean;
sorting?: SortingState;
onSortingChange?: OnChangeFn<SortingState>;
sorting: SortingState;
onSortingChange: OnChangeFn<SortingState>;
pagination: PaginationState;
onPaginationChange: OnChangeFn<PaginationState>;
}
const DEFAULT_SORTING: SortingState = [{ id: "deleted_at", desc: true }];
function EmptyState() {
return (
<div className="flex flex-col items-center gap-1 py-6">
@ -44,8 +42,6 @@ export function DeletedKeysTable({
pagination,
onPaginationChange,
}: DeletedKeysTableProps) {
const [internalSorting, setInternalSorting] = useState<SortingState>(DEFAULT_SORTING);
const columns = useMemo(() => getDeletedKeysTableColumns(), []);
return (
@ -54,8 +50,8 @@ export function DeletedKeysTable({
columns={columns}
getRowId={(key, index) => key.token || String(index)}
sortingMode="client"
sorting={sorting ?? internalSorting}
onSortingChange={onSortingChange ?? setInternalSorting}
sorting={sorting}
onSortingChange={onSortingChange}
paginationMode="server"
pagination={pagination}
onPaginationChange={onPaginationChange}

View file

@ -29,8 +29,6 @@ function UserLinkCell({ userId }: { userId: string | null | undefined }) {
);
}
export const DELETED_KEYS_SORT_FIELDS: readonly string[] = ["spend", "created_at", "deleted_at"];
export const getDeletedKeysTableColumns = (): ColumnDef<DeletedKeyResponse>[] => [
{
id: "token",
@ -142,3 +140,7 @@ export const getDeletedKeysTableColumns = (): ColumnDef<DeletedKeyResponse>[] =>
cell: ({ row }) => <UserLinkCell userId={row.original.deleted_by} />,
},
];
export const DELETED_KEYS_SORT_FIELDS: readonly string[] = getDeletedKeysTableColumns().flatMap((column) =>
column.enableSorting && column.id ? [column.id] : [],
);

View file

@ -1,8 +1,10 @@
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { OnUrlUpdateFunction } from "nuqs/adapters/testing";
import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing";
import type { ReactElement } from "react";
import { vi, it, expect, beforeEach, MockedFunction, type Mock } from "vitest";
import { renderWithProviders } from "../../../tests/test-utils";
import { renderWithProviders, testQueryClient } from "../../../tests/test-utils";
import DeletedTeamsPage from "./DeletedTeamsPage";
import { useDeletedTeams, DeletedTeam } from "@/app/(dashboard)/hooks/teams/useTeams";
@ -71,14 +73,15 @@ it("requests the next page from the server when Next is clicked", () => {
expect(mockUseDeletedTeams).toHaveBeenLastCalledWith(2, 25);
});
it("offers the shared page sizes and refetches with the selected one", async () => {
it("offers the shared page sizes, refetches with the selected one and writes deleted_teams_page_size", async () => {
const user = userEvent.setup();
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
mockUseDeletedTeams.mockReturnValue({
data: { teams: [mockDeletedTeam], total: 137 },
isLoading: false,
} as unknown as ReturnType<typeof useDeletedTeams>);
renderWithProviders(<DeletedTeamsPage />);
renderWithProviders(<DeletedTeamsPage />, { onUrlUpdate });
await user.click(screen.getByTestId("pagination-page-size"));
const options = await screen.findAllByRole("option");
@ -87,6 +90,10 @@ it("offers the shared page sizes and refetches with the selected one", async ()
await user.click(screen.getByRole("option", { name: "100" }));
expect(mockUseDeletedTeams).toHaveBeenLastCalledWith(1, 100);
await waitFor(() =>
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("deleted_teams_page_size")).toBe("100"),
);
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has("page_size")).toBe(false);
});
it("should show the enterprise notice for a non-premium user", () => {
@ -131,6 +138,20 @@ const rowAliases = (aliases: string[]) =>
const lastUrl = (onUrlUpdate: Mock<OnUrlUpdateFunction>) => onUrlUpdate.mock.calls.at(-1)?.[0].searchParams;
const renderKeepingUrlWrites = (ui: ReactElement, searchParams: string, onUrlUpdate: OnUrlUpdateFunction) =>
render(
<NuqsTestingAdapter
searchParams={searchParams}
onUrlUpdate={onUrlUpdate}
hasMemory
resetUrlUpdateQueueOnMount={false}
>
<QueryClientProvider client={testQueryClient}>{ui}</QueryClientProvider>
</NuqsTestingAdapter>,
);
const flushUrlWrites = () => new Promise((resolve) => setTimeout(resolve, 150));
it("requests the page and page size named by the deleted_teams_ URL keys", () => {
renderWithProviders(<DeletedTeamsPage />, {
searchParams: { deleted_teams_page: "3", deleted_teams_page_size: "50" },
@ -158,6 +179,21 @@ it("writes deleted_teams_page when the next page is requested", async () => {
expect(mockUseDeletedTeams).toHaveBeenLastCalledWith(2, 25);
});
it("keeps ?deleted_teams_page= when the deleted teams request fails", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
mockUseDeletedTeams.mockReturnValue({
data: undefined,
isLoading: false,
isError: true,
} as unknown as ReturnType<typeof useDeletedTeams>);
renderKeepingUrlWrites(<DeletedTeamsPage />, "?deleted_teams_page=3", onUrlUpdate);
await flushUrlWrites();
expect(onUrlUpdate).not.toHaveBeenCalled();
expect(mockUseDeletedTeams).toHaveBeenLastCalledWith(3, 25);
});
it.each([
["asc", ["cheap-team", "pricey-team"]],
["desc", ["pricey-team", "cheap-team"]],
@ -171,24 +207,36 @@ it.each([
});
it("falls back to deleted_at descending when deleted_teams_sort_by is not a sortable column", () => {
mockUseDeletedTeams.mockReturnValue(deletedTeamsResult(SORT_TEAMS, 2));
mockUseDeletedTeams.mockReturnValue(deletedTeamsResult([...SORT_TEAMS].reverse(), 2));
renderWithProviders(<DeletedTeamsPage />, { searchParams: { deleted_teams_sort_by: "team_alias" } });
expect(rowAliases(["cheap-team", "pricey-team"])).toEqual(["cheap-team", "pricey-team"]);
});
it("writes deleted_teams_sort_by and a direction that matches the rendered order when a header is clicked", async () => {
it("writes deleted_teams_sort_by and deleted_teams_sort_order when a sorted header is clicked again", async () => {
const user = userEvent.setup();
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
mockUseDeletedTeams.mockReturnValue(deletedTeamsResult(SORT_TEAMS, 2));
renderWithProviders(<DeletedTeamsPage />, { onUrlUpdate });
renderWithProviders(<DeletedTeamsPage />, { searchParams: { deleted_teams_sort_by: "spend" }, onUrlUpdate });
expect(rowAliases(["cheap-team", "pricey-team"])).toEqual(["pricey-team", "cheap-team"]);
await user.click(screen.getByTestId("sort-header-spend"));
await waitFor(() => expect(lastUrl(onUrlUpdate)?.get("deleted_teams_sort_order")).toBe("asc"));
expect(lastUrl(onUrlUpdate)?.get("deleted_teams_sort_by")).toBe("spend");
expect(lastUrl(onUrlUpdate)?.has("sort_by")).toBe(false);
expect(rowAliases(["cheap-team", "pricey-team"])).toEqual(["cheap-team", "pricey-team"]);
});
it("stays on the current page when a header is clicked, since sorting only reorders the loaded page", async () => {
const user = userEvent.setup();
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
mockUseDeletedTeams.mockReturnValue(deletedTeamsResult(SORT_TEAMS, 137));
renderWithProviders(<DeletedTeamsPage />, { searchParams: { deleted_teams_page: "3" }, onUrlUpdate });
await user.click(screen.getByTestId("sort-header-spend"));
await waitFor(() => expect(lastUrl(onUrlUpdate)?.get("deleted_teams_sort_by")).toBe("spend"));
const ascending = lastUrl(onUrlUpdate)?.get("deleted_teams_sort_order") === "asc";
expect(rowAliases(["cheap-team", "pricey-team"])).toEqual(
ascending ? ["cheap-team", "pricey-team"] : ["pricey-team", "cheap-team"],
);
expect(lastUrl(onUrlUpdate)?.has("sort_by")).toBe(false);
expect(lastUrl(onUrlUpdate)?.get("deleted_teams_page")).toBe("3");
expect(mockUseDeletedTeams).toHaveBeenLastCalledWith(3, 25);
});

View file

@ -1,4 +1,6 @@
"use client";
import { useCallback } from "react";
import { OnChangeFn, SortingState } from "@tanstack/react-table";
import { Info } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/shared/Alert";
import { DEFAULT_PAGE_SIZE_OPTIONS, useUrlTableState, type UrlTableStateOptions } from "@/components/shared/DataTable";
@ -18,6 +20,13 @@ const TABLE_STATE_OPTIONS: UrlTableStateOptions<never> = {
export default function DeletedTeamsPage() {
const { premiumUser } = useAuthorized();
const { sorting, onSortingChange, pagination, onPaginationChange } = useUrlTableState(TABLE_STATE_OPTIONS);
const sortLoadedPage = useCallback<OnChangeFn<SortingState>>(
(updater) => {
onSortingChange(updater);
onPaginationChange(pagination);
},
[onSortingChange, onPaginationChange, pagination],
);
const { data: teamsData, isLoading, isError } = useDeletedTeams(pagination.pageIndex + 1, pagination.pageSize);
return (
@ -36,7 +45,7 @@ export default function DeletedTeamsPage() {
isLoading={isLoading}
isError={isError}
sorting={sorting}
onSortingChange={onSortingChange}
onSortingChange={sortLoadedPage}
pagination={pagination}
onPaginationChange={onPaginationChange}
rowCount={teamsData?.total ?? 0}

View file

@ -1,3 +1,4 @@
import { functionalUpdate, type SortingState, type Updater } from "@tanstack/react-table";
import { screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { vi, it, expect, beforeEach } from "vitest";
@ -25,7 +26,11 @@ const makeDeletedTeam = (overrides: Partial<DeletedTeam> = {}): DeletedTeam => (
...overrides,
});
const DELETED_AT_DESC: SortingState = [{ id: "deleted_at", desc: true }];
const paginationProps = {
sorting: DELETED_AT_DESC,
onSortingChange: vi.fn(),
pagination: { pageIndex: 0, pageSize: 25 },
onPaginationChange: vi.fn(),
};
@ -44,7 +49,7 @@ it("should display team information", () => {
expect(screen.getByText("org-1")).toBeInTheDocument();
});
it("should sort teams by deleted_at descending by default", () => {
it("sorts teams by the deleted_at descending sorting it is given", () => {
const teams = [
makeDeletedTeam({ team_id: "team-old", team_alias: "older-team", deleted_at: "2024-01-01T10:00:00Z" }),
makeDeletedTeam({ team_id: "team-new", team_alias: "newer-team", deleted_at: "2024-06-01T10:00:00Z" }),
@ -74,6 +79,8 @@ it("renders the shared pagination footer with the server row count", () => {
teams={[makeDeletedTeam()]}
isLoading={false}
rowCount={137}
sorting={DELETED_AT_DESC}
onSortingChange={vi.fn()}
pagination={{ pageIndex: 2, pageSize: 50 }}
onPaginationChange={vi.fn()}
/>,
@ -105,7 +112,7 @@ it("leaves the default_user_id placeholder unlinked in the deleted by cell", ()
it("sorts by the controlled sorting prop and reports header clicks through onSortingChange", async () => {
const user = userEvent.setup();
const onSortingChange = vi.fn();
const onSortingChange = vi.fn<(updater: Updater<SortingState>) => void>();
const teams = [
makeDeletedTeam({ team_id: "team-cheap", team_alias: "cheap-team", spend: 1 }),
makeDeletedTeam({ team_id: "team-pricey", team_alias: "pricey-team", spend: 9 }),
@ -115,9 +122,9 @@ it("sorts by the controlled sorting prop and reports header clicks through onSor
teams={teams}
isLoading={false}
rowCount={2}
{...paginationProps}
sorting={[{ id: "spend", desc: true }]}
onSortingChange={onSortingChange}
{...paginationProps}
/>,
);
@ -128,4 +135,6 @@ it("sorts by the controlled sorting prop and reports header clicks through onSor
await user.click(screen.getByTestId("sort-header-deleted_at"));
expect(onSortingChange).toHaveBeenCalledTimes(1);
const [next] = functionalUpdate(onSortingChange.mock.calls[0][0], [{ id: "spend", desc: true }]);
expect(next?.id).toBe("deleted_at");
});

View file

@ -2,7 +2,7 @@
import { OnChangeFn, PaginationState, SortingState } from "@tanstack/react-table";
import { Inbox } from "lucide-react";
import { useMemo, useState } from "react";
import { useMemo } from "react";
import { DataTable } from "@/components/shared/DataTable";
import { DeletedTeam } from "@/app/(dashboard)/hooks/teams/useTeams";
@ -13,15 +13,13 @@ interface DeletedTeamsTableProps {
teams: DeletedTeam[];
isLoading: boolean;
isError?: boolean;
sorting?: SortingState;
onSortingChange?: OnChangeFn<SortingState>;
sorting: SortingState;
onSortingChange: OnChangeFn<SortingState>;
pagination: PaginationState;
onPaginationChange: OnChangeFn<PaginationState>;
rowCount: number;
}
const DEFAULT_SORTING: SortingState = [{ id: "deleted_at", desc: true }];
function EmptyState() {
return (
<div className="flex flex-col items-center gap-1 py-6">
@ -44,8 +42,6 @@ export function DeletedTeamsTable({
onPaginationChange,
rowCount,
}: DeletedTeamsTableProps) {
const [internalSorting, setInternalSorting] = useState<SortingState>(DEFAULT_SORTING);
const columns = useMemo(() => getDeletedTeamsTableColumns(), []);
return (
@ -54,8 +50,8 @@ export function DeletedTeamsTable({
columns={columns}
getRowId={(team, index) => team.team_id || String(index)}
sortingMode="client"
sorting={sorting ?? internalSorting}
onSortingChange={onSortingChange ?? setInternalSorting}
sorting={sorting}
onSortingChange={onSortingChange}
paginationMode="server"
pagination={pagination}
onPaginationChange={onPaginationChange}

View file

@ -18,8 +18,6 @@ function EntityCell({ value, href }: { value: string | null | undefined; href: s
);
}
export const DELETED_TEAMS_SORT_FIELDS: readonly string[] = ["spend", "created_at", "deleted_at"];
export const getDeletedTeamsTableColumns = (): ColumnDef<DeletedTeam>[] => [
{
id: "team_alias",
@ -119,3 +117,7 @@ export const getDeletedTeamsTableColumns = (): ColumnDef<DeletedTeam>[] => [
},
},
];
export const DELETED_TEAMS_SORT_FIELDS: readonly string[] = getDeletedTeamsTableColumns().flatMap((column) =>
column.enableSorting && column.id ? [column.id] : [],
);

View file

@ -1,6 +1,7 @@
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { OnUrlUpdateFunction } from "nuqs/adapters/testing";
import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing";
import { beforeEach, describe, expect, it, type Mock, vi } from "vitest";
import { chooseSelectOption, renderWithProviders, testQueryClient } from "../../../tests/test-utils";
@ -58,17 +59,24 @@ const ROWS: AuditLogEntry[] = [
},
];
const respondWith = (total: number, rows: AuditLogEntry[] = []) => {
const response = {
audit_logs: rows,
total,
page: 1,
page_size: PAGE_SIZE,
total_pages: Math.ceil(total / PAGE_SIZE),
};
return vi.mocked(uiAuditLogsCall).mockResolvedValue(response);
const PAGE_TWO_ROW: AuditLogEntry = {
...ROWS[0],
id: "log-3",
object_id: "key-obj-789",
table_name: "LiteLLM_VerificationToken",
};
const auditLogsResponse = (total: number, rows: AuditLogEntry[] = [], page = 1) => ({
audit_logs: rows,
total,
page,
page_size: PAGE_SIZE,
total_pages: Math.ceil(total / PAGE_SIZE),
});
const respondWith = (total: number, rows: AuditLogEntry[] = []) =>
vi.mocked(uiAuditLogsCall).mockResolvedValue(auditLogsResponse(total, rows));
const lastCall = () => vi.mocked(uiAuditLogsCall).mock.calls.at(-1)?.[0];
const sentIdParams = () => ID_PARAM_KEYS.filter((key) => lastCall()?.params?.[key] !== undefined);
const lastUrl = (onUrlUpdate: Mock<OnUrlUpdateFunction>) => onUrlUpdate.mock.calls.at(-1)?.[0];
@ -90,11 +98,39 @@ interface UrlOptions {
const renderPanel = (urlOptions: UrlOptions = {}) =>
renderWithProviders(<AuditLogsPanel {...defaultProps} />, urlOptions);
const TEXT_FILTERS: { filterId: string; placeholder: string; paramKey: keyof AuditLogsParams }[] = [
{ filterId: "object_id", placeholder: "Enter object ID…", paramKey: "object_id" },
{ filterId: "changed_by", placeholder: "Enter user ID…", paramKey: "changed_by" },
{ filterId: "team_id", placeholder: "Enter team ID…", paramKey: "object_team_id" },
{ filterId: "key_hash", placeholder: "Enter key hash…", paramKey: "object_key_hash" },
interface UrlHarnessProps {
searchParams: string;
onUrlUpdate: OnUrlUpdateFunction;
isActive?: boolean;
}
function UrlHarness({ searchParams, onUrlUpdate, isActive = true }: UrlHarnessProps) {
return (
<NuqsTestingAdapter
searchParams={searchParams}
onUrlUpdate={onUrlUpdate}
hasMemory
resetUrlUpdateQueueOnMount={false}
>
<QueryClientProvider client={testQueryClient}>
<AuditLogsPanel {...defaultProps} isActive={isActive} />
</QueryClientProvider>
</NuqsTestingAdapter>
);
}
const flushUrlWrites = () => new Promise((resolve) => setTimeout(resolve, 150));
const TEXT_FILTERS: { filterId: string; placeholder: string; paramKey: keyof AuditLogsParams; urlKey: string }[] = [
{ filterId: "object_id", placeholder: "Enter object ID…", paramKey: "object_id", urlKey: "audit_filter_object_id" },
{ filterId: "changed_by", placeholder: "Enter user ID…", paramKey: "changed_by", urlKey: "audit_filter_changed_by" },
{ filterId: "team_id", placeholder: "Enter team ID…", paramKey: "object_team_id", urlKey: "audit_filter_team" },
{
filterId: "key_hash",
placeholder: "Enter key hash…",
paramKey: "object_key_hash",
urlKey: "audit_filter_key_hash",
},
];
const SELECT_FILTERS: {
@ -103,9 +139,29 @@ const SELECT_FILTERS: {
option: string;
paramKey: keyof AuditLogsParams;
value: string;
urlKey: string;
}[] = [
{ label: "Action", comboboxIndex: 0, option: "Created", paramKey: "action", value: "created" },
{ label: "Table", comboboxIndex: 1, option: "Teams", paramKey: "table_name", value: "LiteLLM_TeamTable" },
{
label: "Action",
comboboxIndex: 0,
option: "Created",
paramKey: "action",
value: "created",
urlKey: "audit_filter_action",
},
{
label: "Table",
comboboxIndex: 1,
option: "Teams",
paramKey: "table_name",
value: "LiteLLM_TeamTable",
urlKey: "audit_filter_table",
},
];
const URL_FILTERS = [
...TEXT_FILTERS.map(({ urlKey, paramKey }) => ({ urlKey, paramKey, value: "val-1" })),
...SELECT_FILTERS.map(({ urlKey, paramKey, value }) => ({ urlKey, paramKey, value })),
];
describe("AuditLogsPanel", () => {
@ -145,24 +201,30 @@ describe("AuditLogsPanel", () => {
expect(lastUrl(onUrlUpdate)?.searchParams.has("audit_search")).toBe(false);
});
it.each(TEXT_FILTERS)("maps the $filterId drawer filter to params.$paramKey", async ({ placeholder, paramKey }) => {
const user = userEvent.setup();
renderPanel();
await waitFor(() => expect(uiAuditLogsCall).toHaveBeenCalled());
it.each(TEXT_FILTERS)(
"maps the $filterId drawer filter to params.$paramKey and ?$urlKey=",
async ({ placeholder, paramKey, urlKey }) => {
const user = userEvent.setup();
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
renderPanel({ onUrlUpdate });
await waitFor(() => expect(uiAuditLogsCall).toHaveBeenCalled());
await user.click(screen.getByTestId("datatable-filters-trigger"));
fireEvent.change(await screen.findByPlaceholderText(placeholder), { target: { value: "val-1" } });
await user.click(screen.getByTestId("filter-drawer-apply"));
await user.click(screen.getByTestId("datatable-filters-trigger"));
fireEvent.change(await screen.findByPlaceholderText(placeholder), { target: { value: "val-1" } });
await user.click(screen.getByTestId("filter-drawer-apply"));
await waitFor(() => expect(lastCall()?.params?.[paramKey]).toBe("val-1"));
expect(sentIdParams()).toEqual([paramKey]);
});
await waitFor(() => expect(lastCall()?.params?.[paramKey]).toBe("val-1"));
expect(sentIdParams()).toEqual([paramKey]);
await waitFor(() => expect(lastUrl(onUrlUpdate)?.searchParams.get(urlKey)).toBe("val-1"));
},
);
it.each(SELECT_FILTERS)(
"maps the $label drawer select to params.$paramKey",
async ({ comboboxIndex, option, paramKey, value }) => {
"maps the $label drawer select to params.$paramKey and ?$urlKey=",
async ({ comboboxIndex, option, paramKey, value, urlKey }) => {
const user = userEvent.setup();
renderPanel();
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
renderPanel({ onUrlUpdate });
await waitFor(() => expect(uiAuditLogsCall).toHaveBeenCalled());
await user.click(screen.getByTestId("datatable-filters-trigger"));
@ -172,6 +234,7 @@ describe("AuditLogsPanel", () => {
await waitFor(() => expect(lastCall()?.params?.[paramKey]).toBe(value));
expect(sentIdParams()).toEqual([paramKey]);
await waitFor(() => expect(lastUrl(onUrlUpdate)?.searchParams.get(urlKey)).toBe(value));
},
);
@ -204,6 +267,56 @@ describe("AuditLogsPanel", () => {
await waitFor(() => expect(screen.getByTestId("pagination-page")).toHaveTextContent("Page 2 of 5"));
});
it.each(URL_FILTERS)("sends ?$urlKey= as params.$paramKey", async ({ urlKey, paramKey, value }) => {
renderPanel({ searchParams: { [urlKey]: value } });
await waitFor(() => expect(lastCall()?.params?.[paramKey]).toBe(value));
expect(sentIdParams()).toEqual([paramKey]);
});
it("writes audit_page_size when the page size changes", async () => {
const user = userEvent.setup();
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
respondWith(120);
renderPanel({ onUrlUpdate });
await waitFor(() => expect(uiAuditLogsCall).toHaveBeenCalled());
await chooseSelectOption(user, screen.getByTestId("pagination-page-size"), "100");
await waitFor(() => expect(lastUrl(onUrlUpdate)?.searchParams.get("audit_page_size")).toBe("100"));
expect(lastUrl(onUrlUpdate)?.searchParams.has("page_size")).toBe(false);
await waitFor(() => expect(lastCall()?.page_size).toBe(100));
});
it("keeps ?audit_page= while the tab is inactive, then requests that page once it opens", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
respondWith(120);
const { rerender } = render(
<UrlHarness searchParams="?audit_page=3" onUrlUpdate={onUrlUpdate} isActive={false} />,
);
await flushUrlWrites();
expect(onUrlUpdate).not.toHaveBeenCalled();
expect(uiAuditLogsCall).not.toHaveBeenCalled();
rerender(<UrlHarness searchParams="?audit_page=3" onUrlUpdate={onUrlUpdate} />);
await waitFor(() => expect(lastCall()?.page).toBe(3));
expect(onUrlUpdate).not.toHaveBeenCalled();
});
it("keeps ?audit_page= when the audit log request fails", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
vi.mocked(uiAuditLogsCall).mockRejectedValue(new Error("audit logs unavailable"));
render(<UrlHarness searchParams="?audit_page=3" onUrlUpdate={onUrlUpdate} />);
await waitFor(() => expect(uiAuditLogsCall).toHaveBeenCalled());
await flushUrlWrites();
expect(onUrlUpdate).not.toHaveBeenCalled();
expect(lastCall()?.page).toBe(3);
});
it("ignores the unprefixed page, search and filter keys that belong to Request Logs", async () => {
renderPanel({ searchParams: { page: "4", search: "nope", filter_team: "other-team" } });
@ -263,22 +376,61 @@ describe("AuditLogsPanel", () => {
describe("detail drawer deep link", () => {
it("opens the drawer for ?audit_log_id= when that row is on the loaded page", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
respondWith(2, ROWS);
renderPanel({ searchParams: { audit_log_id: "log-2" } });
render(<UrlHarness searchParams="?audit_log_id=log-2" onUrlUpdate={onUrlUpdate} />);
const dialog = await screen.findByRole("dialog");
expect(within(dialog).getByText("user-obj-456")).toBeInTheDocument();
expect(within(dialog).queryByText("team-obj-123")).not.toBeInTheDocument();
await flushUrlWrites();
expect(onUrlUpdate).not.toHaveBeenCalled();
});
it("keeps the drawer closed when ?audit_log_id= is not on the loaded page", async () => {
it("keeps the drawer closed and drops ?audit_log_id= when that row is not on the loaded page", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
respondWith(2, ROWS);
renderPanel({ searchParams: { audit_log_id: "log-missing" } });
render(<UrlHarness searchParams="?audit_log_id=log-missing&audit_page_size=25" onUrlUpdate={onUrlUpdate} />);
await screen.findByText("team-obj-123");
await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
expect(lastUrl(onUrlUpdate)?.searchParams.has("audit_log_id")).toBe(false);
expect(lastUrl(onUrlUpdate)?.searchParams.get("audit_page_size")).toBe("25");
expect(lastUrl(onUrlUpdate)?.options.history).toBe("replace");
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
it("drops ?audit_log_id= while the Audit Logs tab is inactive", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
respondWith(2, ROWS);
render(<UrlHarness searchParams="?audit_log_id=log-1" onUrlUpdate={onUrlUpdate} isActive={false} />);
await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
expect(lastUrl(onUrlUpdate)?.searchParams.has("audit_log_id")).toBe(false);
expect(uiAuditLogsCall).not.toHaveBeenCalled();
});
it("waits for the requested page instead of dropping ?audit_log_id= against the previous page's rows", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
const pageTwo = Promise.withResolvers<Awaited<ReturnType<typeof uiAuditLogsCall>>>();
vi.mocked(uiAuditLogsCall).mockImplementation(({ page }) =>
page === 2 ? pageTwo.promise : Promise.resolve(auditLogsResponse(120, ROWS)),
);
const { rerender } = render(<UrlHarness searchParams="" onUrlUpdate={onUrlUpdate} />);
await screen.findByText("team-obj-123");
rerender(<UrlHarness searchParams="?audit_page=2&audit_log_id=log-3" onUrlUpdate={onUrlUpdate} />);
await waitFor(() => expect(lastCall()?.page).toBe(2));
await flushUrlWrites();
expect(onUrlUpdate).not.toHaveBeenCalled();
pageTwo.resolve(auditLogsResponse(120, [PAGE_TWO_ROW], 2));
const dialog = await screen.findByRole("dialog");
expect(within(dialog).getByText("key-obj-789")).toBeInTheDocument();
expect(onUrlUpdate).not.toHaveBeenCalled();
});
it("pushes ?audit_log_id= when a row is opened and removes it on close", async () => {
const user = userEvent.setup();
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();

View file

@ -1,4 +1,4 @@
import { useCallback, useMemo } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useDebouncedValue } from "@tanstack/react-pacer/debouncer";
import { useQuery, keepPreviousData } from "@tanstack/react-query";
import { ColumnFiltersState } from "@tanstack/react-table";
@ -107,6 +107,17 @@ export default function AuditLogsPanel({
const rows = query.data?.audit_logs ?? EMPTY_ROWS;
const selectedLog = useMemo(() => rows.find((log) => log.id === selectedLogId) ?? null, [rows, selectedLogId]);
const [drawerLog, setDrawerLog] = useState<AuditLogEntry | null>(null);
if (selectedLog !== null && selectedLog !== drawerLog) {
setDrawerLog(selectedLog);
}
const hasSettledPage = query.isSuccess && !query.isPlaceholderData;
const isSelectionMissing = selectedLogId !== null && selectedLog === null;
const isSelectionStale = isSelectionMissing && (!isActive || hasSettledPage);
useEffect(() => {
if (isSelectionStale) void setSelectedLogId(null, { history: "replace" });
}, [isSelectionStale, setSelectedLogId]);
const handleViewLog = useCallback((log: AuditLogEntry) => void setSelectedLogId(log.id), [setSelectedLogId]);
const closeDrawer = useCallback(() => void setSelectedLogId(null), [setSelectedLogId]);
@ -148,7 +159,7 @@ export default function AuditLogsPanel({
<AuditLogsTable
data={rows}
rowCount={query.data?.total ?? 0}
isLoading={query.isLoading}
isLoading={query.isPending}
isError={query.isError}
isRefreshing={query.isFetching}
pagination={pagination}
@ -161,7 +172,7 @@ export default function AuditLogsPanel({
onViewLog={handleViewLog}
/>
<AuditLogDrawer open={selectedLog !== null} onClose={closeDrawer} log={selectedLog} />
<AuditLogDrawer open={selectedLog !== null} onClose={closeDrawer} log={drawerLog} />
</>
);
}

View file

@ -1,5 +1,6 @@
import { QueryClientProvider } from "@tanstack/react-query";
import { render, screen, waitFor } from "@testing-library/react";
import type { PropsWithChildren } from "react";
import userEvent from "@testing-library/user-event";
import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing";
import { beforeEach, describe, expect, it, type Mock, vi } from "vitest";
@ -64,23 +65,40 @@ const renderAs = (sessionRole: string, organizations: unknown[] = [], urlOptions
return renderWithProviders(<SpendLogsTable {...defaultProps} userRole={sessionRole} />, urlOptions);
};
const renderKeepingMountUrlWrites = (sessionRole: string, searchParams: string, onUrlUpdate: OnUrlUpdateFunction) => {
interface OrganizationsResult {
data: unknown[] | undefined;
isLoading?: boolean;
}
const keepingMountUrlWrites = (searchParams: string, onUrlUpdate: OnUrlUpdateFunction) =>
function Providers({ children }: PropsWithChildren) {
return (
<NuqsTestingAdapter
searchParams={searchParams}
onUrlUpdate={onUrlUpdate}
hasMemory
resetUrlUpdateQueueOnMount={false}
>
<QueryClientProvider client={testQueryClient}>{children}</QueryClientProvider>
</NuqsTestingAdapter>
);
};
const renderKeepingMountUrlWrites = (
sessionRole: string,
searchParams: string,
onUrlUpdate: OnUrlUpdateFunction,
organizations: OrganizationsResult = { data: [] },
) => {
useAuthorizedMock.mockReturnValue({ userId: "user-1", userRole: sessionRole });
useOrganizationsMock.mockReturnValue({ data: [] });
return render(
<NuqsTestingAdapter
searchParams={searchParams}
onUrlUpdate={onUrlUpdate}
hasMemory
resetUrlUpdateQueueOnMount={false}
>
<QueryClientProvider client={testQueryClient}>
<SpendLogsTable {...defaultProps} userRole={sessionRole} />
</QueryClientProvider>
</NuqsTestingAdapter>,
);
useOrganizationsMock.mockReturnValue(organizations);
return render(<SpendLogsTable {...defaultProps} userRole={sessionRole} />, {
wrapper: keepingMountUrlWrites(searchParams, onUrlUpdate),
});
};
const flushUrlWrites = () => new Promise((resolve) => setTimeout(resolve, 150));
const lastUrl = (onUrlUpdate: Mock<OnUrlUpdateFunction>) => onUrlUpdate.mock.calls.at(-1)?.[0].searchParams;
const tabNames = () => screen.getAllByRole("tab").map((tab) => tab.textContent);
@ -279,6 +297,41 @@ describe("SpendLogsTable", () => {
expect(screen.getByRole("tab", { name: "Deleted Teams" })).toHaveAttribute("aria-selected", "true");
});
it("keeps ?tab=deleted-teams while an org admin's memberships load, then lands on it", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
const { rerender } = renderKeepingMountUrlWrites("Internal User", "?tab=deleted-teams", onUrlUpdate, {
data: undefined,
isLoading: true,
});
await flushUrlWrites();
expect(onUrlUpdate).not.toHaveBeenCalled();
useOrganizationsMock.mockReturnValue({ data: ORG_ADMIN_MEMBERSHIPS, isLoading: false });
rerender(<SpendLogsTable {...defaultProps} userRole="Internal User" />);
expect(screen.getByRole("tab", { name: "Deleted Teams" })).toHaveAttribute("aria-selected", "true");
expect(screen.getByTestId("deleted-teams-page")).toBeInTheDocument();
await flushUrlWrites();
expect(onUrlUpdate).not.toHaveBeenCalled();
});
it("clears ?tab=deleted-teams once the memberships load without an org_admin role", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
const { rerender } = renderKeepingMountUrlWrites("Internal User", "?tab=deleted-teams", onUrlUpdate, {
data: undefined,
isLoading: true,
});
await flushUrlWrites();
useOrganizationsMock.mockReturnValue({ data: [], isLoading: false });
rerender(<SpendLogsTable {...defaultProps} userRole="Internal User" />);
await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
expect(lastUrl(onUrlUpdate)?.has("tab")).toBe(false);
expect(screen.getByRole("tab", { name: "Request Logs" })).toHaveAttribute("aria-selected", "true");
});
it("keeps ?tab=audit-logs while credentials resolve, then lands on it once the admin role is known", async () => {
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
useAuthorizedMock.mockReturnValue({ userId: null, userRole: null });

View file

@ -1,3 +1,4 @@
import { useOrganizations } from "@/app/(dashboard)/hooks/organizations/useOrganizations";
import useCan from "@/app/(dashboard)/hooks/useCan";
import { useUrlTab } from "@/hooks/useUrlTab";
import DeletedKeysPage from "../DeletedKeysPage/DeletedKeysPage";
@ -37,6 +38,7 @@ const tabContentClassName = (tabId: LogsTabId): string =>
export default function SpendLogsTable({ accessToken, token, userRole, userID, premiumUser }: SpendLogsTableProps) {
const canViewAuditLogs = useCan("viewAuditLogs");
const canViewDeletedTeams = useCan("viewDeletedTeams");
const { isLoading: isOrgMembershipLoading } = useOrganizations();
const tabs: LogsTab[] = [
REQUEST_LOGS_TAB,
@ -44,7 +46,8 @@ export default function SpendLogsTable({ accessToken, token, userRole, userID, p
DELETED_KEYS_TAB,
...(canViewDeletedTeams ? [DELETED_TEAMS_TAB] : []),
];
const visibleSlugs: readonly LogsTabSlug[] = userRole ? tabs.map((tab) => tab.slug) : LOGS_TAB_SLUGS;
const isRoleResolved = Boolean(userRole) && !isOrgMembershipLoading;
const visibleSlugs: readonly LogsTabSlug[] = isRoleResolved ? tabs.map((tab) => tab.slug) : LOGS_TAB_SLUGS;
const [activeSlug, setActiveSlug] = useUrlTab(visibleSlugs, REQUEST_LOGS_TAB.slug);
if (!accessToken || !token || !userRole || !userID) {