mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-17 09:34:48 +00:00
Merge pull request #5 from sarvika/litellm_project_filter_usage_page
fix: review changes fixed
This commit is contained in:
commit
33c84ee822
11 changed files with 317 additions and 27 deletions
|
|
@ -1100,6 +1100,7 @@ def _project_daily_activity_error(*, status_code: int, message: str) -> HTTPExce
|
|||
|
||||
|
||||
_MAX_PROJECT_DAILY_ACTIVITY_RANGE_DAYS: Final = 400
|
||||
_MAX_PROJECT_DAILY_ACTIVITY_PROJECT_COUNT: Final = 50
|
||||
|
||||
|
||||
def _project_daily_activity_date_range_error(start_date: str | None, end_date: str | None) -> str | None:
|
||||
|
|
@ -1123,11 +1124,16 @@ def _project_daily_activity_date_range_error(start_date: str | None, end_date: s
|
|||
|
||||
|
||||
def _project_daily_spend_sql(*, project_count: int) -> str:
|
||||
project_placeholders: Final = ", ".join(f"${i}" for i in range(3, 3 + project_count))
|
||||
"""
|
||||
Joins each requested project_id against the team_id it currently belongs to, so a
|
||||
project_id reused by a different team after the original project was deleted cannot
|
||||
pull that team's historical spend into the new project's report.
|
||||
"""
|
||||
pairs: Final = ", ".join(f"(${3 + 2 * i}::text, ${4 + 2 * i}::text)" for i in range(project_count))
|
||||
return f"""
|
||||
SELECT
|
||||
(DATE_TRUNC('day', sl."startTime" AT TIME ZONE 'UTC'))::date::text AS spend_date,
|
||||
sl.metadata->>'user_api_key_project_id' AS project_id,
|
||||
scoped.project_id AS project_id,
|
||||
SUM(sl.spend)::float AS spend,
|
||||
SUM(sl.prompt_tokens)::bigint AS prompt_tokens,
|
||||
SUM(sl.completion_tokens)::bigint AS completion_tokens,
|
||||
|
|
@ -1136,11 +1142,13 @@ def _project_daily_spend_sql(*, project_count: int) -> str:
|
|||
COUNT(*) FILTER (WHERE sl.status IS DISTINCT FROM 'failure')::bigint AS successful_requests,
|
||||
COUNT(*) FILTER (WHERE sl.status = 'failure')::bigint AS failed_requests
|
||||
FROM "LiteLLM_SpendLogs" sl
|
||||
JOIN (VALUES {pairs}) AS scoped(project_id, team_id)
|
||||
ON sl.metadata->>'user_api_key_project_id' = scoped.project_id
|
||||
AND sl.team_id IS NOT DISTINCT FROM scoped.team_id
|
||||
WHERE sl."startTime" >= $1::timestamp
|
||||
AND sl."startTime" < $2::timestamp + INTERVAL '1 day'
|
||||
AND sl.metadata->>'user_api_key_project_id' IN ({project_placeholders})
|
||||
GROUP BY spend_date, project_id
|
||||
ORDER BY spend_date, project_id
|
||||
GROUP BY spend_date, scoped.project_id
|
||||
ORDER BY spend_date, scoped.project_id
|
||||
"""
|
||||
|
||||
|
||||
|
|
@ -1158,6 +1166,7 @@ class _ProjectDailySpendDbRow(TypedDict):
|
|||
|
||||
class _ProjectDailyActivityScope(NamedTuple):
|
||||
project_ids: tuple[str, ...]
|
||||
project_team_ids: tuple[str | None, ...]
|
||||
project_alias_by_id: Mapping[str, str | None]
|
||||
|
||||
|
||||
|
|
@ -1173,9 +1182,14 @@ async def _resolve_project_daily_activity_scope(
|
|||
Proxy admins may query any project. Everyone else must be an admin of the
|
||||
project's team, the same permission /project/update enforces.
|
||||
"""
|
||||
requested: Final = tuple(pid.strip() for pid in project_ids.split(",") if pid.strip())
|
||||
requested: Final = tuple(dict.fromkeys(pid.strip() for pid in project_ids.split(",") if pid.strip()))
|
||||
if not requested:
|
||||
return _ProjectDailyActivityScope(project_ids=(), project_alias_by_id={})
|
||||
return _ProjectDailyActivityScope(project_ids=(), project_team_ids=(), project_alias_by_id={})
|
||||
if len(requested) > _MAX_PROJECT_DAILY_ACTIVITY_PROJECT_COUNT:
|
||||
raise _project_daily_activity_error(
|
||||
status_code=400,
|
||||
message=f"At most {_MAX_PROJECT_DAILY_ACTIVITY_PROJECT_COUNT} project_ids may be requested at once",
|
||||
)
|
||||
|
||||
projects: Final = await _project_table(prisma_client).find_many(where={"project_id": {"in": list(requested)}})
|
||||
found_by_id: Final = {p.project_id: p for p in projects}
|
||||
|
|
@ -1200,6 +1214,7 @@ async def _resolve_project_daily_activity_scope(
|
|||
|
||||
return _ProjectDailyActivityScope(
|
||||
project_ids=requested,
|
||||
project_team_ids=tuple(found_by_id[pid].team_id for pid in requested),
|
||||
project_alias_by_id={pid: found_by_id[pid].project_alias for pid in requested},
|
||||
)
|
||||
|
||||
|
|
@ -1265,11 +1280,14 @@ async def get_project_daily_activity(
|
|||
if not scope.project_ids:
|
||||
return ProjectDailySpendResponse(start_date=start_date, end_date=end_date, results=())
|
||||
|
||||
project_team_params: Final = tuple(
|
||||
value for pair in zip(scope.project_ids, scope.project_team_ids) for value in pair
|
||||
)
|
||||
rows: Final[Sequence[_ProjectDailySpendDbRow]] = await prisma_client.db.query_raw(
|
||||
_project_daily_spend_sql(project_count=len(scope.project_ids)),
|
||||
start_date,
|
||||
end_date,
|
||||
*scope.project_ids,
|
||||
*project_team_params,
|
||||
)
|
||||
results: Final = tuple(
|
||||
ProjectDailySpendRow(
|
||||
|
|
|
|||
|
|
@ -1453,10 +1453,11 @@ async def test_get_project_daily_activity_admin_groups_by_day_and_project(monkey
|
|||
)
|
||||
|
||||
sql, *params = mock_prisma.db.query_raw.call_args.args
|
||||
assert params == ["2026-09-01", "2026-09-02", "project-alpha", "project-beta"]
|
||||
assert params == ["2026-09-01", "2026-09-02", "project-alpha", "team-1", "project-beta", "team-1"]
|
||||
assert 'FROM "LiteLLM_SpendLogs" sl' in sql
|
||||
assert "sl.metadata->>'user_api_key_project_id' IN ($3, $4)" in sql
|
||||
assert "GROUP BY spend_date, project_id" in sql
|
||||
assert "JOIN (VALUES ($3::text, $4::text), ($5::text, $6::text)) AS scoped(project_id, team_id)" in sql
|
||||
assert "sl.team_id IS NOT DISTINCT FROM scoped.team_id" in sql
|
||||
assert "GROUP BY spend_date, scoped.project_id" in sql
|
||||
|
||||
assert response.start_date == "2026-09-01"
|
||||
assert response.end_date == "2026-09-02"
|
||||
|
|
@ -1467,6 +1468,86 @@ async def test_get_project_daily_activity_admin_groups_by_day_and_project(monkey
|
|||
assert (response.results[0].successful_requests, response.results[0].failed_requests) == (2, 1)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_project_daily_activity_dedupes_repeated_project_ids(monkeypatch):
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
project = MagicMock(project_id="project-alpha", project_alias="Alpha", team_id="team-1")
|
||||
|
||||
mock_prisma = MagicMock()
|
||||
mock_prisma.db.litellm_projecttable.find_many = AsyncMock(return_value=[project])
|
||||
mock_prisma.db.query_raw = AsyncMock(return_value=[])
|
||||
monkeypatch.setattr(litellm.proxy.proxy_server, "premium_user", True)
|
||||
monkeypatch.setattr(litellm.proxy.proxy_server, "prisma_client", mock_prisma)
|
||||
|
||||
admin = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin")
|
||||
await get_project_daily_activity(
|
||||
user_api_key_dict=admin,
|
||||
project_ids=",".join(["project-alpha"] * 5000),
|
||||
start_date="2026-09-01",
|
||||
end_date="2026-09-02",
|
||||
)
|
||||
|
||||
mock_prisma.db.litellm_projecttable.find_many.assert_awaited_once_with(where={"project_id": {"in": ["project-alpha"]}})
|
||||
sql, *params = mock_prisma.db.query_raw.call_args.args
|
||||
assert params == ["2026-09-01", "2026-09-02", "project-alpha", "team-1"]
|
||||
assert "(VALUES ($3::text, $4::text))" in sql
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_project_daily_activity_rejects_too_many_project_ids(monkeypatch):
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
mock_prisma = MagicMock()
|
||||
mock_prisma.db.litellm_projecttable.find_many = AsyncMock(return_value=[])
|
||||
mock_prisma.db.query_raw = AsyncMock(return_value=[])
|
||||
monkeypatch.setattr(litellm.proxy.proxy_server, "premium_user", True)
|
||||
monkeypatch.setattr(litellm.proxy.proxy_server, "prisma_client", mock_prisma)
|
||||
|
||||
too_many_ids = ",".join(f"project-{i}" for i in range(51))
|
||||
admin = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin")
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_project_daily_activity(
|
||||
user_api_key_dict=admin,
|
||||
project_ids=too_many_ids,
|
||||
start_date="2026-09-01",
|
||||
end_date="2026-09-02",
|
||||
)
|
||||
assert exc_info.value.status_code == 400
|
||||
assert "At most 50 project_ids" in str(exc_info.value.detail)
|
||||
mock_prisma.db.litellm_projecttable.find_many.assert_not_awaited()
|
||||
mock_prisma.db.query_raw.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_project_daily_activity_scopes_spend_by_team_to_prevent_reused_id_leak(monkeypatch):
|
||||
"""A project_id can be reused by a different team after the original project is deleted.
|
||||
The query must join on (project_id, team_id) together so a reused id cannot pull in the
|
||||
prior team's historical spend."""
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
project_alpha = MagicMock(project_id="project-alpha", project_alias="Alpha", team_id="team-1")
|
||||
project_beta = MagicMock(project_id="project-beta", project_alias="Beta", team_id="team-2")
|
||||
|
||||
mock_prisma = MagicMock()
|
||||
mock_prisma.db.litellm_projecttable.find_many = AsyncMock(return_value=[project_alpha, project_beta])
|
||||
mock_prisma.db.query_raw = AsyncMock(return_value=[])
|
||||
monkeypatch.setattr(litellm.proxy.proxy_server, "premium_user", True)
|
||||
monkeypatch.setattr(litellm.proxy.proxy_server, "prisma_client", mock_prisma)
|
||||
|
||||
admin = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin")
|
||||
await get_project_daily_activity(
|
||||
user_api_key_dict=admin,
|
||||
project_ids="project-alpha,project-beta",
|
||||
start_date="2026-09-01",
|
||||
end_date="2026-09-02",
|
||||
)
|
||||
|
||||
sql, *params = mock_prisma.db.query_raw.call_args.args
|
||||
assert params == ["2026-09-01", "2026-09-02", "project-alpha", "team-1", "project-beta", "team-2"]
|
||||
assert "sl.team_id IS NOT DISTINCT FROM scoped.team_id" in sql
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_project_daily_activity_team_admin_can_view_own_project(monkeypatch):
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
|
|
|||
|
|
@ -129,4 +129,24 @@ describe("useProjects", () => {
|
|||
expect(result.current.isFetched).toBe(false);
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should not fetch when the caller passes enabled=false, even for an eligible role", () => {
|
||||
(global.fetch as any).mockResolvedValue({ ok: true, json: async () => mockProjects });
|
||||
const { result } = renderHook(() => useProjects(false), { wrapper: makeWrapper(queryClient) });
|
||||
expect(result.current.isFetched).toBe(false);
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should fetch once the caller flips enabled back to true", async () => {
|
||||
(global.fetch as any).mockResolvedValue({ ok: true, json: async () => mockProjects });
|
||||
const { result, rerender } = renderHook(({ enabled }: { enabled: boolean }) => useProjects(enabled), {
|
||||
wrapper: makeWrapper(queryClient),
|
||||
initialProps: { enabled: false },
|
||||
});
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ enabled: true });
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
expect(global.fetch).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -70,12 +70,12 @@ const fetchProjects = async (accessToken: string): Promise<ProjectResponse[]> =>
|
|||
|
||||
// ── Hook ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const useProjects = () => {
|
||||
export const useProjects = (enabled: boolean = true) => {
|
||||
const { accessToken, userRole } = useAuthorized();
|
||||
|
||||
return useQuery<ProjectResponse[]>({
|
||||
queryKey: projectKeys.list({}),
|
||||
queryFn: async () => fetchProjects(accessToken!),
|
||||
enabled: Boolean(accessToken) && projectReaderRoles.includes(userRole!),
|
||||
enabled: enabled && Boolean(accessToken) && projectReaderRoles.includes(userRole!),
|
||||
});
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { useAgents } from "@/app/(dashboard)/hooks/agents/useAgents";
|
||||
import { useCustomers } from "@/app/(dashboard)/hooks/customers/useCustomers";
|
||||
import { useProjects } from "@/app/(dashboard)/hooks/projects/useProjects";
|
||||
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
|
||||
import useIsOrgAdmin from "@/app/(dashboard)/hooks/useIsOrgAdmin";
|
||||
import { useCurrentUser } from "@/app/(dashboard)/hooks/users/useCurrentUser";
|
||||
|
|
@ -7,7 +8,7 @@ import { useInfiniteUsers } from "@/app/(dashboard)/hooks/users/useUsers";
|
|||
import { act, fireEvent, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderWithProviders } from "@/../tests/test-utils";
|
||||
import { renderWithProviders, testQueryClient } from "@/../tests/test-utils";
|
||||
import type { Organization } from "@/components/networking";
|
||||
import * as networking from "@/components/networking";
|
||||
import UsagePage from "./UsagePageView";
|
||||
|
|
@ -28,6 +29,7 @@ vi.mock("@/components/networking", () => ({
|
|||
userDailyActivityCall: vi.fn(),
|
||||
userDailyActivityAggregatedCall: vi.fn(),
|
||||
gatewayDailyActivityCall: vi.fn(),
|
||||
getUiSettings: vi.fn(),
|
||||
tagListCall: vi.fn(),
|
||||
}));
|
||||
|
||||
|
|
@ -60,14 +62,25 @@ vi.mock("./EntityUsage/SpendByProvider", () => ({
|
|||
default: () => <div>Spend By Provider</div>,
|
||||
}));
|
||||
|
||||
vi.mock("./ProjectUsage/ProjectUsage", () => ({
|
||||
default: ({ projectList }: { projectList: unknown }) => (
|
||||
<div data-testid="project-usage" data-project-list={JSON.stringify(projectList ?? null)}>
|
||||
Project Usage Panel
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("./EndpointUsage/EndpointUsage", () => ({
|
||||
default: () => <div>Endpoint Usage</div>,
|
||||
}));
|
||||
|
||||
vi.mock("./UsageViewSelect/UsageViewSelect", async () => {
|
||||
const React = await import("react");
|
||||
const UsageViewSelect = ({ value, onChange, canViewTagUsage = false }: any) => {
|
||||
const UsageViewSelect = ({ value, onChange, canViewTagUsage = false, enableProjectsUI = false }: any) => {
|
||||
const tagOption = canViewTagUsage ? React.createElement("option", { value: "tag" }, "Tag Usage") : null;
|
||||
const projectOption = enableProjectsUI
|
||||
? React.createElement("option", { value: "project" }, "Project Usage")
|
||||
: null;
|
||||
return React.createElement(
|
||||
"select",
|
||||
{
|
||||
|
|
@ -79,6 +92,7 @@ vi.mock("./UsageViewSelect/UsageViewSelect", async () => {
|
|||
React.createElement("option", { value: "global" }, "Global Usage"),
|
||||
React.createElement("option", { value: "team" }, "Team Usage"),
|
||||
React.createElement("option", { value: "organization" }, "Organization Usage"),
|
||||
projectOption,
|
||||
React.createElement("option", { value: "customer" }, "Customer Usage"),
|
||||
tagOption,
|
||||
React.createElement("option", { value: "agent" }, "Agent Usage"),
|
||||
|
|
@ -137,6 +151,10 @@ vi.mock("@/app/(dashboard)/hooks/agents/useAgents", () => ({
|
|||
useAgents: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/app/(dashboard)/hooks/projects/useProjects", () => ({
|
||||
useProjects: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({
|
||||
__esModule: true,
|
||||
default: vi.fn(),
|
||||
|
|
@ -163,6 +181,8 @@ describe("UsagePage", () => {
|
|||
const mockGatewayDailyActivityCall = vi.mocked(networking.gatewayDailyActivityCall);
|
||||
const mockUseCustomers = vi.mocked(useCustomers);
|
||||
const mockUseAgents = vi.mocked(useAgents);
|
||||
const mockUseProjects = vi.mocked(useProjects);
|
||||
const mockGetUiSettings = vi.mocked(networking.getUiSettings);
|
||||
const mockUseAuthorized = vi.mocked(useAuthorized);
|
||||
const mockUseCurrentUser = vi.mocked(useCurrentUser);
|
||||
const mockUseInfiniteUsers = vi.mocked(useInfiniteUsers);
|
||||
|
|
@ -353,6 +373,11 @@ describe("UsagePage", () => {
|
|||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// useUISettings is a real react-query hook (not mocked below), and the shared
|
||||
// testQueryClient never expires a cached query on its own (staleTime/gcTime:
|
||||
// Infinity, refetchOnMount: false). Without clearing it, one test's
|
||||
// getUiSettings mock leaks into the next test's render of the same query key.
|
||||
testQueryClient.clear();
|
||||
mockUseAuthorized.mockReturnValue({
|
||||
isLoading: false,
|
||||
isAuthorized: true,
|
||||
|
|
@ -411,6 +436,15 @@ describe("UsagePage", () => {
|
|||
isLoading: false,
|
||||
error: null,
|
||||
} as any);
|
||||
mockUseProjects.mockReturnValue({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
} as any);
|
||||
// Left unset (rather than resolved) by default: enable_projects_ui reads
|
||||
// as off until a test explicitly turns it on, matching a proxy that has
|
||||
// not enabled the flag.
|
||||
mockGetUiSettings.mockReturnValue(new Promise(() => {}));
|
||||
});
|
||||
|
||||
it("should render and fetch usage data on mount", async () => {
|
||||
|
|
@ -812,6 +846,80 @@ describe("UsagePage", () => {
|
|||
expect(screen.queryByText("Entity Usage")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe("project usage", () => {
|
||||
// A team admin's session role is "Internal User" — the same role a plain
|
||||
// member carries — so team-admin-ness only shows up in the team's own
|
||||
// members_with_roles.
|
||||
const teamAdminProps = {
|
||||
...defaultProps,
|
||||
teams: [
|
||||
{
|
||||
...defaultProps.teams[0],
|
||||
members_with_roles: [{ role: "admin", user_id: "user-123" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it("should not fetch the project list while Project Usage UI is disabled", async () => {
|
||||
renderWithProviders(<UsagePage {...defaultProps} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
expect(mockUseProjects).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it("should fetch the project list once Project Usage UI is turned on", async () => {
|
||||
mockGetUiSettings.mockResolvedValue({ field_schema: {}, values: { enable_projects_ui: true } });
|
||||
|
||||
renderWithProviders(<UsagePage {...defaultProps} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUseProjects).toHaveBeenLastCalledWith(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("should let a team admin open Project Usage once it is enabled", async () => {
|
||||
mockGetUiSettings.mockResolvedValue({ field_schema: {}, values: { enable_projects_ui: true } });
|
||||
mockUseAuthorized.mockReturnValue(nonAdminSession);
|
||||
mockUseProjects.mockReturnValue({
|
||||
data: [{ project_id: "project-1", project_alias: "Project One" }],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
} as any);
|
||||
|
||||
renderWithProviders(<UsagePage {...teamAdminProps} />);
|
||||
|
||||
await screen.findByRole("option", { name: "Project Usage" });
|
||||
act(() => {
|
||||
fireEvent.change(screen.getByTestId("usage-view-select"), { target: { value: "project" } });
|
||||
});
|
||||
|
||||
const projectUsage = await screen.findByTestId("project-usage");
|
||||
expect(projectUsage).toHaveAttribute(
|
||||
"data-project-list",
|
||||
JSON.stringify([{ label: "Project One", value: "project-1" }]),
|
||||
);
|
||||
});
|
||||
|
||||
// The dropdown's own capability gating (which roles see the Project Usage option
|
||||
// at all, including a team admin) is covered by UsageViewSelect.test.tsx; this
|
||||
// checks the composition point specific to this component: nothing should fetch
|
||||
// the project list for a session that Project Usage was never going to grant.
|
||||
it("should not fetch the project list for a plain internal user who administers no team", async () => {
|
||||
mockGetUiSettings.mockResolvedValue({ field_schema: {}, values: { enable_projects_ui: true } });
|
||||
mockUseAuthorized.mockReturnValue(nonAdminSession);
|
||||
|
||||
renderWithProviders(<UsagePage {...defaultProps} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUserDailyActivityAggregatedCall).toHaveBeenCalled();
|
||||
});
|
||||
expect(mockUseProjects).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("admin user selector", () => {
|
||||
// Anchored on the field's own label, so it does not depend on which library draws the control.
|
||||
const userSelectCombobox = (): HTMLElement => {
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ import { useCurrentUser } from "@/app/(dashboard)/hooks/users/useCurrentUser";
|
|||
import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings";
|
||||
import { hasCapability } from "@/utils/capabilities";
|
||||
import { formatNumberWithCommas } from "@/utils/dataUtils";
|
||||
import { all_admin_roles, internalUserRoles } from "@/utils/roles";
|
||||
import { all_admin_roles, internalUserRoles, isUserTeamAdminForAnyTeam } from "@/utils/roles";
|
||||
import { ActivityMetrics, processActivityData } from "@/components/activity_metrics";
|
||||
import CloudZeroExportModal from "@/components/cloudzero_export_modal";
|
||||
import UserDropdown from "@/components/common_components/UserDropdown";
|
||||
|
|
@ -106,16 +106,17 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
|
|||
// filter reads as loading rather than as a range with no customers.
|
||||
const { data: customers } = useCustomers();
|
||||
const { data: agentsResponse } = useAgents();
|
||||
const { data: projectsResponse } = useProjects();
|
||||
const { data: currentUser } = useCurrentUser();
|
||||
const isAdmin = all_admin_roles.includes(userRole || "");
|
||||
const canViewTagUsage = isAdmin || internalUserRoles.includes(userRole || "");
|
||||
const isOrgAdmin = useIsOrgAdmin();
|
||||
const isTeamAdmin = isUserTeamAdminForAnyTeam(teams, userID || "");
|
||||
const canViewOrganizationUsage = hasCapability(userRole, "viewOrganizationUsage", isOrgAdmin);
|
||||
const canViewAgentUsage = hasCapability(userRole, "viewAgentUsage");
|
||||
const { data: uiSettingsData } = useUISettings();
|
||||
const enableProjectsUI = Boolean(uiSettingsData?.values?.enable_projects_ui);
|
||||
const canViewProjectUsage = hasCapability(userRole, "viewProjectUsage") && enableProjectsUI;
|
||||
const canViewProjectUsage = hasCapability(userRole, "viewProjectUsage", isOrgAdmin, isTeamAdmin) && enableProjectsUI;
|
||||
const { data: projectsResponse } = useProjects(canViewProjectUsage);
|
||||
|
||||
// For admins: null means global view (all users), a string means filter by that user
|
||||
// For non-admins: always set to their own user ID
|
||||
|
|
@ -490,6 +491,7 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
|
|||
userRole={userRole}
|
||||
canViewTagUsage={canViewTagUsage}
|
||||
isOrgAdmin={isOrgAdmin}
|
||||
isTeamAdmin={isTeamAdmin}
|
||||
enableProjectsUI={enableProjectsUI}
|
||||
/>
|
||||
<AdvancedDatePicker value={dateValue} onValueChange={handleDateChange} />
|
||||
|
|
|
|||
|
|
@ -103,6 +103,40 @@ describe("UsageViewSelect", () => {
|
|||
expect(offers(container, optionName)).toBe(expected);
|
||||
});
|
||||
|
||||
// A team admin's session role is also "Internal User" — team-admin-ness lives in the
|
||||
// team's members_with_roles — so this cannot be told apart from a plain internal user
|
||||
// by role alone either. Project Usage must open for them without unlocking the other
|
||||
// admin-only options the org-admin case above already guards.
|
||||
it.each([
|
||||
["Project Usage", true],
|
||||
["Organization Usage", false],
|
||||
["Agent Usage (A2A)", false],
|
||||
] as const)("should offer %s to a team admin: %s", async (optionName, expected) => {
|
||||
const user = userEvent.setup();
|
||||
const { container } = render(
|
||||
<UsageViewSelect value="global" onChange={mockOnChange} userRole="Internal User" isTeamAdmin={true} />,
|
||||
);
|
||||
|
||||
await openMenu(user);
|
||||
expect(offers(container, optionName)).toBe(expected);
|
||||
});
|
||||
|
||||
it("should hide Project Usage from a team admin when enableProjectsUI is false", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { container } = render(
|
||||
<UsageViewSelect
|
||||
value="global"
|
||||
onChange={mockOnChange}
|
||||
userRole="Internal User"
|
||||
isTeamAdmin={true}
|
||||
enableProjectsUI={false}
|
||||
/>,
|
||||
);
|
||||
|
||||
await openMenu(user);
|
||||
expect(offers(container, "Project Usage")).toBe(false);
|
||||
});
|
||||
|
||||
it("should hide Project Usage from an admin when enableProjectsUI is false", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { container } = render(
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ export interface UsageViewSelectProps {
|
|||
userRole: string | null;
|
||||
canViewTagUsage?: boolean;
|
||||
isOrgAdmin?: boolean;
|
||||
isTeamAdmin?: boolean;
|
||||
enableProjectsUI?: boolean;
|
||||
title?: string;
|
||||
description?: string;
|
||||
|
|
@ -119,6 +120,7 @@ export const UsageViewSelect: React.FC<UsageViewSelectProps> = ({
|
|||
userRole,
|
||||
canViewTagUsage = false,
|
||||
isOrgAdmin = false,
|
||||
isTeamAdmin = false,
|
||||
enableProjectsUI = true,
|
||||
title = "Usage View",
|
||||
description = "Select the usage data you want to view",
|
||||
|
|
@ -131,7 +133,7 @@ export const UsageViewSelect: React.FC<UsageViewSelectProps> = ({
|
|||
return false;
|
||||
}
|
||||
if (option.capability) {
|
||||
return hasCapability(userRole, option.capability, isOrgAdmin);
|
||||
return hasCapability(userRole, option.capability, isOrgAdmin, isTeamAdmin);
|
||||
}
|
||||
if (option.value === "tag" && canViewTagUsage) {
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -102,11 +102,6 @@ export const getFilterValue = (columnFilters: ColumnFiltersState, columnId: stri
|
|||
return trimmed === "" ? undefined : trimmed;
|
||||
};
|
||||
|
||||
/**
|
||||
* The Team and Project filter chips carry the id as their filter value (needed for the
|
||||
* backend query and for re-selecting the right option in the filter drawer), but showing
|
||||
* that id in the chip is meaningless to a reader. Resolve it back to the alias they picked.
|
||||
*/
|
||||
export const resolveLogFilterDisplayValue = (
|
||||
columnId: string,
|
||||
rawValue: string,
|
||||
|
|
|
|||
|
|
@ -92,6 +92,30 @@ describe("hasCapability for organization admins", () => {
|
|||
});
|
||||
});
|
||||
|
||||
const SESSION_ROLE_A_TEAM_ADMIN_ACTUALLY_CARRIES = "Internal User";
|
||||
|
||||
describe("hasCapability for team admins", () => {
|
||||
it.each(NON_ADMIN_ROLES)("grants viewProjectUsage to a team admin whose session role is %s", (role) => {
|
||||
expect(hasCapability(role, "viewProjectUsage", false, true)).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves viewProjectUsage denied when the caller is not a team admin", () => {
|
||||
expect(hasCapability(SESSION_ROLE_A_TEAM_ADMIN_ACTUALLY_CARRIES, "viewProjectUsage", false, false)).toBe(false);
|
||||
expect(hasCapability(SESSION_ROLE_A_TEAM_ADMIN_ACTUALLY_CARRIES, "viewProjectUsage")).toBe(false);
|
||||
});
|
||||
|
||||
it.each(ADMIN_ONLY_CAPABILITIES.filter((capability) => capability !== "viewProjectUsage"))(
|
||||
"leaves %s denied for a team admin whose session role is not otherwise entitled",
|
||||
(capability) => {
|
||||
expect(hasCapability(SESSION_ROLE_A_TEAM_ADMIN_ACTUALLY_CARRIES, capability, false, true)).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not let the team-admin allowance reopen the proxy-admin-only viewGlobalSpend gate", () => {
|
||||
expect(hasCapability(SESSION_ROLE_A_TEAM_ADMIN_ACTUALLY_CARRIES, "viewGlobalSpend", false, true)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasCapability - viewGlobalSpend", () => {
|
||||
it.each(ADMIN_ROLES)("should grant it to %s", (role) => {
|
||||
expect(hasCapability(role, "viewGlobalSpend")).toBe(true);
|
||||
|
|
|
|||
|
|
@ -25,12 +25,18 @@ const ORG_ADMIN_CAPABILITIES: ReadonlySet<Capability> = new Set<Capability>([
|
|||
"viewOrganizationUsage",
|
||||
]);
|
||||
|
||||
const TEAM_ADMIN_CAPABILITIES: ReadonlySet<Capability> = new Set<Capability>(["viewProjectUsage"]);
|
||||
|
||||
export const hasCapability = (
|
||||
userRole: string | null | undefined,
|
||||
capability: Capability,
|
||||
isOrgAdmin: boolean = false,
|
||||
): boolean =>
|
||||
(isOrgAdmin && ORG_ADMIN_CAPABILITIES.has(capability)) ||
|
||||
(userRole != null && CAPABILITY_ROLES[capability].includes(userRole));
|
||||
isTeamAdmin: boolean = false,
|
||||
): boolean => {
|
||||
const grantedViaOrgAdmin = isOrgAdmin && ORG_ADMIN_CAPABILITIES.has(capability);
|
||||
const grantedViaTeamAdmin = isTeamAdmin && TEAM_ADMIN_CAPABILITIES.has(capability);
|
||||
const grantedViaRole = userRole != null && CAPABILITY_ROLES[capability].includes(userRole);
|
||||
return grantedViaOrgAdmin || grantedViaTeamAdmin || grantedViaRole;
|
||||
};
|
||||
|
||||
export const rolesWithCapability = (capability: Capability): string[] => [...CAPABILITY_ROLES[capability]];
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue