mirror of
https://github.com/BerriAI/litellm.git
synced 2026-10-05 02:41:56 +00:00
feat(ui): keep organizations list and detail tab state in the URL
The organizations list now reads its search (org_search), org ID filter (filter_org_id), sort (sort_by, sort_order) and pagination (page, page_size) from the URL through useUrlTableState. The detail view tabs are controlled by ?org_tab=, and the Edit row action opens ?org=<id>&org_tab=settings in one history entry instead of passing an editOrg flag
This commit is contained in:
parent
8bb4317c75
commit
417cc5c4fb
8 changed files with 380 additions and 70 deletions
|
|
@ -1,10 +1,23 @@
|
|||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { act, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { NuqsTestingAdapter, type UrlUpdateEvent } from "nuqs/adapters/testing";
|
||||
import React from "react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type OrganizationsTableComponent from "./OrganizationsTable";
|
||||
import type OrganizationInfoViewComponent from "@/components/organization/organization_view";
|
||||
import type { OrganizationListFilters } from "@/app/(dashboard)/hooks/organizations/useOrganizations";
|
||||
|
||||
const useOrganizationsSpy = vi.hoisted(() => vi.fn<(filters?: OrganizationListFilters) => void>());
|
||||
vi.mock("@/app/(dashboard)/hooks/organizations/useOrganizations", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/app/(dashboard)/hooks/organizations/useOrganizations")>();
|
||||
return {
|
||||
...actual,
|
||||
useOrganizations: (filters?: OrganizationListFilters) => {
|
||||
useOrganizationsSpy(filters);
|
||||
return actual.useOrganizations(filters);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/vector_store_management/VectorStoreSelector", () => ({
|
||||
__esModule: true,
|
||||
|
|
@ -79,10 +92,13 @@ const renderPanel = ({ premiumUser = true, searchParams = "" }: RenderPanelOptio
|
|||
const expectQueryString = (queryString: string) =>
|
||||
waitFor(() => expect(onUrlUpdate).toHaveBeenLastCalledWith(expect.objectContaining({ queryString })));
|
||||
|
||||
const lastSearchParams = () => onUrlUpdate.mock.calls.at(-1)?.[0].searchParams;
|
||||
|
||||
beforeEach(() => {
|
||||
capturedTableProps = null;
|
||||
mockOrgInfoView.mockClear();
|
||||
onUrlUpdate.mockClear();
|
||||
useOrganizationsSpy.mockClear();
|
||||
});
|
||||
|
||||
describe("OrganizationsPanel", () => {
|
||||
|
|
@ -123,9 +139,7 @@ describe("OrganizationsPanel - org detail deep link (?org=)", () => {
|
|||
it("opens the org detail directly from a ?org= deep link", () => {
|
||||
renderPanel({ searchParams: "?org=org-from-url" });
|
||||
|
||||
expect(mockOrgInfoView).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ organizationId: "org-from-url", editOrg: false }),
|
||||
);
|
||||
expect(mockOrgInfoView).toHaveBeenLastCalledWith(expect.objectContaining({ organizationId: "org-from-url" }));
|
||||
expect(screen.queryByTestId("organizations-table")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
|
@ -139,23 +153,24 @@ describe("OrganizationsPanel - org detail deep link (?org=)", () => {
|
|||
expect(screen.getByTestId("organizations-table")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("the edit action opens the detail in edit mode with ?org= set", async () => {
|
||||
it("the edit action pushes ?org= with ?org_tab=settings in one history entry", async () => {
|
||||
renderPanel();
|
||||
|
||||
act(() => capturedTableProps?.onEditClick("org-edit"));
|
||||
|
||||
await expectQueryString("?org=org-edit");
|
||||
expect(mockOrgInfoView).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ organizationId: "org-edit", editOrg: true }),
|
||||
await expectQueryString("?org=org-edit&org_tab=settings");
|
||||
expect(onUrlUpdate).toHaveBeenCalledTimes(1);
|
||||
expect(onUrlUpdate).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ options: expect.objectContaining({ history: "push" }) }),
|
||||
);
|
||||
expect(mockOrgInfoView).toHaveBeenLastCalledWith(expect.objectContaining({ organizationId: "org-edit" }));
|
||||
});
|
||||
|
||||
it("a plain row click after leaving an edit view via browser history does not reopen in edit mode", async () => {
|
||||
it("a plain row click after leaving an edit view via browser history opens the detail without the settings tab", async () => {
|
||||
const { navigate } = renderPanel();
|
||||
|
||||
act(() => capturedTableProps?.onEditClick("org-edit"));
|
||||
await expectQueryString("?org=org-edit");
|
||||
expect(mockOrgInfoView).toHaveBeenLastCalledWith(expect.objectContaining({ editOrg: true }));
|
||||
await expectQueryString("?org=org-edit&org_tab=settings");
|
||||
|
||||
navigate("");
|
||||
expect(screen.getByTestId("organizations-table")).toBeInTheDocument();
|
||||
|
|
@ -163,8 +178,76 @@ describe("OrganizationsPanel - org detail deep link (?org=)", () => {
|
|||
act(() => capturedTableProps?.onOrganizationClick("org-plain"));
|
||||
|
||||
await expectQueryString("?org=org-plain");
|
||||
expect(mockOrgInfoView).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ organizationId: "org-plain", editOrg: false }),
|
||||
expect(mockOrgInfoView).toHaveBeenLastCalledWith(expect.objectContaining({ organizationId: "org-plain" }));
|
||||
});
|
||||
|
||||
it("a row click drops a leftover ?org_tab= so the detail opens on its default tab", async () => {
|
||||
renderPanel({ searchParams: "?org_tab=settings" });
|
||||
|
||||
act(() => capturedTableProps?.onOrganizationClick("org-plain"));
|
||||
|
||||
await expectQueryString("?org=org-plain");
|
||||
});
|
||||
|
||||
it("closing the org detail drops ?org_tab= together with ?org=", async () => {
|
||||
renderPanel({ searchParams: "?org=org-from-url&org_tab=members" });
|
||||
|
||||
act(() => mockOrgInfoView.mock.calls.at(-1)?.[0].onClose());
|
||||
|
||||
await expectQueryString("");
|
||||
expect(onUrlUpdate).toHaveBeenCalledTimes(1);
|
||||
expect(onUrlUpdate).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ options: expect.objectContaining({ history: "push" }) }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("OrganizationsPanel - list filters in the URL", () => {
|
||||
it("restores the name search and org ID filter from the URL and fetches with both", () => {
|
||||
renderPanel({ searchParams: "?org_search=Acme&filter_org_id=org-7" });
|
||||
|
||||
expect(screen.getByPlaceholderText("Search by Organization Name")).toHaveValue("Acme");
|
||||
expect(screen.getByPlaceholderText("Search by Organization ID")).toHaveValue("org-7");
|
||||
expect(useOrganizationsSpy).toHaveBeenLastCalledWith({ org_id: "org-7", org_alias: "Acme" });
|
||||
expect(capturedTableProps?.searchActive).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the org ID filter panel collapsed when the URL has no org ID filter", () => {
|
||||
renderPanel({ searchParams: "?org_search=Acme" });
|
||||
|
||||
expect(screen.queryByPlaceholderText("Search by Organization ID")).not.toBeInTheDocument();
|
||||
expect(useOrganizationsSpy).toHaveBeenLastCalledWith({ org_id: "", org_alias: "Acme" });
|
||||
});
|
||||
|
||||
it("writes the name search to ?org_search= and returns the list to the first page", async () => {
|
||||
renderPanel({ searchParams: "?page=3" });
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("Search by Organization Name"), { target: { value: "Acme" } });
|
||||
|
||||
await waitFor(() => expect(lastSearchParams()?.get("org_search")).toBe("Acme"));
|
||||
expect(lastSearchParams()?.has("page")).toBe(false);
|
||||
expect(useOrganizationsSpy).toHaveBeenLastCalledWith({ org_id: "", org_alias: "Acme" });
|
||||
});
|
||||
|
||||
it("writes the org ID filter to ?filter_org_id= and returns the list to the first page", async () => {
|
||||
renderPanel({ searchParams: "?page=3" });
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Filters" }));
|
||||
fireEvent.change(screen.getByPlaceholderText("Search by Organization ID"), { target: { value: "org-9" } });
|
||||
|
||||
await waitFor(() => expect(lastSearchParams()?.get("filter_org_id")).toBe("org-9"));
|
||||
expect(lastSearchParams()?.has("page")).toBe(false);
|
||||
expect(useOrganizationsSpy).toHaveBeenLastCalledWith({ org_id: "org-9", org_alias: "" });
|
||||
});
|
||||
|
||||
it("clears the search, the org ID filter and the page in one update on reset", async () => {
|
||||
renderPanel({ searchParams: "?org_search=Acme&filter_org_id=org-7&page=2" });
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset Filters" }));
|
||||
|
||||
await expectQueryString("");
|
||||
expect(onUrlUpdate).toHaveBeenCalledTimes(1);
|
||||
expect(useOrganizationsSpy).toHaveBeenLastCalledWith({ org_id: "", org_alias: "" });
|
||||
expect(capturedTableProps?.searchActive).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,16 +2,18 @@ import { organizationKeys, useOrganizations } from "@/app/(dashboard)/hooks/orga
|
|||
import { useUserModels } from "@/app/(dashboard)/hooks/models/useModels";
|
||||
import OrganizationFilters, { FilterState } from "@/app/(dashboard)/organizations/OrganizationFilters";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { parseAsString, useQueryState } from "nuqs";
|
||||
import { parseAsString, parseAsStringLiteral, useQueryStates } from "nuqs";
|
||||
import React, { useState } from "react";
|
||||
import DeleteResourceModal from "@/components/common_components/DeleteResourceModal";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { organizationDeleteCall } from "@/components/networking";
|
||||
import { OrgCreateDialog } from "@/components/organization/org-create/OrgCreateDialog";
|
||||
import OrganizationInfoView from "@/components/organization/organization_view";
|
||||
import { ORGANIZATION_TAB_URL_KEY, ORGANIZATION_TABS } from "@/components/organization/organizationTabs";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import OrganizationsTable from "./OrganizationsTable";
|
||||
import { organizationIdFilter, useOrganizationsTableState } from "./useOrganizationsTableState";
|
||||
|
||||
interface OrganizationsPanelProps {
|
||||
userRole: string;
|
||||
|
|
@ -19,15 +21,25 @@ interface OrganizationsPanelProps {
|
|||
premiumUser: boolean;
|
||||
}
|
||||
|
||||
const ORGANIZATION_DETAIL_STATE = {
|
||||
org: parseAsString,
|
||||
tab: parseAsStringLiteral(ORGANIZATION_TABS),
|
||||
};
|
||||
const ORGANIZATION_DETAIL_URL_KEYS = { tab: ORGANIZATION_TAB_URL_KEY };
|
||||
|
||||
const OrganizationsPanel: React.FC<OrganizationsPanelProps> = ({ userRole, accessToken, premiumUser }) => {
|
||||
const [selectedOrgId, setSelectedOrgId] = useQueryState("org", parseAsString.withOptions({ history: "push" }));
|
||||
const [editOrg, setEditOrg] = useState(false);
|
||||
const [{ org: selectedOrgId }, setOrganizationDetail] = useQueryStates(ORGANIZATION_DETAIL_STATE, {
|
||||
history: "push",
|
||||
urlKeys: ORGANIZATION_DETAIL_URL_KEYS,
|
||||
});
|
||||
const tableState = useOrganizationsTableState();
|
||||
const { setSearch, onColumnFiltersChange } = tableState;
|
||||
const filters: FilterState = { org_id: organizationIdFilter(tableState), org_alias: tableState.search };
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const [orgToDelete, setOrgToDelete] = useState<string | null>(null);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isOrgModalVisible, setIsOrgModalVisible] = useState(false);
|
||||
const [showFilters, setShowFilters] = useState(false);
|
||||
const [filters, setFilters] = useState<FilterState>({ org_id: "", org_alias: "" });
|
||||
const [showFilters, setShowFilters] = useState(() => filters.org_id !== "");
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { data: organizations = [], isLoading } = useOrganizations({
|
||||
|
|
@ -41,11 +53,16 @@ const OrganizationsPanel: React.FC<OrganizationsPanelProps> = ({ userRole, acces
|
|||
const refetchOrganizations = () => queryClient.invalidateQueries({ queryKey: organizationKeys.lists() });
|
||||
|
||||
const handleFilterChange = (key: keyof FilterState, value: string) => {
|
||||
setFilters((previousFilters) => ({ ...previousFilters, [key]: value }));
|
||||
if (key === "org_alias") {
|
||||
setSearch(value);
|
||||
return;
|
||||
}
|
||||
onColumnFiltersChange(value ? [{ id: "org_id", value }] : []);
|
||||
};
|
||||
|
||||
const handleFilterReset = () => {
|
||||
setFilters({ org_id: "", org_alias: "" });
|
||||
setSearch("");
|
||||
onColumnFiltersChange([]);
|
||||
};
|
||||
|
||||
const handleDelete = (orgId: string | null) => {
|
||||
|
|
@ -108,15 +125,11 @@ const OrganizationsPanel: React.FC<OrganizationsPanelProps> = ({ userRole, acces
|
|||
{selectedOrgId ? (
|
||||
<OrganizationInfoView
|
||||
organizationId={selectedOrgId}
|
||||
onClose={() => {
|
||||
void setSelectedOrgId(null);
|
||||
setEditOrg(false);
|
||||
}}
|
||||
onClose={() => void setOrganizationDetail(null)}
|
||||
accessToken={accessToken}
|
||||
is_org_admin={true}
|
||||
is_proxy_admin={userRole === "Admin"}
|
||||
userModels={userModels}
|
||||
editOrg={editOrg}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
|
|
@ -133,14 +146,8 @@ const OrganizationsPanel: React.FC<OrganizationsPanelProps> = ({ userRole, acces
|
|||
isLoading={isLoading}
|
||||
userRole={userRole}
|
||||
searchActive={searchActive}
|
||||
onOrganizationClick={(organizationId) => {
|
||||
setEditOrg(false);
|
||||
void setSelectedOrgId(organizationId);
|
||||
}}
|
||||
onEditClick={(organizationId) => {
|
||||
void setSelectedOrgId(organizationId);
|
||||
setEditOrg(true);
|
||||
}}
|
||||
onOrganizationClick={(organizationId) => void setOrganizationDetail({ org: organizationId, tab: null })}
|
||||
onEditClick={(organizationId) => void setOrganizationDetail({ org: organizationId, tab: "settings" })}
|
||||
onDeleteClick={handleDelete}
|
||||
/>
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { render, screen, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import type { OnUrlUpdateFunction } from "nuqs/adapters/testing";
|
||||
import React from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi, type Mock } from "vitest";
|
||||
|
||||
import { renderWithProviders, screen, waitFor, within } from "../../../../../tests/test-utils";
|
||||
|
||||
import { Organization } from "@/components/networking";
|
||||
|
||||
|
|
@ -26,6 +28,34 @@ const makeOrganization = (overrides: Partial<Organization> = {}): Organization =
|
|||
...overrides,
|
||||
});
|
||||
|
||||
const thirtyOrganizations = Array.from({ length: 30 }, (_, index) =>
|
||||
makeOrganization({ organization_id: `org-${index}`, organization_alias: `Org ${index}` }),
|
||||
);
|
||||
|
||||
const sortableOrganization = (alias: string, createdAt: string, spend: number): Organization => {
|
||||
const overrides: Partial<Organization> = {
|
||||
organization_id: `org-${alias.toLowerCase()}`,
|
||||
organization_alias: alias,
|
||||
created_at: createdAt,
|
||||
spend,
|
||||
};
|
||||
return makeOrganization(overrides);
|
||||
};
|
||||
|
||||
const sortableOrganizations = [
|
||||
sortableOrganization("Mid", "2024-03-01T00:00:00Z", 5),
|
||||
sortableOrganization("Zed", "2023-01-01T00:00:00Z", 1),
|
||||
sortableOrganization("Ace", "2025-01-01T00:00:00Z", 3),
|
||||
];
|
||||
|
||||
const bodyRowAliases = () =>
|
||||
screen
|
||||
.getAllByRole("row")
|
||||
.slice(1)
|
||||
.map((row) => ["Ace", "Mid", "Zed"].find((alias) => within(row).queryByText(alias) !== null));
|
||||
|
||||
const lastSearchParams = (onUrlUpdate: Mock<OnUrlUpdateFunction>) => onUrlUpdate.mock.calls.at(-1)?.[0].searchParams;
|
||||
|
||||
const baseProps = {
|
||||
isLoading: false,
|
||||
userRole: "Admin",
|
||||
|
|
@ -37,7 +67,7 @@ const baseProps = {
|
|||
|
||||
describe("OrganizationsTable", () => {
|
||||
it("renders every column header", () => {
|
||||
render(<OrganizationsTable {...baseProps} organizations={[]} />);
|
||||
renderWithProviders(<OrganizationsTable {...baseProps} organizations={[]} />);
|
||||
for (const header of [
|
||||
"Organization ID",
|
||||
"Organization Name",
|
||||
|
|
@ -55,7 +85,7 @@ describe("OrganizationsTable", () => {
|
|||
it("opens the detail view when the organization ID cell is clicked", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onOrganizationClick = vi.fn();
|
||||
render(
|
||||
renderWithProviders(
|
||||
<OrganizationsTable
|
||||
{...baseProps}
|
||||
onOrganizationClick={onOrganizationClick}
|
||||
|
|
@ -72,7 +102,7 @@ describe("OrganizationsTable", () => {
|
|||
const user = userEvent.setup();
|
||||
const onEditClick = vi.fn();
|
||||
const onDeleteClick = vi.fn();
|
||||
render(
|
||||
renderWithProviders(
|
||||
<OrganizationsTable
|
||||
{...baseProps}
|
||||
userRole="Admin"
|
||||
|
|
@ -92,7 +122,7 @@ describe("OrganizationsTable", () => {
|
|||
});
|
||||
|
||||
it("hides the row actions menu from non-admins", () => {
|
||||
render(
|
||||
renderWithProviders(
|
||||
<OrganizationsTable
|
||||
{...baseProps}
|
||||
userRole="Internal User"
|
||||
|
|
@ -104,7 +134,7 @@ describe("OrganizationsTable", () => {
|
|||
});
|
||||
|
||||
it("sorts by created_at descending by default", () => {
|
||||
render(
|
||||
renderWithProviders(
|
||||
<OrganizationsTable
|
||||
{...baseProps}
|
||||
organizations={[
|
||||
|
|
@ -129,7 +159,7 @@ describe("OrganizationsTable", () => {
|
|||
});
|
||||
|
||||
it("renders budget, limits, members, and models for a fully-populated organization", () => {
|
||||
render(
|
||||
renderWithProviders(
|
||||
<OrganizationsTable
|
||||
{...baseProps}
|
||||
organizations={[
|
||||
|
|
@ -151,7 +181,7 @@ describe("OrganizationsTable", () => {
|
|||
});
|
||||
|
||||
it("shows Unlimited budget and All Proxy Models when unset", () => {
|
||||
render(
|
||||
renderWithProviders(
|
||||
<OrganizationsTable
|
||||
{...baseProps}
|
||||
organizations={[makeOrganization({ organization_id: "org-empty", litellm_budget_table: {}, models: [] })]}
|
||||
|
|
@ -166,7 +196,7 @@ describe("OrganizationsTable", () => {
|
|||
});
|
||||
|
||||
it("renders a tpm/rpm limit of 0 as 0, never as Unlimited", () => {
|
||||
render(
|
||||
renderWithProviders(
|
||||
<OrganizationsTable
|
||||
{...baseProps}
|
||||
organizations={[makeOrganization({ litellm_budget_table: { max_budget: null, tpm_limit: 0, rpm_limit: 0 } })]}
|
||||
|
|
@ -180,7 +210,7 @@ describe("OrganizationsTable", () => {
|
|||
});
|
||||
|
||||
it("renders loading skeletons instead of rows while loading", () => {
|
||||
render(
|
||||
renderWithProviders(
|
||||
<OrganizationsTable
|
||||
{...baseProps}
|
||||
isLoading
|
||||
|
|
@ -194,10 +224,8 @@ describe("OrganizationsTable", () => {
|
|||
|
||||
it("pages long lists client-side with the shared size selector and footer", async () => {
|
||||
const user = userEvent.setup();
|
||||
const organizations = Array.from({ length: 30 }, (_, index) =>
|
||||
makeOrganization({ organization_id: `org-${index}`, organization_alias: `Org ${index}` }),
|
||||
);
|
||||
render(<OrganizationsTable {...baseProps} organizations={organizations} />);
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderWithProviders(<OrganizationsTable {...baseProps} organizations={thirtyOrganizations} />, { onUrlUpdate });
|
||||
|
||||
expect(screen.getAllByRole("row")).toHaveLength(26);
|
||||
expect(screen.getByTestId("pagination-range")).toHaveTextContent("Showing 1-25 of 30");
|
||||
|
|
@ -207,13 +235,87 @@ describe("OrganizationsTable", () => {
|
|||
|
||||
expect(screen.getAllByRole("row")).toHaveLength(31);
|
||||
expect(screen.getByTestId("pagination-range")).toHaveTextContent("Showing 1-30 of 30");
|
||||
await waitFor(() => expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("page_size")).toBe("50"));
|
||||
});
|
||||
|
||||
it("uses a search-aware empty state", () => {
|
||||
const { rerender } = render(<OrganizationsTable {...baseProps} searchActive={false} organizations={[]} />);
|
||||
const { rerender } = renderWithProviders(
|
||||
<OrganizationsTable {...baseProps} searchActive={false} organizations={[]} />,
|
||||
);
|
||||
expect(screen.getByText("No organizations yet")).toBeInTheDocument();
|
||||
|
||||
rerender(<OrganizationsTable {...baseProps} searchActive={true} organizations={[]} />);
|
||||
expect(screen.getByText("No matching organizations")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("OrganizationsTable URL state", () => {
|
||||
it("restores the sort column and direction from ?sort_by=&sort_order=", () => {
|
||||
renderWithProviders(<OrganizationsTable {...baseProps} organizations={sortableOrganizations} />, {
|
||||
searchParams: "?sort_by=spend&sort_order=desc",
|
||||
});
|
||||
|
||||
expect(bodyRowAliases()).toEqual(["Mid", "Ace", "Zed"]);
|
||||
});
|
||||
|
||||
it("falls back to sorting by creation date for a ?sort_by= column that cannot be sorted", () => {
|
||||
renderWithProviders(<OrganizationsTable {...baseProps} organizations={sortableOrganizations} />, {
|
||||
searchParams: "?sort_by=members&sort_order=asc",
|
||||
});
|
||||
|
||||
expect(bodyRowAliases()).toEqual(["Zed", "Mid", "Ace"]);
|
||||
});
|
||||
|
||||
it("writes the clicked sort column to the URL and returns to the first page", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderWithProviders(<OrganizationsTable {...baseProps} organizations={thirtyOrganizations} />, {
|
||||
searchParams: "?page=2",
|
||||
onUrlUpdate,
|
||||
});
|
||||
expect(screen.getByTestId("pagination-range")).toHaveTextContent("Showing 26-30 of 30");
|
||||
|
||||
await user.click(screen.getByTestId("sort-header-organization_alias"));
|
||||
|
||||
await waitFor(() => expect(lastSearchParams(onUrlUpdate)?.get("sort_by")).toBe("organization_alias"));
|
||||
expect(onUrlUpdate).toHaveBeenCalledTimes(1);
|
||||
expect(lastSearchParams(onUrlUpdate)?.get("sort_order")).toBe("asc");
|
||||
expect(lastSearchParams(onUrlUpdate)?.has("page")).toBe(false);
|
||||
expect(screen.getByTestId("pagination-range")).toHaveTextContent("Showing 1-25 of 30");
|
||||
expect(within(screen.getAllByRole("row")[1]).getByText("Org 0")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens the page named by ?page= and writes page changes back to the URL", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderWithProviders(<OrganizationsTable {...baseProps} organizations={thirtyOrganizations} />, {
|
||||
searchParams: "?page=2",
|
||||
onUrlUpdate,
|
||||
});
|
||||
|
||||
expect(screen.getByTestId("pagination-range")).toHaveTextContent("Showing 26-30 of 30");
|
||||
expect(screen.getByText("org-29")).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByTestId("pagination-prev"));
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId("pagination-range")).toHaveTextContent("Showing 1-25 of 30"));
|
||||
expect(lastSearchParams(onUrlUpdate)?.has("page")).toBe(false);
|
||||
|
||||
await user.click(screen.getByTestId("pagination-next"));
|
||||
|
||||
await waitFor(() => expect(lastSearchParams(onUrlUpdate)?.get("page")).toBe("2"));
|
||||
});
|
||||
|
||||
it("keeps a deep-linked ?page= while the organization list is still loading", async () => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
const { rerender } = renderWithProviders(<OrganizationsTable {...baseProps} isLoading organizations={[]} />, {
|
||||
searchParams: "?page=2",
|
||||
onUrlUpdate,
|
||||
});
|
||||
|
||||
rerender(<OrganizationsTable {...baseProps} organizations={thirtyOrganizations} />);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId("pagination-range")).toHaveTextContent("Showing 26-30 of 30"));
|
||||
expect(onUrlUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
"use client";
|
||||
|
||||
import { SortingState } from "@tanstack/react-table";
|
||||
import { Building2, SearchX } from "lucide-react";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import React, { useMemo } from "react";
|
||||
|
||||
import { DataTable } from "@/components/shared/DataTable";
|
||||
import { Organization } from "@/components/networking";
|
||||
|
||||
import { getOrganizationsTableColumns } from "./OrganizationsTableColumns";
|
||||
import { useOrganizationsTableState } from "./useOrganizationsTableState";
|
||||
|
||||
interface OrganizationsTableProps {
|
||||
organizations: Organization[];
|
||||
|
|
@ -19,8 +19,6 @@ interface OrganizationsTableProps {
|
|||
onDeleteClick: (organizationId: string) => void;
|
||||
}
|
||||
|
||||
const DEFAULT_SORTING: SortingState = [{ id: "created_at", desc: true }];
|
||||
|
||||
function EmptyState({ searchActive }: { searchActive: boolean }) {
|
||||
const Icon = searchActive ? SearchX : Building2;
|
||||
return (
|
||||
|
|
@ -49,7 +47,7 @@ const OrganizationsTable: React.FC<OrganizationsTableProps> = ({
|
|||
onEditClick,
|
||||
onDeleteClick,
|
||||
}) => {
|
||||
const [sorting, setSorting] = useState<SortingState>(DEFAULT_SORTING);
|
||||
const { sorting, onSortingChange, pagination, onPaginationChange } = useOrganizationsTableState();
|
||||
|
||||
const columns = useMemo(() => {
|
||||
const deps = { userRole, onOrganizationClick, onEditClick, onDeleteClick };
|
||||
|
|
@ -60,11 +58,13 @@ const OrganizationsTable: React.FC<OrganizationsTableProps> = ({
|
|||
<DataTable
|
||||
data={organizations}
|
||||
paginationMode="client"
|
||||
pagination={pagination}
|
||||
onPaginationChange={onPaginationChange}
|
||||
columns={columns}
|
||||
getRowId={(organization, index) => organization.organization_id || String(index)}
|
||||
sortingMode="client"
|
||||
sorting={sorting}
|
||||
onSortingChange={setSorting}
|
||||
onSortingChange={onSortingChange}
|
||||
isLoading={isLoading}
|
||||
loadingMessage="Loading organizations…"
|
||||
noDataMessage={<EmptyState searchActive={searchActive} />}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,19 @@
|
|||
import { useUrlTableState, type UrlTableState, type UrlTableStateOptions } from "@/components/shared/DataTable";
|
||||
|
||||
const FILTER_COLUMNS = ["org_id"] as const;
|
||||
type FilterColumn = (typeof FILTER_COLUMNS)[number];
|
||||
|
||||
const TABLE_STATE_OPTIONS: UrlTableStateOptions<FilterColumn> = {
|
||||
sortFields: ["organization_id", "organization_alias", "created_at", "spend"],
|
||||
defaultSort: { id: "created_at", desc: true },
|
||||
defaultPageSize: 25,
|
||||
filterColumns: FILTER_COLUMNS,
|
||||
urlKeys: { search: "org_search" },
|
||||
};
|
||||
|
||||
export const useOrganizationsTableState = (): UrlTableState => useUrlTableState(TABLE_STATE_OPTIONS);
|
||||
|
||||
export const organizationIdFilter = ({ columnFilters }: Pick<UrlTableState, "columnFilters">): string => {
|
||||
const value = columnFilters.find((filter) => filter.id === "org_id")?.value;
|
||||
return typeof value === "string" ? value : "";
|
||||
};
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export const ORGANIZATION_TABS = ["overview", "members", "settings"] as const;
|
||||
export type OrganizationTab = (typeof ORGANIZATION_TABS)[number];
|
||||
export const ORGANIZATION_TAB_URL_KEY = "org_tab";
|
||||
|
|
@ -1,8 +1,10 @@
|
|||
import React from "react";
|
||||
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { vi, test, expect, beforeEach } from "vitest";
|
||||
import { renderWithProviders } from "../../../tests/test-utils";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing";
|
||||
import { vi, test, expect, beforeEach, describe, type Mock } from "vitest";
|
||||
import { renderWithProviders, testQueryClient } from "../../../tests/test-utils";
|
||||
import OrganizationInfoView from "./organization_view";
|
||||
import { useOrganization } from "@/app/(dashboard)/hooks/organizations/useOrganizations";
|
||||
|
||||
|
|
@ -115,7 +117,6 @@ test("renders organization view after loading data", async () => {
|
|||
is_org_admin={false}
|
||||
is_proxy_admin={false}
|
||||
userModels={[]}
|
||||
editOrg={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
|
@ -135,7 +136,6 @@ test("should display empty state when organization has no members", async () =>
|
|||
is_org_admin={false}
|
||||
is_proxy_admin={false}
|
||||
userModels={[]}
|
||||
editOrg={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
|
@ -165,7 +165,6 @@ test("should display team aliases when teams are available", async () => {
|
|||
is_org_admin={false}
|
||||
is_proxy_admin={false}
|
||||
userModels={[]}
|
||||
editOrg={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
|
@ -199,7 +198,6 @@ test("should display team ID as fallback when alias is not found", async () => {
|
|||
is_org_admin={false}
|
||||
is_proxy_admin={false}
|
||||
userModels={[]}
|
||||
editOrg={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
|
@ -223,7 +221,6 @@ test("links each team badge to that team's detail page", async () => {
|
|||
is_org_admin={false}
|
||||
is_proxy_admin={false}
|
||||
userModels={[]}
|
||||
editOrg={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
|
@ -250,7 +247,6 @@ test("model badges stay non-clickable", async () => {
|
|||
is_org_admin={false}
|
||||
is_proxy_admin={false}
|
||||
userModels={[]}
|
||||
editOrg={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
|
@ -272,7 +268,6 @@ test("should keep unsaved settings edits when switching tabs and back", async ()
|
|||
is_org_admin={false}
|
||||
is_proxy_admin={true}
|
||||
userModels={[]}
|
||||
editOrg={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
|
@ -308,7 +303,6 @@ test("renders a tpm/rpm limit of 0 as 0 in the overview and settings tabs, never
|
|||
is_org_admin={false}
|
||||
is_proxy_admin={true}
|
||||
userModels={[]}
|
||||
editOrg={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
|
|
@ -323,3 +317,99 @@ test("renders a tpm/rpm limit of 0 as 0 in the overview and settings tabs, never
|
|||
expect(screen.queryByText("TPM: Unlimited")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("RPM: Unlimited")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
const renderOrgView = (props: { is_proxy_admin?: boolean } = {}) => (
|
||||
<OrganizationInfoView
|
||||
organizationId="org_123"
|
||||
onClose={() => {}}
|
||||
accessToken="test-token"
|
||||
is_org_admin={false}
|
||||
is_proxy_admin={props.is_proxy_admin ?? false}
|
||||
userModels={[]}
|
||||
/>
|
||||
);
|
||||
|
||||
const lastSearchParams = (onUrlUpdate: Mock<OnUrlUpdateFunction>) => onUrlUpdate.mock.calls.at(-1)?.[0].searchParams;
|
||||
|
||||
describe("organization detail tab in the URL (?org_tab=)", () => {
|
||||
beforeEach(() => {
|
||||
mockUseOrganization.mockReturnValue({ data: mockOrg, isLoading: false } as unknown as ReturnType<
|
||||
typeof useOrganization
|
||||
>);
|
||||
});
|
||||
|
||||
test("opens on the tab named by ?org_tab=", () => {
|
||||
renderWithProviders(renderOrgView(), { searchParams: "?org=org_123&org_tab=members" });
|
||||
|
||||
expect(screen.getByRole("tab", { name: "Members" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(screen.getByText("No members found")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("the settings deep link used by the list's Edit action opens the Settings tab", () => {
|
||||
renderWithProviders(renderOrgView({ is_proxy_admin: true }), { searchParams: "?org=org_123&org_tab=settings" });
|
||||
|
||||
expect(screen.getByRole("tab", { name: "Settings" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(screen.getByRole("button", { name: /Edit Settings/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("opens on Overview when the URL names no tab", () => {
|
||||
renderWithProviders(renderOrgView(), { searchParams: "?org=org_123" });
|
||||
|
||||
expect(screen.getByRole("tab", { name: "Overview" })).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
|
||||
test("writes the selected tab to ?org_tab= and drops it again for Overview", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderWithProviders(renderOrgView(), { searchParams: "?org=org_123", onUrlUpdate });
|
||||
|
||||
await user.click(screen.getByRole("tab", { name: "Settings" }));
|
||||
|
||||
await waitFor(() => expect(lastSearchParams(onUrlUpdate)?.get("org_tab")).toBe("settings"));
|
||||
expect(lastSearchParams(onUrlUpdate)?.get("org")).toBe("org_123");
|
||||
expect(screen.getByRole("tab", { name: "Settings" })).toHaveAttribute("aria-selected", "true");
|
||||
|
||||
await user.click(screen.getByRole("tab", { name: "Overview" }));
|
||||
|
||||
await waitFor(() => expect(lastSearchParams(onUrlUpdate)?.has("org_tab")).toBe(false));
|
||||
expect(lastSearchParams(onUrlUpdate)?.get("org")).toBe("org_123");
|
||||
});
|
||||
|
||||
test("falls back to Overview for an unknown ?org_tab= and removes it from the URL", async () => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
render(renderOrgView(), {
|
||||
wrapper: ({ children }) => (
|
||||
<NuqsTestingAdapter
|
||||
searchParams="?org=org_123&org_tab=billing"
|
||||
onUrlUpdate={onUrlUpdate}
|
||||
hasMemory
|
||||
resetUrlUpdateQueueOnMount={false}
|
||||
>
|
||||
<QueryClientProvider client={testQueryClient}>{children}</QueryClientProvider>
|
||||
</NuqsTestingAdapter>
|
||||
),
|
||||
});
|
||||
|
||||
expect(screen.getByRole("tab", { name: "Overview" })).toHaveAttribute("aria-selected", "true");
|
||||
await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
|
||||
expect(lastSearchParams(onUrlUpdate)?.has("org_tab")).toBe(false);
|
||||
expect(lastSearchParams(onUrlUpdate)?.get("org")).toBe("org_123");
|
||||
});
|
||||
|
||||
test("follows back and forward navigation between tabs while the detail view stays open", () => {
|
||||
const atUrl = (searchParams: string) => (
|
||||
<NuqsTestingAdapter searchParams={searchParams} hasMemory>
|
||||
<QueryClientProvider client={testQueryClient}>{renderOrgView()}</QueryClientProvider>
|
||||
</NuqsTestingAdapter>
|
||||
);
|
||||
const { rerender } = render(atUrl("?org=org_123&org_tab=members"));
|
||||
expect(screen.getByRole("tab", { name: "Members" })).toHaveAttribute("aria-selected", "true");
|
||||
|
||||
rerender(atUrl("?org=org_123"));
|
||||
expect(screen.getByRole("tab", { name: "Overview" })).toHaveAttribute("aria-selected", "true");
|
||||
|
||||
rerender(atUrl("?org=org_123&org_tab=members"));
|
||||
expect(screen.getByRole("tab", { name: "Members" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(screen.getByText("No members found")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { useTeams } from "@/app/(dashboard)/hooks/teams/useTeams";
|
||||
import { organizationKeys, useOrganization } from "@/app/(dashboard)/hooks/organizations/useOrganizations";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useUrlTab } from "@/hooks/useUrlTab";
|
||||
import { useVisitedTabs } from "@/hooks/useVisitedTabs";
|
||||
import { MoneyCell } from "@/components/shared/table_cells";
|
||||
import CopyButton from "@/components/shared/CopyButton";
|
||||
|
|
@ -25,6 +26,7 @@ import {
|
|||
import ObjectPermissionsView from "../object_permissions_view";
|
||||
import MemberModal from "../team/EditMembership";
|
||||
import { OrgSettingsForm } from "./org-settings/OrgSettingsForm";
|
||||
import { ORGANIZATION_TAB_URL_KEY, ORGANIZATION_TABS, type OrganizationTab } from "./organizationTabs";
|
||||
|
||||
interface OrganizationInfoProps {
|
||||
organizationId: string;
|
||||
|
|
@ -33,7 +35,6 @@ interface OrganizationInfoProps {
|
|||
is_org_admin: boolean;
|
||||
is_proxy_admin: boolean;
|
||||
userModels: string[];
|
||||
editOrg: boolean;
|
||||
}
|
||||
|
||||
const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
|
||||
|
|
@ -43,7 +44,6 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
|
|||
is_org_admin,
|
||||
is_proxy_admin,
|
||||
userModels,
|
||||
editOrg,
|
||||
}) => {
|
||||
const queryClient = useQueryClient();
|
||||
const { data: orgData, isLoading: loading } = useOrganization(organizationId);
|
||||
|
|
@ -53,10 +53,16 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
|
|||
const [selectedEditMember, setSelectedEditMember] = useState<Member | null>(null);
|
||||
const canEditOrg = is_org_admin || is_proxy_admin;
|
||||
const { data: teams } = useTeams();
|
||||
const { onTabChange, hasVisited } = useVisitedTabs(editOrg ? "settings" : "overview");
|
||||
const [tab, setTab] = useUrlTab(ORGANIZATION_TABS, "overview", ORGANIZATION_TAB_URL_KEY);
|
||||
const { onTabChange, hasVisited } = useVisitedTabs(tab);
|
||||
|
||||
const teamAliasMap = useMemo(() => createTeamAliasMap(teams), [teams]);
|
||||
|
||||
const handleTabChange = (value: OrganizationTab) => {
|
||||
setTab(value);
|
||||
onTabChange(value);
|
||||
};
|
||||
|
||||
const handleMemberAdd = async (values: any) => {
|
||||
try {
|
||||
if (accessToken == null) {
|
||||
|
|
@ -158,7 +164,7 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue={editOrg ? "settings" : "overview"} onValueChange={onTabChange} className="mb-4">
|
||||
<Tabs value={tab} onValueChange={handleTabChange} className="mb-4">
|
||||
<TabsList variant="line" className="h-auto w-full justify-start rounded-none border-b p-0">
|
||||
<TabsTrigger value="overview" className="flex-none rounded-none px-4 py-2">
|
||||
Overview
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue