fix(ui): clarify customer usage periods and preserve date ranges (#51899)

* fix(ui): clarify customer usage periods and preserve date ranges

* fix(ui): preserve fixed customer dates with stale preset labels
This commit is contained in:
moe-berri 2026-11-15 11:09:35 +08:00 • committed by GitHub
parent aeb9ed07aa
commit bc78cbe9a2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 242 additions and 88 deletions

View file

@ -1,6 +1,6 @@
import { useTranslation } from "react-i18next";
import type { CustomerUsageEntity } from "./customerUsageApi";
import CustomerBudgetSpend, { CustomerBudgetWindow } from "./CustomerBudgetSpend";
import { CustomerBudgetWindow } from "./CustomerBudgetSpend";
import { CUSTOMER_BUDGET_LABELS, customerBudgetPeriod, customerBudgetUsage } from "./customerBudgetUsage";
export default function CustomerBudgetSummary({
@ -35,10 +35,10 @@ export default function CustomerBudgetSummary({
</div>
);
})}
{budgets.length === 0 && (
<CustomerBudgetSpend spend={entity.spend} limit={null} label={t("customerPortal.analytics.budgetSummary")} />
{budgets.length === 0 && <p className="text-muted-foreground">{t("customerPortal.analytics.noBudget")}</p>}
{budgets.length > 0 && (
<p className="text-[11px] text-muted-foreground">{t("customerPortal.analytics.budgetUsageHint")}</p>
)}
<p className="text-[11px] text-muted-foreground">{t("customerPortal.analytics.budgetUsageHint")}</p>
</section>
);
}

View file

@ -9,8 +9,7 @@ import { ErrorState } from "@/components/shared/ErrorState";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { extractProxyErrorMessage } from "@/lib/http/client";
import { uiHref } from "@/utils/uiHref";
import CustomerHierarchyNavigation, { customerHierarchyHref } from "./CustomerHierarchyNavigation";
import CustomerHierarchyNavigation, { useCustomerHierarchyLinks } from "./CustomerHierarchyNavigation";
import CustomerHierarchySettings from "./CustomerHierarchySettings";
import CustomerBudgetGroups from "./CustomerBudgetGroups";
import CustomerBudgetSummary from "./CustomerBudgetSummary";
@ -39,6 +38,7 @@ const DESCRIPTION_KEYS = {
function HierarchyHeader({ hierarchy, selected }: Pick<ScopeProps, "hierarchy" | "selected">) {
const { t } = useTranslation();
const { customerHierarchyHref, customersHref } = useCustomerHierarchyLinks();
const entity = selected.entity;
const team = selected.team;
const label = customerEntityLabel(entity);
@ -70,7 +70,7 @@ function HierarchyHeader({ hierarchy, selected }: Pick<ScopeProps, "hierarchy" |
aria-label={t("customerPortal.analytics.breadcrumb")}
className="mb-5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground"
>
<a href={uiHref("customers")} className="hover:text-foreground">
<a href={customersHref} className="hover:text-foreground">
{t("customerPortal.entities.organizations")}
</a>
<ChevronRight aria-hidden="true" className="size-3" />
@ -147,6 +147,7 @@ function hierarchyRows({ hierarchy, selected, scope }: ScopeProps) {
}
function HierarchyCreateAction({ hierarchy, selected, scope }: ScopeProps) {
const { customerHierarchyHref } = useCustomerHierarchyLinks();
const { t } = useTranslation();
const [open, setOpen] = useState(false);
if (hierarchy.childTab === "members" && selected.team === null)
@ -178,6 +179,7 @@ function HierarchyCreateAction({ hierarchy, selected, scope }: ScopeProps) {
}
function HierarchyChildTable(props: ScopeProps) {
const { customerHierarchyHref } = useCustomerHierarchyLinks();
const { t } = useTranslation();
const { hierarchy } = props;
const { children, childTab, page } = hierarchy;
@ -302,6 +304,7 @@ function HierarchyChildTable(props: ScopeProps) {
}
export default function CustomerHierarchyManager() {
const { customersHref } = useCustomerHierarchyLinks();
const { t } = useTranslation();
const router = useRouter();
const hierarchy = useCustomerHierarchy();
@ -319,7 +322,7 @@ export default function CustomerHierarchyManager() {
<div className="space-y-3 px-8 py-12">
<h1 className="text-xl font-semibold">{t("customerPortal.hierarchy.title")}</h1>
<p className="text-sm text-muted-foreground">{t("customerPortal.hierarchy.missingOrganization")}</p>
<a href={uiHref("customers")} className="text-sm text-primary hover:underline">
<a href={customersHref} className="text-sm text-primary hover:underline">
{t("customerPortal.hierarchy.backToCustomers")}
</a>
</div>
@ -349,7 +352,7 @@ export default function CustomerHierarchyManager() {
hierarchy.refresh();
if (selected.member && selected.team) hierarchy.openTeam(selected.team.customer_team_id);
else if (selected.team) hierarchy.openOrganization();
else router.push(uiHref("customers"));
else router.push(customersHref);
};
return (

View file

@ -1,7 +1,9 @@
import { useTranslation } from "react-i18next";
import { createSerializer, parseAsString, useQueryStates, type inferParserType } from "nuqs";
import { cn } from "@/lib/cva.config";
import { uiHref } from "@/utils/uiHref";
import type { CustomerUsageScope } from "./customerUsageApi";
import { customerUsageDateParsers } from "./customerUsageRange";
type CustomerHierarchyView = "usage" | "teams" | "members" | "budget_groups" | "settings";
const LABELS = {
@ -12,11 +14,30 @@ const LABELS = {
settings: "customerPortal.hierarchy.settings",
} as const;
export function customerHierarchyHref(page: "usage" | "manage", scope: CustomerUsageScope): string {
const query = new URLSearchParams({ org: scope.org });
if (scope.team) query.set("team", scope.team);
if (scope.member) query.set("member", scope.member);
return `${uiHref(`customers/${page}`)}?${query}`;
const hierarchyParsers = {
org: parseAsString,
team: parseAsString,
member: parseAsString,
...customerUsageDateParsers,
};
const hierarchyHref = createSerializer(hierarchyParsers);
const listHref = createSerializer(customerUsageDateParsers);
export function customerHierarchyHref(
page: "usage" | "manage",
scope: CustomerUsageScope,
dates: Partial<inferParserType<typeof customerUsageDateParsers>> = {},
): string {
return hierarchyHref(uiHref(`customers/${page}`), { ...scope, ...dates });
}
export function useCustomerHierarchyLinks() {
const [dates] = useQueryStates(customerUsageDateParsers);
return {
customerHierarchyHref: (page: "usage" | "manage", scope: CustomerUsageScope) =>
customerHierarchyHref(page, scope, dates),
customersHref: listHref(uiHref("customers"), dates),
};
}
export default function CustomerHierarchyNavigation({
@ -27,6 +48,7 @@ export default function CustomerHierarchyNavigation({
active: CustomerHierarchyView;
}) {
const { t } = useTranslation();
const { customerHierarchyHref } = useCustomerHierarchyLinks();
let pages: readonly CustomerHierarchyView[] = ["usage", "teams", "members", "budget_groups", "settings"];
if (scope.team) pages = ["usage", "members", "settings"];
if (scope.member) pages = ["usage", "settings"];

View file

@ -3,7 +3,8 @@ import { ChevronRight } from "lucide-react";
import { useTranslation } from "react-i18next";
import AdvancedDatePicker from "@/components/shared/advanced_date_picker";
import type { DateRangePickerValue } from "@/components/shared/date_picker_types";
import { uiHref } from "@/utils/uiHref";
import { useCustomerHierarchyLinks } from "./CustomerHierarchyNavigation";
import { customerUsagePresets, CUSTOMER_USAGE_MAX_RANGE_DAYS } from "./customerUsageRange";
import type { CustomerHierarchyUsage, CustomerUsageScope } from "./customerUsageApi";
interface CustomerUsageHeaderProps {
@ -29,12 +30,13 @@ function CustomerUsageBreadcrumbs({
onTeamClick,
}: Pick<CustomerUsageHeaderProps, "scope" | "data" | "onOrganizationClick" | "onTeamClick">) {
const { t } = useTranslation();
const { customersHref } = useCustomerHierarchyLinks();
return (
<nav
aria-label={t("customerPortal.analytics.breadcrumb")}
className="mb-5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground"
>
<a href={uiHref("customers")} className="hover:text-foreground">
<a href={customersHref} className="hover:text-foreground">
{t("customerPortal.entities.organizations")}
</a>
<ChevronRight aria-hidden="true" className="size-3" />
@ -88,7 +90,10 @@ export default function CustomerUsageHeader({
<AdvancedDatePicker
value={dateValue}
presetShortLabel={preset}
label={t("customerPortal.range.label")}
showTimeRange={false}
presets={customerUsagePresets}
maxRangeDays={CUSTOMER_USAGE_MAX_RANGE_DAYS}
onValueChange={onDateRangeChange}
/>
</div>

View file

@ -1,5 +1,14 @@
import { describe, expect, it } from "vitest";
import { customerPresetRange, customerRangeParser } from "./customerUsageRange";
import { createLoader } from "nuqs";
import {
customerDateSelection,
customerDatePatch,
customerPresetRange,
customerRangeParser,
customerUsageDateParsers,
} from "./customerUsageRange";
const loadDates = createLoader(customerUsageDateParsers);
describe("customer usage calendar ranges", () => {
it.each([
@ -7,6 +16,10 @@ describe("customer usage calendar ranges", () => {
["previous", "2025-01-01T00:00:00Z", "2024-12-01..2024-12-31"],
["YTD", "2025-01-01T00:00:00Z", "2025-01-01..2025-01-01"],
["YTD", "2025-11-12T00:01:00Z", "2025-01-01..2025-11-12"],
["MTD", "2025-01-01T00:01:00Z", "2025-01-01..2025-01-01"],
["today", "2025-01-01T00:01:00Z", "2025-01-01..2025-01-01"],
["7d", "2025-01-01T00:01:00Z", "2024-12-25..2025-01-01"],
["30d", "2024-03-01T23:59:00Z", "2024-01-31..2024-03-01"],
] as const)("resolves %s at %s as UTC calendar days", (preset, now, expected) => {
expect(customerRangeParser.serialize(customerPresetRange(preset, new Date(now)))).toBe(expected);
});
@ -17,6 +30,37 @@ describe("customer usage calendar ranges", () => {
expect(customerRangeParser.serialize(range!)).toBe("2024-02-29..2024-02-29");
});
it.each([
["?range=2024-02-01..2024-02-29&period=previous", "2024-02-01..2024-02-29", "previous"],
["?from=2024-02-01&to=2024-02-29", "2024-02-01..2024-02-29", null],
["?range=MTD&from=2024-01-01&to=2024-01-03", "2024-03-01..2024-03-01", "MTD"],
["?range=garbage", "2024-03-01..2024-03-31", "month"],
["?from=2024-02-30&to=2024-03-02", "2024-03-01..2024-03-31", "month"],
["?from=2024-03-02&to=2024-03-01", "2024-03-01..2024-03-31", "month"],
["?from=2024-01-01&to=2025-02-05", "2024-03-01..2024-03-31", "month"],
])("resolves saved links and falls back for invalid dates in %s", (query, expected, preset) => {
const selection = customerDateSelection(loadDates(query), new Date("2024-03-01T00:30:00Z"));
expect(customerRangeParser.serialize(selection.dateValue)).toBe(expected);
expect(selection.preset).toBe(preset);
});
it("keeps saved calendar dates when their preset label is stale", () => {
const now = new Date("2024-06-01T12:00:00Z");
const selection = customerDateSelection(loadDates("?range=2024-02-01..2024-02-29&period=previous"), now);
expect(selection.preset).toBeNull();
const expected = { range: null, period: null, from: "2024-02-01", to: "2024-02-29" };
expect(customerDatePatch(selection.dateValue, selection.preset)).toEqual(expected);
});
it("replaces a previous preset with the exact calendar selection", () => {
const value = { from: new Date(2024, 2, 9), to: new Date(2024, 2, 11) };
const custom = { range: null, period: null, from: "2024-03-09", to: "2024-03-11" };
const relative = { range: "7d", period: null, from: null, to: null };
expect(customerDatePatch(value, null)).toEqual(custom);
expect(customerDatePatch(value, "7d")).toEqual(relative);
expect(customerDatePatch({ from: value.to, to: value.from }, null)).toBeNull();
});
it("accepts the API's 400-day boundary across leap years and daylight saving", () => {
const range = customerRangeParser.parse("2024-01-01..2025-02-04");
expect(range).not.toBeNull();

View file

@ -1,9 +1,9 @@
import { createParser, parseAsStringLiteral, useQueryStates } from "nuqs";
import { createParser, parseAsStringLiteral, useQueryStates, type inferParserType } from "nuqs";
import { useMemo } from "react";
import type { DateRangePickerValue } from "@/components/shared/date_picker_types";
import type { RelativeTimeOption } from "@/components/shared/date_range_presets";
import { relativeTimeOptions, type RelativeTimeOption } from "@/components/shared/date_range_presets";
const PRESETS = ["month", "previous", "YTD"] as const;
const PRESETS = ["month", "previous", "YTD", "MTD", "today", "7d", "30d"] as const;
type Preset = (typeof PRESETS)[number];
type Range = { from: Date; to: Date };
@ -35,8 +35,13 @@ export const customerRangeParser = createParser<Range>({
export const customerPresetRange = (preset: Preset, now = new Date()): Range => {
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
if (preset === "YTD") {
return { from: new Date(year, 0, 1), to: new Date(year, month, now.getUTCDate(), 23, 59, 59) };
const day = now.getUTCDate();
const to = new Date(year, month, day, 23, 59, 59);
if (preset === "YTD") return { from: new Date(year, 0, 1), to };
if (preset === "MTD") return { from: new Date(year, month, 1), to };
if (preset === "today" || preset === "7d" || preset === "30d") {
const days = { today: 0, "7d": 7, "30d": 30 }[preset];
return { from: new Date(year, month, day - days), to };
}
const targetMonth = preset === "previous" ? month - 1 : month;
return { from: new Date(year, targetMonth, 1), to: new Date(year, targetMonth + 1, 0, 23, 59, 59) };
@ -55,27 +60,56 @@ export const customerUsagePresets: readonly RelativeTimeOption[] = [
settingValue: "previous_month",
getValue: () => customerPresetRange("previous"),
},
{
label: "shared.dateRangePresets.yearToDate",
shortLabel: "YTD",
settingValue: "year_to_date",
getValue: () => customerPresetRange("YTD"),
},
...relativeTimeOptions.map((option) => ({
...option,
getValue: () => customerPresetRange(presetParser.parse(option.shortLabel) ?? "month"),
})),
];
const presetParser = parseAsStringLiteral(PRESETS);
const parsers = { range: customerRangeParser, period: presetParser };
const rangeParser = createParser<Range | Preset>({
parse: (value) => presetParser.parse(value) ?? customerRangeParser.parse(value),
serialize: (value) => (typeof value === "string" ? value : customerRangeParser.serialize(value)),
eq: (a, b) => (typeof a === "string" || typeof b === "string" ? a === b : customerRangeParser.eq(a, b)),
});
const dateParser = createParser({
parse: (value) => (parseDate(value) ? value : null),
serialize: (value: string) => value,
});
export const customerUsageDateParsers = { range: rangeParser, period: presetParser, from: dateParser, to: dateParser };
type DateParams = inferParserType<typeof customerUsageDateParsers>;
export const customerDateSelection = (params: DateParams, now = new Date()) => {
if (typeof params.range === "string") {
return { dateValue: customerPresetRange(params.range, now), preset: params.range };
}
if (params.range) {
const preset =
params.period && customerRangeParser.eq(params.range, customerPresetRange(params.period, now))
? params.period
: null;
return { dateValue: params.range, preset };
}
const custom = params.from && params.to ? customerRangeParser.parse(`${params.from}..${params.to}`) : null;
if (custom) return { dateValue: custom, preset: null };
return { dateValue: customerPresetRange("month", now), preset: "month" };
};
export const customerDatePatch = (value: DateRangePickerValue, preset: string | null) => {
if (!value.from || !value.to) return null;
const from = calendarDate(value.from);
const to = calendarDate(value.to);
if (!customerRangeParser.parse(`${from}..${to}`)) return null;
const range = preset ? presetParser.parse(preset) : null;
return { range, period: null, from: range ? null : from, to: range ? null : to };
};
export const useCustomerUsageRange = () => {
const [params, setParams] = useQueryStates(parsers);
const initialRange = useMemo(() => customerPresetRange("month"), []);
const dateValue = params.range ?? initialRange;
const [params, setParams] = useQueryStates(customerUsageDateParsers);
const selection = useMemo(() => customerDateSelection(params), [params]);
const onDateChange = (value: DateRangePickerValue, preset: string | null) => {
if (!value.from || !value.to || value.from > value.to) return;
void setParams(
{ range: { from: value.from, to: value.to }, period: preset ? presetParser.parse(preset) : null },
{ history: "push" },
);
const patch = customerDatePatch(value, preset);
if (patch) void setParams(patch, { history: "push" });
};
return { dateValue, onDateChange, preset: params.range ? params.period : "month" };
return { ...selection, onDateChange };
};

View file

@ -2,26 +2,25 @@ import { useMemo } from "react";
import { skipToken, useQuery } from "@tanstack/react-query";
import { parseAsInteger, parseAsString, parseAsStringLiteral, useQueryStates } from "nuqs";
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
import {
dateRangeFromParams,
dateRangePatch,
defaultUsageDateRange,
usageUrlParsers,
} from "@/app/(dashboard)/usage/_components/usageUrlState";
import {
modelColorMap,
overviewTotals,
type Granularity,
type UsageMetric,
} from "@/app/(dashboard)/usage/_components/components/overview/overviewData";
import { formatDate } from "@/components/networking";
import type { DateRangePickerValue } from "@/components/shared/date_picker_types";
import { EMPTY_DAILY_ACTIVITY_METADATA } from "@/components/UsagePage/dailyActivityApi";
import type { DailyData } from "@/components/UsagePage/types";
import { customerHierarchyUsageCall, type CustomerUsageScope } from "./customerUsageApi";
import { rankCustomerModels, rankCustomerUsage } from "./customerUsageData";
import { CUSTOMER_USAGE_DIMENSIONS, type CustomerUsageDimension } from "./CustomerUsageRankings";
import { calendarDate, customerPresetRange } from "./customerUsageRange";
import {
calendarDate,
customerPresetRange,
customerDateSelection,
customerDatePatch,
customerUsageDateParsers,
} from "./customerUsageRange";
const usageParsers = {
org: parseAsString,
@ -32,9 +31,7 @@ const usageParsers = {
bucket: parseAsStringLiteral(["day", "week"] as const).withDefault("day"),
search: parseAsString.withDefault(""),
usagePage: parseAsInteger.withDefault(1),
range: usageUrlParsers.range,
from: usageUrlParsers.from,
to: usageUrlParsers.to,
...customerUsageDateParsers,
};
const EMPTY_RESULTS: readonly DailyData[] = [];
const ORGANIZATION_PATCH = { team: null, member: null, search: null, usagePage: null };
@ -54,11 +51,9 @@ const usageRequest = (
export default function useCustomerHierarchyUsage() {
const { accessToken } = useAuthorized();
const [params, setParams] = useQueryStates(usageParsers);
const defaultRange = useMemo(() => defaultUsageDateRange("month_to_date"), []);
const dateValue = useMemo(() => dateRangeFromParams(params) ?? defaultRange.value, [params, defaultRange]);
const preset = params.range ?? (params.from === null && params.to === null ? defaultRange.preset : null);
const startDate = dateValue.from ? formatDate(dateValue.from) : undefined;
const endDate = dateValue.to ? formatDate(dateValue.to) : undefined;
const { dateValue, preset } = useMemo(() => customerDateSelection(params), [params]);
const startDate = calendarDate(dateValue.from);
const endDate = calendarDate(dateValue.to);
const scope = params.org ? { org: params.org, team: params.team, member: params.member } : null;
const request = usageRequest(scope, accessToken, startDate, endDate);
const month = customerPresetRange("month");
@ -107,9 +102,8 @@ export default function useCustomerHierarchyUsage() {
void setParams(patch, { history: "push" });
};
const setDateRange = (value: DateRangePickerValue, selectedPreset: string | null) => {
const { range, from, to } = dateRangePatch(value, selectedPreset);
const patch = { range, from, to, usagePage: null };
void setParams(patch);
const patch = customerDatePatch(value, selectedPreset);
if (patch) void setParams({ ...patch, usagePage: null }, { history: "push" });
};
const setDimension = (breakdown: CustomerUsageDimension) =>
void setParams({ breakdown, search: null, usagePage: null });

View file

@ -216,6 +216,22 @@ describe("customer hierarchy management", () => {
testQueryClient.clear();
});
it("keeps usage dates while opening team settings and returning to usage", async () => {
const user = userEvent.setup();
renderWithProviders(<CustomerHierarchyManager />, { searchParams: "?org=org-1&from=2026-11-01&to=2026-11-03" });
await screen.findByRole("table", { name: "Customer teams" });
await user.click(screen.getByRole("button", { name: "Edit Product" }));
await screen.findByRole("heading", { name: "Product" });
expect(screen.getByRole("link", { name: "Usage", exact: true })).toHaveAttribute(
"href",
`${uiHref("customers/usage")}?org=org-1&team=team-a&from=2026-11-01&to=2026-11-03`,
);
expect(screen.getByRole("link", { name: "Customer organizations", exact: true })).toHaveAttribute(
"href",
`${uiHref("customers")}?from=2026-11-01&to=2026-11-03`,
);
});
it("should render the selected organization and request its paginated teams", async () => {
const user = userEvent.setup();
renderWithProviders(<CustomerHierarchyManager />, { searchParams: "?org=org-1" });

View file

@ -147,29 +147,32 @@ describe("customer organization overview", () => {
expect(within(overview).getByText("$100.00")).toBeInTheDocument();
});
it("restores saved sorting and changes summary dates without changing monthly shares", async () => {
const user = userEvent.setup();
renderWithProviders(<CustomersPage />, {
searchParams: "?sort_by=customer&sort_order=asc&range=2024-02-01..2024-02-29",
});
await screen.findByRole("link", { name: "Customer 00" });
expect(customerLinks()[0]).toHaveTextContent("Customer 00");
expect(
within(screen.getByRole("region", { name: "Overall customer usage" })).getByText("$20.00"),
).toBeInTheDocument();
expect(within(screen.getByRole("row", { name: /Customer 00/ })).getByText("75%")).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Customer 00" })).toHaveAttribute(
"href",
"/ui/customers/usage?org=customer-00&from=2024-02-01&to=2024-02-29",
);
await user.click(screen.getByRole("button", { name: /1 Feb 2024/ }));
await user.click(screen.getByRole("button", { name: /This month/ }));
await user.click(screen.getByRole("button", { name: "Apply" }));
expect(
await within(screen.getByRole("region", { name: "Overall customer usage" })).findByText("$100.00"),
).toBeInTheDocument();
expect(within(screen.getByRole("row", { name: /Customer 00/ })).getByText("75%")).toBeInTheDocument();
});
it.each(["range=2024-02-01..2024-02-29", "from=2024-02-01&to=2024-02-29"])(
"restores saved sorting and %s without changing monthly shares",
async (dates) => {
const user = userEvent.setup();
renderWithProviders(<CustomersPage />, {
searchParams: `?sort_by=customer&sort_order=asc&${dates}`,
});
await screen.findByRole("link", { name: "Customer 00" });
expect(customerLinks()[0]).toHaveTextContent("Customer 00");
expect(
within(screen.getByRole("region", { name: "Overall customer usage" })).getByText("$20.00"),
).toBeInTheDocument();
expect(within(screen.getByRole("row", { name: /Customer 00/ })).getByText("75%")).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Customer 00" })).toHaveAttribute(
"href",
"/ui/customers/usage?org=customer-00&from=2024-02-01&to=2024-02-29",
);
await user.click(screen.getByRole("button", { name: /1 Feb 2024/ }));
await user.click(screen.getByRole("button", { name: /This month/ }));
await user.click(screen.getByRole("button", { name: "Apply" }));
expect(
await within(screen.getByRole("region", { name: "Overall customer usage" })).findByText("$100.00"),
).toBeInTheDocument();
expect(within(screen.getByRole("row", { name: /Customer 00/ })).getByText("75%")).toBeInTheDocument();
},
);
it("shows a newly created customer first and resets the search, sort, and page", async () => {
const user = userEvent.setup();

View file

@ -209,13 +209,45 @@ describe("CustomerHierarchyUsagePage", () => {
vi.unstubAllGlobals();
});
it.each([
["2026-11-15T00:30:00Z", "", "2026-11-01", "2026-11-30"],
["2027-01-01T00:30:00Z", "", "2027-01-01", "2027-01-31"],
["2026-11-15T00:30:00Z", "&range=MTD", "2026-11-01", "2026-11-15"],
["2026-11-30T23:30:00Z", "&range=today", "2026-11-30", "2026-11-30"],
])("uses UTC calendar dates at %s with %s", async (now, query, startDate, endDate) => {
vi.setSystemTime(new Date(now));
renderWithProviders(<CustomerHierarchyUsagePage />, { searchParams: `?org=org-1${query}` });
await screen.findByRole("heading", { name: "Customer organization" });
expect(
requestedUrls()
.find((url) => url.pathname.endsWith("/daily/activity"))
?.searchParams.get("start_date"),
).toBe(startDate);
expect(
requestedUrls()
.find((url) => url.pathname.endsWith("/daily/activity"))
?.searchParams.get("end_date"),
).toBe(endDate);
});
it("keeps the selected dates in customer navigation and the return to all customers", async () => {
renderWithProviders(<CustomerHierarchyUsagePage />, { searchParams: initialUrl });
await screen.findByRole("heading", { name: "Customer organization" });
for (const name of ["Customer teams", "Customer members", "Settings", "Customer organizations"]) {
const link = screen.getByRole("link", { name, exact: true });
const url = new URL(link.getAttribute("href")!, "http://localhost");
expect(url.searchParams.get("from")).toBe("2026-11-01");
expect(url.searchParams.get("to")).toBe("2026-11-03");
}
});
it("should render organization totals and model rankings from the selected UTC date range", async () => {
renderWithProviders(<CustomerHierarchyUsagePage />, { searchParams: initialUrl });
expect(await screen.findByRole("heading", { name: "Customer organization" })).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Customer teams", exact: true })).toHaveAttribute(
"href",
"/ui/customers/manage?org=org-1",
"/ui/customers/manage?org=org-1&from=2026-11-01&to=2026-11-03",
);
expect(screen.getByText("$15.00")).toBeInTheDocument();
const budget = screen.getByRole("region", { name: "Current budget" });
@ -223,7 +255,7 @@ describe("CustomerHierarchyUsagePage", () => {
expect(within(budget).getByText("Recorded budget spend")).toBeInTheDocument();
expect(within(budget).getByRole("link", { name: "Edit budget" })).toHaveAttribute(
"href",
"/ui/customers/manage?org=org-1&tab=settings",
"/ui/customers/manage?org=org-1&from=2026-11-01&to=2026-11-03&tab=settings",
);
expect(screen.getByTitle("700 tokens")).toBeInTheDocument();
expect(screen.getByRole("heading", { name: "Usage over time" })).toBeInTheDocument();
@ -276,10 +308,11 @@ describe("CustomerHierarchyUsagePage", () => {
expect(activityUrl("customer_teams", "team-a")?.pathname).toBe("/management/v1/customer_teams/daily/activity");
expect(activityUrl("customer_teams", "team-a")?.searchParams.get("customer_team_ids")).toBe("team-a");
const teamBudget = screen.getByRole("region", { name: "Current budget" });
expect(within(teamBudget).getByText("$40.00 / No limit")).toBeInTheDocument();
expect(within(teamBudget).getByText("No budget set")).toBeInTheDocument();
expect(within(teamBudget).queryByText(/\$40\.00/)).not.toBeInTheDocument();
expect(within(teamBudget).getByRole("link", { name: "Set budget" })).toHaveAttribute(
"href",
"/ui/customers/manage?org=org-1&team=team-a&tab=settings",
"/ui/customers/manage?org=org-1&team=team-a&from=2026-11-01&to=2026-11-03&tab=settings",
);
await user.click(
@ -290,7 +323,7 @@ describe("CustomerHierarchyUsagePage", () => {
expect(within(memberBudget).getByText("$40.00 / $10.00")).toBeInTheDocument();
expect(within(memberBudget).getByRole("link", { name: "Edit budget" })).toHaveAttribute(
"href",
"/ui/customers/manage?org=org-1&team=team-a&member=member-a&tab=settings",
"/ui/customers/manage?org=org-1&team=team-a&member=member-a&from=2026-11-01&to=2026-11-03&tab=settings",
);
const memberUrl = activityUrl("customer_members", "member-a")!;
expect(memberUrl.pathname).toBe("/management/v1/customer_members/daily/activity");

View file

@ -5,10 +5,9 @@ import UsageStatStrip from "@/app/(dashboard)/usage/_components/components/overv
import { ErrorState } from "@/components/shared/ErrorState";
import { Button } from "@/components/ui/button";
import { extractProxyErrorMessage } from "@/lib/http/client";
import { uiHref } from "@/utils/uiHref";
import CustomerMemberSpend from "../_components/CustomerMemberSpend";
import CustomerUsageHeader from "../_components/CustomerUsageHeader";
import CustomerHierarchyNavigation, { customerHierarchyHref } from "../_components/CustomerHierarchyNavigation";
import CustomerHierarchyNavigation, { useCustomerHierarchyLinks } from "../_components/CustomerHierarchyNavigation";
import CustomerBudgetSummary from "../_components/CustomerBudgetSummary";
import CustomerUsageRankings from "../_components/CustomerUsageRankings";
import CustomerUsageTrend from "../_components/CustomerUsageTrend";
@ -27,6 +26,7 @@ const TOP_DIMENSION_LABELS = {
export default function CustomerHierarchyUsagePage() {
const { t } = useTranslation();
const { customerHierarchyHref, customersHref } = useCustomerHierarchyLinks();
const {
params,
scope,
@ -57,7 +57,7 @@ export default function CustomerHierarchyUsagePage() {
<div className="px-8 py-12">
<h1 className="text-xl font-semibold">{t("customerPortal.analytics.title")}</h1>
<p className="mt-2 text-sm text-muted-foreground">{t("customerPortal.analytics.selectOrganization")}</p>
<a className="mt-5 inline-block text-sm font-medium text-primary hover:underline" href={uiHref("customers")}>
<a className="mt-5 inline-block text-sm font-medium text-primary hover:underline" href={customersHref}>
{t("customerPortal.analytics.backToCustomers")}
</a>
</div>