feat(ui): add "Since last budget reset" range to usage page picker

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
mrinal 2026-09-10 13:44:56 +00:00
parent e5da59336d
commit 0274a77717
6 changed files with 246 additions and 9 deletions

View file

@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { lastBudgetResetAt } from "./budgetWindow";
describe("lastBudgetResetAt", () => {
it.each([
[null, "30d"],
[undefined, "30d"],
["2026-10-01T00:00:00Z", null],
["2026-10-01T00:00:00Z", undefined],
])("returns null for missing inputs", (budgetResetAt, budgetDuration) => {
expect(lastBudgetResetAt(budgetResetAt, budgetDuration)).toBeNull();
});
it("returns null for an invalid reset date", () => {
expect(lastBudgetResetAt("not-a-date", "30d")).toBeNull();
});
it("returns null for an unknown duration", () => {
expect(lastBudgetResetAt("2026-10-01T00:00:00Z", "abc")).toBeNull();
});
it.each([
["30d", "2026-09-01T00:00:00.000Z"],
["1mo", "2026-09-01T00:00:00.000Z"],
["monthly", "2026-09-01T00:00:00.000Z"],
["7d", "2026-09-24T00:00:00.000Z"],
["weekly", "2026-09-24T00:00:00.000Z"],
["1d", "2026-09-30T00:00:00.000Z"],
["daily", "2026-09-30T00:00:00.000Z"],
["12h", "2026-09-30T12:00:00.000Z"],
["45m", "2026-09-30T23:15:00.000Z"],
])("subtracts the current budget period for %s", (budgetDuration, expected) => {
expect(lastBudgetResetAt("2026-10-01T00:00:00Z", budgetDuration)?.toISOString()).toBe(expected);
});
});

View file

@ -0,0 +1,48 @@
import moment from "moment";
const budgetDurationAliases: Readonly<Record<string, string>> = {
hourly: "1h",
daily: "24h",
weekly: "7d",
monthly: "30d",
};
export const lastBudgetResetAt = (
budgetResetAt: string | null | undefined,
budgetDuration: string | null | undefined,
): Date | null => {
if (!budgetResetAt || !budgetDuration) return null;
const resetAt = moment(budgetResetAt);
if (!resetAt.isValid()) return null;
const normalizedDuration = budgetDuration.trim().toLowerCase();
const duration = budgetDurationAliases[normalizedDuration] ?? normalizedDuration;
const match = /^(\d+)(mo|[smhdw])$/.exec(duration);
if (!match) return null;
const value = Number(match[1]);
const unit = match[2];
if (unit === "mo" || (unit === "d" && value === 30)) {
return resetAt.subtract(1, "month").toDate();
}
if (unit === "w") {
return resetAt.subtract(value * 7, "days").toDate();
}
if (unit === "d") {
return resetAt.subtract(value, "days").toDate();
}
if (unit === "h") {
return resetAt.subtract(value, "hours").toDate();
}
if (unit === "m") {
return resetAt.subtract(value, "minutes").toDate();
}
return resetAt.subtract(value, "seconds").toDate();
};

View file

@ -77,6 +77,7 @@ vi.mock("./UsageViewSelect/UsageViewSelect", async () => {
"data-testid": "usage-view-select",
},
React.createElement("option", { value: "global" }, "Global Usage"),
React.createElement("option", { value: "my-usage" }, "Your Usage"),
React.createElement("option", { value: "team" }, "Team Usage"),
React.createElement("option", { value: "organization" }, "Organization Usage"),
React.createElement("option", { value: "customer" }, "Customer Usage"),
@ -92,9 +93,13 @@ vi.mock("./UsageViewSelect/UsageViewSelect", async () => {
vi.mock("@/components/shared/advanced_date_picker", async () => {
const React = await import("react");
// The button is how a test drives a range change; the real picker's own UI is
// not what any test here is asserting on.
const AdvancedDatePicker = ({ onValueChange }: { onValueChange?: (value: unknown) => void }) =>
const AdvancedDatePicker = ({
onValueChange,
additionalOptions = [],
}: {
onValueChange?: (value: unknown) => void;
additionalOptions?: readonly { label: string; getValue: () => unknown }[];
}) =>
React.createElement(
"div",
{ "data-testid": "advanced-date-picker" },
@ -108,6 +113,17 @@ vi.mock("@/components/shared/advanced_date_picker", async () => {
},
"pick",
),
...additionalOptions.map((option) =>
React.createElement(
"button",
{
key: option.label,
type: "button",
onClick: () => onValueChange?.(option.getValue()),
},
option.label,
),
),
);
AdvancedDatePicker.displayName = "AdvancedDatePicker";
return { default: AdvancedDatePicker };
@ -369,6 +385,8 @@ describe("UsagePage", () => {
data: {
user_id: "user-123",
max_budget: null,
budget_duration: null,
budget_reset_at: null,
},
isLoading: false,
error: null,
@ -586,6 +604,73 @@ describe("UsagePage", () => {
});
});
it("shows the last budget reset option in my usage view", async () => {
mockUseCurrentUser.mockReturnValue({
data: {
user_id: "user-123",
max_budget: null,
budget_duration: "30d",
budget_reset_at: "2026-10-01T00:00:00Z",
},
isLoading: false,
error: null,
} as any);
renderWithProviders(<UsagePage {...defaultProps} />);
fireEvent.change(screen.getByTestId("usage-view-select"), { target: { value: "my-usage" } });
expect(await screen.findByRole("button", { name: "Since last budget reset" })).toBeInTheDocument();
});
it("shows the last budget reset option for non-admin users", async () => {
mockUseAuthorized.mockReturnValue({
isLoading: false,
isAuthorized: true,
token: "mock-token",
accessToken: "test-token",
userId: "user-123",
userEmail: "test@example.com",
userRole: "Internal User",
premiumUser: false,
disabledPersonalKeyCreation: false,
showSSOBanner: false,
} as any);
mockUseCurrentUser.mockReturnValue({
data: {
user_id: "user-123",
max_budget: null,
budget_duration: "30d",
budget_reset_at: "2026-10-01T00:00:00Z",
},
isLoading: false,
error: null,
} as any);
renderWithProviders(<UsagePage {...defaultProps} />);
expect(await screen.findByRole("button", { name: "Since last budget reset" })).toBeInTheDocument();
});
it("does not show the last budget reset option without a budget duration", async () => {
mockUseCurrentUser.mockReturnValue({
data: {
user_id: "user-123",
max_budget: null,
budget_duration: null,
budget_reset_at: "2026-10-01T00:00:00Z",
},
isLoading: false,
error: null,
} as any);
renderWithProviders(<UsagePage {...defaultProps} />);
await waitFor(() => {
expect(screen.queryByRole("button", { name: "Since last budget reset" })).not.toBeInTheDocument();
});
});
it("should withhold the tag list until it resolves so no empty state is shown while loading", async () => {
let resolveTagList: (tags: Record<string, unknown>) => void = () => {};
mockTagListCall.mockReturnValue(

View file

@ -7,6 +7,7 @@
*/
import { ChevronDown, ChevronRight, Download, Info, Sparkles, X } from "lucide-react";
import moment from "moment";
import type { DateRangePickerValue } from "@/components/shared/date_picker_types";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
@ -39,6 +40,7 @@ import {
userDailyActivityCall,
} from "@/components/networking";
import AdvancedDatePicker from "@/components/shared/advanced_date_picker";
import type { RelativeTimeOption } from "@/components/shared/advanced_date_picker";
import { ChartLoader } from "@/components/shared/chart_loader";
import { Tag } from "@/components/tag_management/types";
import UserAgentActivity from "@/components/user_agent_activity";
@ -64,6 +66,7 @@ import { TOP_MODEL_LIMITS } from "./EntityUsage/TopModelView";
import TopKeyView from "@/components/UsagePage/components/EntityUsage/TopKeyView";
import UsageAIChatPanel from "./UsageAIChatPanel";
import { UsageOption, UsageViewSelect } from "./UsageViewSelect/UsageViewSelect";
import { lastBudgetResetAt } from "../budgetWindow";
interface UsagePageProps {
teams: Team[];
@ -137,6 +140,23 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
// For non-admins or "my-usage" view, always pass their own user_id
const effectiveUserId = usageView === "my-usage" || !isAdmin ? userID || null : selectedUserId;
const budgetWindowOptions = useMemo<RelativeTimeOption[]>(() => {
if (!(usageView === "my-usage" || !isAdmin)) return [];
const lastReset = lastBudgetResetAt(currentUser?.budget_reset_at, currentUser?.budget_duration);
if (!lastReset) return [];
return [
{
label: "Since last budget reset",
shortLabel: "budget",
getValue: () => ({
from: lastReset,
to: moment().endOf("day").toDate(),
}),
},
];
}, [currentUser?.budget_duration, currentUser?.budget_reset_at, isAdmin, usageView]);
const startTime = useMemo(() => (dateValue.from ? new Date(dateValue.from) : null), [dateValue.from]);
const endTime = useMemo(() => (dateValue.to ? new Date(dateValue.to) : null), [dateValue.to]);
@ -483,7 +503,11 @@ const UsagePage: React.FC<UsagePageProps> = ({ teams, organizations }) => {
canViewTagUsage={canViewTagUsage}
isOrgAdmin={isOrgAdmin}
/>
<AdvancedDatePicker value={dateValue} onValueChange={handleDateChange} />
<AdvancedDatePicker
value={dateValue}
onValueChange={handleDateChange}
additionalOptions={budgetWindowOptions}
/>
</div>
<PaginationStatusAlerts
isFetchingMore={paginatedResult.isFetchingMore}

View file

@ -76,6 +76,46 @@ describe("AdvancedDatePicker", () => {
expect(screen.getByText("Year to date")).toBeInTheDocument();
});
it("renders and applies additional options after the built-in presets", async () => {
const from = new Date("2025-02-01T00:00:00.000Z");
const to = new Date("2025-02-28T23:59:59.999Z");
const user = userEvent.setup();
const { container } = render(
<AdvancedDatePicker
value={defaultValue}
onValueChange={mockOnValueChange}
additionalOptions={[
{
label: "Since last budget reset",
shortLabel: "budget",
getValue: () => ({ from, to }),
},
]}
/>,
);
openDropdown(container);
const presets = container.querySelectorAll('[data-slot="advanced-date-picker-preset"]');
expect(presets).toHaveLength(6);
expect(screen.getByText("Since last budget reset")).toBeInTheDocument();
await user.click(screen.getByText("Since last budget reset"));
await user.click(screen.getByRole("button", { name: "Apply" }));
await waitFor(() => {
expect(mockOnValueChange).toHaveBeenCalledWith({ from, to });
});
});
it("renders only the built-in presets without additional options", () => {
const { container } = render(<AdvancedDatePicker value={defaultValue} onValueChange={mockOnValueChange} />);
openDropdown(container);
expect(container.querySelectorAll('[data-slot="advanced-date-picker-preset"]')).toHaveLength(5);
});
it("anchors the panel to the trigger edge named by align", () => {
const { container, unmount } = render(
<AdvancedDatePicker value={defaultValue} onValueChange={mockOnValueChange} align="left" />,

View file

@ -3,7 +3,9 @@ import { Button } from "@/components/ui/button";
import { cn } from "@/lib/cva.config";
import type { DateRangePickerValue } from "./date_picker_types";
import moment from "moment";
import React, { useCallback, useEffect, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
const emptyAdditionalOptions: readonly RelativeTimeOption[] = [];
interface AdvancedDatePickerProps {
value: DateRangePickerValue;
@ -12,9 +14,10 @@ interface AdvancedDatePickerProps {
className?: string;
showTimeRange?: boolean;
align?: "left" | "right";
additionalOptions?: readonly RelativeTimeOption[];
}
interface RelativeTimeOption {
export interface RelativeTimeOption {
label: string;
shortLabel: string;
getValue: () => { from: Date; to: Date };
@ -73,10 +76,12 @@ const AdvancedDatePicker: React.FC<AdvancedDatePickerProps> = ({
className,
showTimeRange = true,
align = "right",
additionalOptions = emptyAdditionalOptions,
}) => {
const [isOpen, setIsOpen] = useState(false);
const [tempValue, setTempValue] = useState<DateRangePickerValue>(value);
const [selectedOption, setSelectedOption] = useState<string | null>(null);
const options = useMemo(() => [...relativeTimeOptions, ...additionalOptions], [additionalOptions]);
// Custom date inputs only - removed time inputs
const [startDate, setStartDate] = useState("");
@ -88,7 +93,7 @@ const AdvancedDatePicker: React.FC<AdvancedDatePickerProps> = ({
const getMatchingOption = useCallback((currentValue: DateRangePickerValue): string | null => {
if (!currentValue.from || !currentValue.to) return null;
for (const option of relativeTimeOptions) {
for (const option of options) {
const optionRange = option.getValue();
// Compare dates with some tolerance (to account for time differences)
@ -101,7 +106,7 @@ const AdvancedDatePicker: React.FC<AdvancedDatePickerProps> = ({
}
return null;
}, []);
}, [options]);
// Update selected option when value changes
useEffect(() => {
@ -322,7 +327,7 @@ const AdvancedDatePicker: React.FC<AdvancedDatePickerProps> = ({
<span className="text-sm font-semibold text-foreground">Relative time</span>
</div>
<div className="h-[350px] overflow-y-auto">
{relativeTimeOptions.map((option) => {
{options.map((option) => {
const isSelected = selectedOption === option.shortLabel;
return (
<button