Skip to content

Commit feace55

Browse files
committed
feat: add detailed AI spend page with CSV export
1 parent edff0cd commit feace55

21 files changed

Lines changed: 1493 additions & 9 deletions

‎site/src/api/api.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,57 @@ describe("api.ts", () => {
264264
});
265265
});
266266

267+
describe("organization AI spend details", () => {
268+
afterEach(() => {
269+
vi.restoreAllMocks();
270+
});
271+
272+
it("passes detail filters and pagination to the organization spend endpoint", async () => {
273+
const getSpy = vi.spyOn(axiosInstance, "get").mockResolvedValueOnce({
274+
data: { rows: [], count: 0 },
275+
});
276+
277+
await API.getOrganizationAISpendDetails("my-org", {
278+
user_id: "user-1",
279+
group_id: "group-1",
280+
provider_name: "openai",
281+
model: "gpt-4o-mini",
282+
limit: 25,
283+
offset: 50,
284+
});
285+
286+
expect(getSpy).toHaveBeenCalledWith(
287+
expect.stringContaining("/api/v2/organizations/my-org/ai/spend?"),
288+
);
289+
const [url] = getSpy.mock.calls[0];
290+
expect(url).toContain("user_id=user-1");
291+
expect(url).toContain("group_id=group-1");
292+
expect(url).toContain("limit=25");
293+
expect(url).toContain("offset=50");
294+
});
295+
296+
it("downloads the full filtered organization spend export as a blob", async () => {
297+
const blob = new Blob(["csv"]);
298+
const getSpy = vi
299+
.spyOn(axiosInstance, "get")
300+
.mockResolvedValueOnce({ data: blob });
301+
302+
await expect(
303+
API.exportOrganizationAISpend("my-org", {
304+
period_start: "2026-09-01T00:00:00Z",
305+
period_end: "2026-09-15T00:00:00Z",
306+
provider_name: "openai",
307+
}),
308+
).resolves.toBe(blob);
309+
expect(getSpy).toHaveBeenCalledWith(
310+
expect.stringContaining(
311+
"/api/v2/organizations/my-org/ai/spend/export?",
312+
),
313+
{ responseType: "blob" },
314+
);
315+
});
316+
});
317+
267318
describe("update", () => {
268319
describe("given a running workspace", () => {
269320
it("stops with current version before starting with the latest version", async () => {

‎site/src/api/api.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,10 @@ export class ParameterValidationError extends Error {
423423
}
424424
}
425425

426+
type OrganizationAISpendDetailsParams =
427+
TypesGen.OrganizationAISpendDetailsFilter &
428+
Pick<TypesGen.Pagination, "limit" | "offset">;
429+
426430
export type GetProvisionerJobsParams = {
427431
status?: string;
428432
limit?: number;
@@ -2193,6 +2197,31 @@ class ApiMethods {
21932197
* meaningful response.
21942198
* @param organization Can be the organization's ID or name
21952199
*/
2200+
getOrganizationAISpendDetails = async (
2201+
organization: string,
2202+
params: OrganizationAISpendDetailsParams,
2203+
): Promise<TypesGen.OrganizationAISpendDetails> => {
2204+
const url = getURLWithSearchParams(
2205+
`/api/v2/organizations/${organization}/ai/spend`,
2206+
params,
2207+
);
2208+
const response =
2209+
await this.axios.get<TypesGen.OrganizationAISpendDetails>(url);
2210+
return response.data;
2211+
};
2212+
2213+
exportOrganizationAISpend = async (
2214+
organization: string,
2215+
params: TypesGen.OrganizationAISpendDetailsFilter,
2216+
): Promise<Blob> => {
2217+
const url = getURLWithSearchParams(
2218+
`/api/v2/organizations/${organization}/ai/spend/export`,
2219+
params,
2220+
);
2221+
const response = await this.axios.get<Blob>(url, { responseType: "blob" });
2222+
return response.data;
2223+
};
2224+
21962225
getOrganizationGroupsAISpend = async (
21972226
organization: string,
21982227
groupIds: readonly string[],

‎site/src/api/queries/aiBridge.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { API } from "#/api/api";
33
import type {
44
AIBridgeListSessionsResponse,
55
AIBridgeSessionThreadsResponse,
6+
OrganizationAISpendDetails,
7+
OrganizationAISpendDetailsFilter,
68
} from "#/api/typesGenerated";
79
import { useFilterParamsKey } from "#/components/Filter/Filter";
810
import type { UsePaginatedQueryOptions } from "#/hooks/usePaginatedQuery";
@@ -27,6 +29,50 @@ export const paginatedSessions = (
2729
};
2830
};
2931

32+
const organizationAISpendDetailsKey = (
33+
organizationId: string,
34+
filter: OrganizationAISpendDetailsFilter,
35+
pageNumber: number,
36+
) =>
37+
[
38+
"organization",
39+
organizationId,
40+
"aiSpendDetails",
41+
filter,
42+
pageNumber,
43+
] as const;
44+
45+
export const paginatedOrganizationAISpendDetails = (
46+
organizationId: string,
47+
filter: OrganizationAISpendDetailsFilter,
48+
): UsePaginatedQueryOptions<
49+
OrganizationAISpendDetails,
50+
OrganizationAISpendDetailsFilter
51+
> => ({
52+
queryPayload: () => filter,
53+
queryKey: ({ payload, pageNumber }) =>
54+
organizationAISpendDetailsKey(organizationId, payload, pageNumber),
55+
queryFn: ({ payload, limit, offset }) =>
56+
API.getOrganizationAISpendDetails(organizationId, {
57+
...payload,
58+
limit,
59+
offset,
60+
}),
61+
prefetch: false,
62+
placeholderData: (previousData, previousQuery) =>
63+
previousQuery?.queryKey[1] === organizationId ? previousData : undefined,
64+
});
65+
66+
export const exportOrganizationAISpend = () => ({
67+
mutationFn: ({
68+
organizationId,
69+
filter,
70+
}: {
71+
organizationId: string;
72+
filter: OrganizationAISpendDetailsFilter;
73+
}) => API.exportOrganizationAISpend(organizationId, filter),
74+
});
75+
3076
export const infiniteSessionThreads = (sessionId: string) => {
3177
return {
3278
queryKey: ["aiBridgeSessionThreads", sessionId],

‎site/src/components/DateRangePicker/DateRangePicker.stories.tsx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,18 @@ export const CancelClosesWithoutApplying: Story = {
165165
},
166166
};
167167

168+
export const ConstrainedRange: Story = {
169+
args: {
170+
value: defaultValue,
171+
onChange: () => {},
172+
minDate: new Date("2025-03-10T00:00:00Z"),
173+
maxDays: 7,
174+
},
175+
play: async ({ canvasElement }) => {
176+
await userEvent.click(within(canvasElement).getByRole("button"));
177+
},
178+
};
179+
168180
export const CustomPresets: Story = {
169181
args: {
170182
value: defaultValue,
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { screen } from "@testing-library/react";
2+
import userEvent from "@testing-library/user-event";
3+
import { expect, it, vi } from "vitest";
4+
import { render } from "#/testHelpers/renderHelpers";
5+
import { DateRangePicker } from "./DateRangePicker";
6+
7+
it("resets an overlong calendar selection before committing a new range", async () => {
8+
const user = userEvent.setup();
9+
const onChange = vi.fn();
10+
render(
11+
<DateRangePicker
12+
value={{
13+
startDate: new Date("2025-03-01T00:00:00Z"),
14+
endDate: new Date("2025-03-03T00:00:00Z"),
15+
}}
16+
onChange={onChange}
17+
now={new Date("2025-03-20T12:00:00Z")}
18+
maxDays={7}
19+
/>,
20+
);
21+
22+
await user.click(screen.getByRole("button", { name: /Mar 1, 2025/ }));
23+
await user.click(
24+
screen.getByRole("button", { name: "Wednesday, March 5th, 2025" }),
25+
);
26+
await user.click(
27+
screen.getByRole("button", { name: "Saturday, March 15th, 2025" }),
28+
);
29+
await user.click(screen.getByRole("button", { name: "Apply" }));
30+
31+
expect(onChange).not.toHaveBeenCalled();
32+
});

‎site/src/components/DateRangePicker/DateRangePicker.tsx‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@ interface DateRangePickerProps {
8383
now?: Date;
8484
presets?: DateRangePreset[];
8585
size?: ButtonProps["size"];
86+
maxDays?: number;
87+
minDate?: Date;
8688
}
8789

8890
/**
@@ -121,10 +123,21 @@ export const DateRangePicker: FC<DateRangePickerProps> = ({
121123
now,
122124
presets,
123125
size = "sm",
126+
maxDays,
127+
minDate,
124128
}) => {
125129
const [open, setOpen] = useState(false);
126130
const currentTime = now ?? new Date();
127-
const resolvedPresets = presets ?? buildDefaultPresets(now);
131+
const resolvedPresets = (presets ?? buildDefaultPresets(now)).filter(
132+
(preset) => {
133+
const { from, to } = preset.range();
134+
const rangeDays = dayjs(to).diff(from, "day") + 1;
135+
return (
136+
(minDate === undefined || !dayjs(from).isBefore(minDate, "day")) &&
137+
(maxDays === undefined || rangeDays <= maxDays)
138+
);
139+
},
140+
);
128141

129142
// Internal selection state kept separate from the committed value
130143
// so the user can freely adjust the range before applying. This
@@ -149,7 +162,6 @@ export const DateRangePicker: FC<DateRangePickerProps> = ({
149162
};
150163

151164
const handleCalendarSelect = (range: DayPickerDateRange | undefined) => {
152-
if (!range) return;
153165
setSelection(range);
154166
};
155167

@@ -245,7 +257,8 @@ export const DateRangePicker: FC<DateRangePickerProps> = ({
245257
selected={selection}
246258
onSelect={handleCalendarSelect}
247259
numberOfMonths={2}
248-
disabled={{ after: currentTime }}
260+
max={maxDays === undefined ? undefined : maxDays - 1}
261+
disabled={{ before: minDate, after: currentTime }}
249262
today={currentTime}
250263
/>
251264
</div>

‎site/src/hooks/usePaginatedQuery.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,45 @@ describe(usePaginatedQuery.name, () => {
6969
});
7070
});
7171

72+
describe("placeholder data", () => {
73+
it("does not retain data when a custom placeholder rejects a different organization", async () => {
74+
type SpendPage = PaginatedData & { rows: readonly string[] };
75+
type Props = { organizationId: string };
76+
const pending = new Promise<SpendPage>(() => undefined);
77+
const options = (
78+
organizationId: string,
79+
): UsePaginatedQueryOptions<SpendPage> => ({
80+
queryKey: () => ["organization", organizationId, "spend"] as const,
81+
queryFn: () =>
82+
organizationId === "organization-a"
83+
? Promise.resolve({ count: 1, rows: ["organization-a"] })
84+
: pending,
85+
prefetch: false,
86+
placeholderData: (previousData, previousQuery) =>
87+
previousQuery?.queryKey[1] === organizationId
88+
? previousData
89+
: undefined,
90+
});
91+
const { result, rerender } = await renderHookWithAuth(
92+
({ organizationId }: Props) =>
93+
usePaginatedQuery(options(organizationId)),
94+
{
95+
renderOptions: { initialProps: { organizationId: "organization-a" } },
96+
},
97+
);
98+
99+
await waitFor(() =>
100+
expect(result.current.data).toEqual({
101+
count: 1,
102+
rows: ["organization-a"],
103+
}),
104+
);
105+
await rerender({ organizationId: "organization-b" });
106+
107+
expect(result.current.data).toBeUndefined();
108+
});
109+
});
110+
72111
describe("Querying for current page", () => {
73112
const mockQueryKey = vi.fn(() => ["mock"]);
74113
const mockQueryFn = vi.fn(() => Promise.resolve({ count: 50 }));

‎site/src/hooks/usePaginatedQuery.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ export function usePaginatedQuery<
152152
const query = useQuery<TQueryFnData, TError, TData, TQueryKey>({
153153
...extraOptions,
154154
...getQueryOptionsFromPage(currentPage),
155-
placeholderData: keepPreviousData,
155+
placeholderData: extraOptions.placeholderData ?? keepPreviousData,
156156
});
157157

158158
const count = query.data?.count;

‎site/src/modules/management/AISettingsSidebar.tsx‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { FC } from "react";
22
import { useAuthenticated } from "#/hooks/useAuthenticated";
33
import { useDashboard } from "#/modules/dashboard/useDashboard";
44
import AISettingsSidebarView from "#/modules/management/AISettingsSidebarView";
5+
import { getAIBridgePermissions } from "#/pages/AIBridgePage/getAIBridgePermissions";
56
import { useCanShareOrganizationMCPServers } from "#/pages/AISettingsPage/MCPServersPage/organizationSharing";
67
import { useAccessibleModelOrganizations } from "#/pages/AISettingsPage/ModelsPage/organizationModels";
78

@@ -10,7 +11,11 @@ import { useAccessibleModelOrganizations } from "#/pages/AISettingsPage/ModelsPa
1011
*/
1112
export const AISettingsSidebar: FC = () => {
1213
const { permissions } = useAuthenticated();
13-
const { organizations } = useDashboard();
14+
const { organizations, entitlements } = useDashboard();
15+
const { isEntitled, isEnabled, hasPermission } = getAIBridgePermissions(
16+
entitlements,
17+
permissions,
18+
);
1419
const accessibleOrgsQuery = useAccessibleModelOrganizations(organizations);
1520
const organizationMCPSharing = useCanShareOrganizationMCPServers(
1621
organizations,
@@ -20,6 +25,7 @@ export const AISettingsSidebar: FC = () => {
2025
return (
2126
<AISettingsSidebarView
2227
permissions={permissions}
28+
canViewAISpend={isEntitled && isEnabled && hasPermission}
2329
canAccessOrganizationModels={
2430
(accessibleOrgsQuery.organizations.length ?? 0) > 0
2531
}

‎site/src/modules/management/AISettingsSidebarView.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { modelOrganizationSearchParam } from "#/pages/AISettingsPage/ModelsPage/
2020
interface AISettingsSidebarViewProps {
2121
/** Site-wide permissions. */
2222
permissions: Permissions;
23+
canViewAISpend?: boolean;
2324
canAccessOrganizationModels?: boolean;
2425
canShareOrganizationMCPServers?: boolean;
2526
}
@@ -78,6 +79,7 @@ const ModelsSidebarNavItem: FC<{ href: To }> = ({ href }) => {
7879

7980
const AISettingsSidebarView: FC<AISettingsSidebarViewProps> = ({
8081
permissions,
82+
canViewAISpend = false,
8183
canAccessOrganizationModels = false,
8284
canShareOrganizationMCPServers = false,
8385
}) => {
@@ -108,6 +110,11 @@ const AISettingsSidebarView: FC<AISettingsSidebarViewProps> = ({
108110
AI Governance
109111
</SidebarNavItem>
110112
)}
113+
{canViewAISpend && (
114+
<SidebarNavItem href="/ai/settings/spend-details">
115+
Spend details
116+
</SidebarNavItem>
117+
)}
111118
{permissions.viewAIGatewayKeys && (
112119
<SidebarNavItem href="/ai/settings/gateway-keys">
113120
AI Gateway keys

0 commit comments

Comments
 (0)