You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airavata.apache.org by la...@apache.org on 2026/07/09 20:33:07 UTC
(airavata-custos) 02/08: Clusters, resources, and resource rate management UI components
This is an automated email from the ASF dual-hosted git repository.
lahirujayathilake pushed a commit to branch web-changes
in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit 918722dbcf09c073191b2c174d4aa9b5da819bcc
Author: lahiruj <la...@gmail.com>
AuthorDate: Wed Jul 8 02:30:19 2026 -0400
Clusters, resources, and resource rate management UI components
---
.../core/clusters/__fixtures__/cluster-users.json | 16 +-
.../core/clusters/__fixtures__/clusters.json | 4 +-
.../core/clusters/__tests__/ClustersTab.test.tsx | 10 +-
.../features/core/clusters/__tests__/api.test.ts | 24 ++-
.../core/clusters/__tests__/queries.test.ts | 4 +-
.../core/clusters/__tests__/schemas.test.ts | 8 +-
web/src/features/core/clusters/api.ts | 8 +-
.../core/resources/__fixtures__/rates.json | 16 +-
.../core/resources/__fixtures__/resources.json | 24 +--
.../__tests__/ResourcesRatesDrawer.test.tsx | 190 +++++++++++++++----
.../core/resources/__tests__/ResourcesTab.test.tsx | 34 ++--
.../features/core/resources/__tests__/api.test.ts | 24 ++-
.../core/resources/__tests__/queries.test.tsx | 57 ++++++
.../core/resources/__tests__/schemas.test.ts | 8 +-
web/src/features/core/resources/api.ts | 23 ++-
.../resources/components/ResourcesRatesDrawer.tsx | 207 +++++++++++++++++++--
web/src/features/core/resources/queries.ts | 15 +-
web/src/features/core/resources/schemas.ts | 31 ++-
web/src/mocks/handlers/resources.ts | 13 ++
web/tests/admin-read-only.e2e.ts | 33 +++-
web/tests/admin-viewer.e2e.ts | 9 +
21 files changed, 620 insertions(+), 138 deletions(-)
diff --git a/web/src/features/core/clusters/__fixtures__/cluster-users.json b/web/src/features/core/clusters/__fixtures__/cluster-users.json
index 88ac10a6e..16338d9e6 100644
--- a/web/src/features/core/clusters/__fixtures__/cluster-users.json
+++ b/web/src/features/core/clusters/__fixtures__/cluster-users.json
@@ -1,19 +1,19 @@
[
{
- "id": "ccu-anvil-ada",
- "compute_cluster_id": "cluster-anvil",
+ "id": "ccu-a-ada",
+ "compute_cluster_id": "cluster-a",
"user_id": "user-ada-lovelace",
"local_username": "alovelace"
},
{
- "id": "ccu-anvil-grace",
- "compute_cluster_id": "cluster-anvil",
+ "id": "ccu-a-grace",
+ "compute_cluster_id": "cluster-a",
"user_id": "user-grace-hopper",
"local_username": "ghopper"
},
{
- "id": "ccu-anvil-dennis",
- "compute_cluster_id": "cluster-anvil",
+ "id": "ccu-a-dennis",
+ "compute_cluster_id": "cluster-a",
"user_id": "user-dennis-ritchie",
"local_username": "dritchie"
},
@@ -30,8 +30,8 @@
"local_username": "kjohnson"
},
{
- "id": "ccu-delta-donald",
- "compute_cluster_id": "cluster-delta",
+ "id": "ccu-b-donald",
+ "compute_cluster_id": "cluster-b",
"user_id": "user-donald-knuth",
"local_username": "dknuth"
}
diff --git a/web/src/features/core/clusters/__fixtures__/clusters.json b/web/src/features/core/clusters/__fixtures__/clusters.json
index 6715d7894..b6e873f04 100644
--- a/web/src/features/core/clusters/__fixtures__/clusters.json
+++ b/web/src/features/core/clusters/__fixtures__/clusters.json
@@ -1,6 +1,6 @@
[
- { "id": "cluster-anvil", "name": "Anvil" },
+ { "id": "cluster-a", "name": "ClusterA" },
{ "id": "cluster-bridges2", "name": "Bridges-2" },
{ "id": "cluster-expanse", "name": "Expanse" },
- { "id": "cluster-delta", "name": "Delta" }
+ { "id": "cluster-b", "name": "ClusterB" }
]
diff --git a/web/src/features/core/clusters/__tests__/ClustersTab.test.tsx b/web/src/features/core/clusters/__tests__/ClustersTab.test.tsx
index eb83300f1..bb1d55e91 100644
--- a/web/src/features/core/clusters/__tests__/ClustersTab.test.tsx
+++ b/web/src/features/core/clusters/__tests__/ClustersTab.test.tsx
@@ -31,13 +31,13 @@ import { ClustersTab } from "../components/ClustersTab";
beforeEach(() => {
clusters = [
- { id: "cluster-anvil", name: "Anvil" },
+ { id: "cluster-a", name: "ClusterA" },
{ id: "cluster-bridges2", name: "Bridges-2" },
];
users = [
{
id: "ccu-1",
- compute_cluster_id: "cluster-anvil",
+ compute_cluster_id: "cluster-a",
user_id: "user-ada-lovelace",
local_username: "alovelace",
},
@@ -48,15 +48,15 @@ describe("<ClustersTab />", () => {
it("filters clusters client-side by name", () => {
render(<ClustersTab />);
fireEvent.change(screen.getByLabelText("Search clusters"), { target: { value: "bridges" } });
- expect(screen.queryByText("Anvil")).not.toBeInTheDocument();
+ expect(screen.queryByText("ClusterA")).not.toBeInTheDocument();
expect(screen.getByText("Bridges-2")).toBeInTheDocument();
});
it("opens a drawer with local users, rendering the user id as plain text", () => {
render(<ClustersTab />);
- fireEvent.click(screen.getByRole("button", { name: "Anvil" }));
+ fireEvent.click(screen.getByRole("button", { name: "ClusterA" }));
- expect(screen.getByText("Cluster: Anvil")).toBeInTheDocument();
+ expect(screen.getByText("Cluster: ClusterA")).toBeInTheDocument();
expect(screen.getByText("alovelace")).toBeInTheDocument();
expect(screen.getByText("user-ada-lovelace")).toBeInTheDocument();
expect(screen.queryByRole("link", { name: "user-ada-lovelace" })).not.toBeInTheDocument();
diff --git a/web/src/features/core/clusters/__tests__/api.test.ts b/web/src/features/core/clusters/__tests__/api.test.ts
index 7e0069b9d..5e1bf4951 100644
--- a/web/src/features/core/clusters/__tests__/api.test.ts
+++ b/web/src/features/core/clusters/__tests__/api.test.ts
@@ -30,10 +30,10 @@ afterEach(() => {
fetchMock.mockReset();
});
-const cluster = { id: "cluster-anvil", name: "Anvil" };
+const cluster = { id: "cluster-a", name: "ClusterA" };
const clusterUser = {
id: "ccu-1",
- compute_cluster_id: "cluster-anvil",
+ compute_cluster_id: "cluster-a",
user_id: "user-ada-lovelace",
local_username: "alovelace",
};
@@ -43,22 +43,34 @@ describe("listClusters", () => {
fetchMock.mockResolvedValueOnce(mockResponse(200, [cluster]));
const out = await listClusters();
expect(out).toHaveLength(1);
- expect(out[0]?.name).toBe("Anvil");
+ expect(out[0]?.name).toBe("ClusterA");
+ });
+
+ it("returns an empty array when the backend sends null", async () => {
+ fetchMock.mockResolvedValueOnce(mockResponse(200, "null"));
+ await expect(listClusters()).resolves.toEqual([]);
+ });
+});
+
+describe("listClusterUsers null body", () => {
+ it("returns an empty array when the backend sends null", async () => {
+ fetchMock.mockResolvedValueOnce(mockResponse(200, "null"));
+ await expect(listClusterUsers("cluster-a")).resolves.toEqual([]);
});
});
describe("getCluster", () => {
it("parses a single cluster", async () => {
fetchMock.mockResolvedValueOnce(mockResponse(200, cluster));
- const out = await getCluster("cluster-anvil");
- expect(out.id).toBe("cluster-anvil");
+ const out = await getCluster("cluster-a");
+ expect(out.id).toBe("cluster-a");
});
});
describe("listClusterUsers", () => {
it("parses a bare array of cluster users", async () => {
fetchMock.mockResolvedValueOnce(mockResponse(200, [clusterUser]));
- const out = await listClusterUsers("cluster-anvil");
+ const out = await listClusterUsers("cluster-a");
expect(out[0]?.local_username).toBe("alovelace");
});
});
diff --git a/web/src/features/core/clusters/__tests__/queries.test.ts b/web/src/features/core/clusters/__tests__/queries.test.ts
index e602a7fef..7c9caeb6c 100644
--- a/web/src/features/core/clusters/__tests__/queries.test.ts
+++ b/web/src/features/core/clusters/__tests__/queries.test.ts
@@ -24,7 +24,7 @@ describe("clusterKeys", () => {
});
it("detail and users keys carry the id", () => {
- expect(clusterKeys.detail("cluster-anvil")).toEqual(["clusters", "detail", "cluster-anvil"]);
- expect(clusterKeys.users("cluster-anvil")).toEqual(["clusters", "users", "cluster-anvil"]);
+ expect(clusterKeys.detail("cluster-a")).toEqual(["clusters", "detail", "cluster-a"]);
+ expect(clusterKeys.users("cluster-a")).toEqual(["clusters", "users", "cluster-a"]);
});
});
diff --git a/web/src/features/core/clusters/__tests__/schemas.test.ts b/web/src/features/core/clusters/__tests__/schemas.test.ts
index 65fe62c0e..3e07a6095 100644
--- a/web/src/features/core/clusters/__tests__/schemas.test.ts
+++ b/web/src/features/core/clusters/__tests__/schemas.test.ts
@@ -20,11 +20,11 @@ import { computeClusterSchema, computeClusterUserSchema } from "../schemas";
describe("computeClusterSchema", () => {
it("accepts a cluster with id and name", () => {
- expect(computeClusterSchema.parse({ id: "cluster-anvil", name: "Anvil" }).name).toBe("Anvil");
+ expect(computeClusterSchema.parse({ id: "cluster-a", name: "ClusterA" }).name).toBe("ClusterA");
});
it("rejects a cluster missing its name", () => {
- expect(computeClusterSchema.safeParse({ id: "cluster-anvil" }).success).toBe(false);
+ expect(computeClusterSchema.safeParse({ id: "cluster-a" }).success).toBe(false);
});
});
@@ -32,7 +32,7 @@ describe("computeClusterUserSchema", () => {
it("accepts a fully populated cluster user", () => {
const parsed = computeClusterUserSchema.parse({
id: "ccu-1",
- compute_cluster_id: "cluster-anvil",
+ compute_cluster_id: "cluster-a",
user_id: "user-ada-lovelace",
local_username: "alovelace",
});
@@ -42,7 +42,7 @@ describe("computeClusterUserSchema", () => {
it("rejects a cluster user missing its local username", () => {
const result = computeClusterUserSchema.safeParse({
id: "ccu-1",
- compute_cluster_id: "cluster-anvil",
+ compute_cluster_id: "cluster-a",
user_id: "user-ada-lovelace",
});
expect(result.success).toBe(false);
diff --git a/web/src/features/core/clusters/api.ts b/web/src/features/core/clusters/api.ts
index 5b6cf7356..9f15fdc3e 100644
--- a/web/src/features/core/clusters/api.ts
+++ b/web/src/features/core/clusters/api.ts
@@ -24,9 +24,13 @@ import {
computeClusterUserSchema,
} from "./schemas";
+// The backend serializes empty lists as JSON null (Go nil slice).
+const clusterListSchema = z.array(computeClusterSchema).nullable();
+const clusterUserListSchema = z.array(computeClusterUserSchema).nullable();
+
export async function listClusters(): Promise<ComputeCluster[]> {
const raw = await apiFetch("/compute-clusters");
- return z.array(computeClusterSchema).parse(raw);
+ return clusterListSchema.parse(raw) ?? [];
}
export async function getCluster(id: string): Promise<ComputeCluster> {
@@ -36,5 +40,5 @@ export async function getCluster(id: string): Promise<ComputeCluster> {
export async function listClusterUsers(id: string): Promise<ComputeClusterUser[]> {
const raw = await apiFetch(`/compute-clusters/${id}/users`);
- return z.array(computeClusterUserSchema).parse(raw);
+ return clusterUserListSchema.parse(raw) ?? [];
}
diff --git a/web/src/features/core/resources/__fixtures__/rates.json b/web/src/features/core/resources/__fixtures__/rates.json
index 833ca49ea..4c676c730 100644
--- a/web/src/features/core/resources/__fixtures__/rates.json
+++ b/web/src/features/core/resources/__fixtures__/rates.json
@@ -1,28 +1,28 @@
[
{
- "id": "rate-anvil-cpu-current",
- "compute_allocation_resource_id": "res-anvil-cpu",
+ "id": "rate-a-cpu-current",
+ "compute_allocation_resource_id": "res-a-cpu",
"rate": 0.05,
"start_time": "2020-01-01T00:00:00Z",
"end_time": "2035-01-01T00:00:00Z"
},
{
- "id": "rate-anvil-cpu-old",
- "compute_allocation_resource_id": "res-anvil-cpu",
+ "id": "rate-a-cpu-old",
+ "compute_allocation_resource_id": "res-a-cpu",
"rate": 0.04,
"start_time": "2018-01-01T00:00:00Z",
"end_time": "2020-01-01T00:00:00Z"
},
{
- "id": "rate-anvil-gpu-current",
- "compute_allocation_resource_id": "res-anvil-gpu",
+ "id": "rate-a-gpu-current",
+ "compute_allocation_resource_id": "res-a-gpu",
"rate": 0.5,
"start_time": "2021-06-01T00:00:00Z",
"end_time": "2035-06-01T00:00:00Z"
},
{
- "id": "rate-anvil-gpu-old",
- "compute_allocation_resource_id": "res-anvil-gpu",
+ "id": "rate-a-gpu-old",
+ "compute_allocation_resource_id": "res-a-gpu",
"rate": 0.45,
"start_time": "2019-06-01T00:00:00Z",
"end_time": "2021-06-01T00:00:00Z"
diff --git a/web/src/features/core/resources/__fixtures__/resources.json b/web/src/features/core/resources/__fixtures__/resources.json
index d4eeb62bb..664f304a3 100644
--- a/web/src/features/core/resources/__fixtures__/resources.json
+++ b/web/src/features/core/resources/__fixtures__/resources.json
@@ -1,17 +1,17 @@
[
{
- "id": "res-anvil-cpu",
- "name": "Anvil CPU",
+ "id": "res-a-cpu",
+ "name": "ClusterA CPU",
"resource_type": "CPU",
"resource_amount": 1000000,
- "compute_cluster_id": "cluster-anvil"
+ "compute_cluster_id": "cluster-a"
},
{
- "id": "res-anvil-gpu",
- "name": "Anvil GPU",
+ "id": "res-a-gpu",
+ "name": "ClusterA GPU",
"resource_type": "GPU",
"resource_amount": 50000,
- "compute_cluster_id": "cluster-anvil"
+ "compute_cluster_id": "cluster-a"
},
{
"id": "res-bridges2-cpu",
@@ -35,17 +35,17 @@
"compute_cluster_id": "cluster-expanse"
},
{
- "id": "res-delta-cpu",
- "name": "Delta CPU",
+ "id": "res-b-cpu",
+ "name": "ClusterB CPU",
"resource_type": "CPU",
"resource_amount": 600000,
- "compute_cluster_id": "cluster-delta"
+ "compute_cluster_id": "cluster-b"
},
{
- "id": "res-delta-gpu",
- "name": "Delta GPU A100",
+ "id": "res-b-gpu",
+ "name": "ClusterB GPU A100",
"resource_type": "GPU",
"resource_amount": 40000,
- "compute_cluster_id": "cluster-delta"
+ "compute_cluster_id": "cluster-b"
}
]
diff --git a/web/src/features/core/resources/__tests__/ResourcesRatesDrawer.test.tsx b/web/src/features/core/resources/__tests__/ResourcesRatesDrawer.test.tsx
index a7ad1445b..f743edff6 100644
--- a/web/src/features/core/resources/__tests__/ResourcesRatesDrawer.test.tsx
+++ b/web/src/features/core/resources/__tests__/ResourcesRatesDrawer.test.tsx
@@ -15,68 +15,192 @@
// specific language governing permissions and limitations
// under the License.
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Rate } from "../schemas";
-// Windows are anchored far in the past/future so the ACTIVE/EXPIRED derivation
-// stays stable regardless of the wall clock at test time.
-const activeRate: Rate = {
- id: "rate-current",
- compute_allocation_resource_id: "res-1",
- rate: 0.05,
- start_time: "2000-01-01T00:00:00Z",
- end_time: "2100-01-01T00:00:00Z",
-};
-const expiredRate: Rate = {
- id: "rate-old",
- compute_allocation_resource_id: "res-1",
- rate: 0.04,
- start_time: "2000-01-01T00:00:00Z",
- end_time: "2001-01-01T00:00:00Z",
-};
+// Windows are anchored far in the past/future so classifyRate stays stable
+// regardless of the wall clock at test time (assumes now is 2011..2098).
+const expiredRate: Rate = rate("rate-expired", 0.03, "2000-01-01T00:00:00Z", "2001-01-01T00:00:00Z");
+const supersededRate: Rate = rate("rate-super", 0.04, "2001-01-01T00:00:00Z", "2100-01-01T00:00:00Z");
+const activeRate: Rate = rate("rate-active", 0.05, "2010-01-01T00:00:00Z", "2100-01-01T00:00:00Z");
+const scheduledRate: Rate = rate("rate-sched", 0.06, "2099-01-01T00:00:00Z", "2100-01-01T00:00:00Z");
+
+function rate(id: string, value: number, start: string, end: string): Rate {
+ return { id, compute_allocation_resource_id: "res-1", rate: value, start_time: start, end_time: end };
+}
let rates: Rate[] = [];
let effective: Rate | undefined;
+let canManage = true;
+const mutation = { mutateAsync: vi.fn(), isPending: false };
vi.mock("../queries", () => ({
useResourceRates: () => ({ data: rates, isLoading: false, error: null, refetch: vi.fn() }),
useEffectiveRate: () => ({ data: effective, isLoading: false, error: null, refetch: vi.fn() }),
+ useCreateResourceRate: () => mutation,
+}));
+
+vi.mock("@/shared/casl/AbilityProvider", () => ({
+ useAbility: () => ({ can: () => canManage }),
+}));
+
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: vi.fn() },
}));
+import { toast } from "sonner";
import { ResourcesRatesDrawer } from "../components/ResourcesRatesDrawer";
+function renderDrawer() {
+ return render(
+ <ResourcesRatesDrawer resourceId="res-1" resourceName="ClusterA CPU" onOpenChange={vi.fn()} />,
+ );
+}
+
+function openForm() {
+ fireEvent.click(screen.getByRole("button", { name: "+ Add rate" }));
+}
+
+function todayUtc(): string {
+ return new Date().toISOString().slice(0, 10);
+}
+
beforeEach(() => {
- rates = [activeRate, expiredRate];
+ rates = [expiredRate, supersededRate, activeRate, scheduledRate];
effective = activeRate;
+ canManage = true;
+ mutation.isPending = false;
+ mutation.mutateAsync = vi.fn().mockResolvedValue({});
+ vi.mocked(toast.success).mockClear();
+ vi.mocked(toast.error).mockClear();
});
describe("<ResourcesRatesDrawer />", () => {
- it("derives ACTIVE and EXPIRED badges per rate window", () => {
- render(
- <ResourcesRatesDrawer resourceId="res-1" resourceName="Anvil CPU" onOpenChange={vi.fn()} />,
+ it("renders the effective card with an ACTIVE badge, omitted on 404", () => {
+ const { rerender } = renderDrawer();
+ expect(screen.getByText("Effective rate")).toBeInTheDocument();
+
+ effective = undefined;
+ rerender(
+ <ResourcesRatesDrawer resourceId="res-1" resourceName="ClusterA CPU" onOpenChange={vi.fn()} />,
);
- // One badge in the effective card plus one per active history row.
- expect(screen.getAllByText("ACTIVE").length).toBeGreaterThanOrEqual(2);
- expect(screen.getByText("EXPIRED")).toBeInTheDocument();
+ expect(screen.queryByText("Effective rate")).not.toBeInTheDocument();
});
- it("titles the drawer with the resource name and shows the effective rate", () => {
- render(
- <ResourcesRatesDrawer resourceId="res-1" resourceName="Anvil CPU" onOpenChange={vi.fn()} />,
+ it("classifies each row and sorts start_time DESC", () => {
+ effective = undefined; // keep ACTIVE unique to the table
+ renderDrawer();
+ const rows = screen.getAllByRole("row").slice(1); // drop header
+ const badges = rows.map((r) => within(r).getByText(/ACTIVE|SCHEDULED|SUPERSEDED|EXPIRED/).textContent);
+ expect(badges).toEqual(["SCHEDULED", "ACTIVE", "SUPERSEDED", "EXPIRED"]);
+ });
+
+ it("hides Add rate without manage Allocation and shows it with it", () => {
+ canManage = false;
+ const { rerender } = renderDrawer();
+ expect(screen.queryByRole("button", { name: "+ Add rate" })).not.toBeInTheDocument();
+
+ canManage = true;
+ rerender(
+ <ResourcesRatesDrawer resourceId="res-1" resourceName="ClusterA CPU" onOpenChange={vi.fn()} />,
+ );
+ expect(screen.getByRole("button", { name: "+ Add rate" })).toBeInTheDocument();
+ });
+
+ it("opens the form with end date pre-filled to start + 1 year", () => {
+ renderDrawer();
+ openForm();
+ const start = todayUtc();
+ const expectedEnd = new Date(start);
+ expectedEnd.setUTCFullYear(expectedEnd.getUTCFullYear() + 1);
+ expect((screen.getByLabelText("Effective date") as HTMLInputElement).value).toBe(start);
+ expect((screen.getByLabelText("Ends") as HTMLInputElement).value).toBe(
+ expectedEnd.toISOString().slice(0, 10),
);
- expect(screen.getByText("Rates: Anvil CPU")).toBeInTheDocument();
- expect(screen.getByText("Effective rate")).toBeInTheDocument();
});
- it("shows the empty state when no rates are recorded", () => {
+ it("rejects a negative rate inline without posting", async () => {
+ renderDrawer();
+ openForm();
+ fireEvent.change(screen.getByLabelText("Rate"), { target: { value: "-1" } });
+ fireEvent.click(screen.getByRole("button", { name: "Add rate" }));
+ expect(await screen.findByText(/zero or greater/i)).toBeInTheDocument();
+ expect(mutation.mutateAsync).not.toHaveBeenCalled();
+ });
+
+ it("rejects end on or before start inline without posting", async () => {
+ renderDrawer();
+ openForm();
+ fireEvent.change(screen.getByLabelText("Rate"), { target: { value: "0.07" } });
+ fireEvent.change(screen.getByLabelText("Ends"), {
+ target: { value: (screen.getByLabelText("Effective date") as HTMLInputElement).value },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Add rate" }));
+ expect(await screen.findByText(/after the start date/i)).toBeInTheDocument();
+ expect(mutation.mutateAsync).not.toHaveBeenCalled();
+ });
+
+ it("posts a today rate with a now start_time, toasts and collapses", async () => {
+ renderDrawer();
+ openForm();
+ fireEvent.change(screen.getByLabelText("Rate"), { target: { value: "0.07" } });
+ fireEvent.click(screen.getByRole("button", { name: "Add rate" }));
+
+ await waitFor(() => expect(mutation.mutateAsync).toHaveBeenCalledTimes(1));
+ const payload = mutation.mutateAsync.mock.calls[0]?.[0] as {
+ compute_allocation_resource_id: string;
+ rate: number;
+ start_time: string;
+ };
+ expect(payload.compute_allocation_resource_id).toBe("res-1");
+ expect(payload.rate).toBe(0.07);
+ // Today -> current wall-clock instant, not midnight.
+ expect(payload.start_time).not.toBe(`${todayUtc()}T00:00:00Z`);
+ expect(payload.start_time).toMatch(/T\d\d:\d\d/);
+ expect(toast.success).toHaveBeenCalledWith("Rate added.");
+ await waitFor(() =>
+ expect(screen.queryByRole("form", { name: "Add rate form" })).not.toBeInTheDocument(),
+ );
+ });
+
+ it("keeps the populated form and shows a backend error without toasting", async () => {
+ mutation.mutateAsync = vi.fn().mockRejectedValue(new Error("Rate conflicts with an existing window"));
+ renderDrawer();
+ openForm();
+ fireEvent.change(screen.getByLabelText("Rate"), { target: { value: "0.09" } });
+ fireEvent.click(screen.getByRole("button", { name: "Add rate" }));
+
+ expect(await screen.findByText(/conflicts with an existing window/i)).toBeInTheDocument();
+ expect(screen.getByRole("form", { name: "Add rate form" })).toBeInTheDocument();
+ expect((screen.getByLabelText("Rate") as HTMLInputElement).value).toBe("0.09");
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it("switches the preview copy between immediate and scheduled", () => {
+ renderDrawer();
+ openForm();
+ expect(screen.getByText(/becomes the active rate immediately/i)).toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText("Effective date"), { target: { value: "2099-06-01" } });
+ expect(screen.getByText(/Scheduled to take effect/i)).toBeInTheDocument();
+ });
+
+ it("warns about a pricing gap when no later rate follows the new end", () => {
+ rates = [rate("rate-only", 0.05, "2000-01-01T00:00:00Z", "2100-01-01T00:00:00Z")];
+ renderDrawer();
+ openForm();
+ // Default end is ~1 year out; nothing in history starts after it.
+ expect(screen.getByText(/avoid a pricing gap/i)).toBeInTheDocument();
+ });
+
+ it("shows the empty state with an Add rate action", () => {
rates = [];
effective = undefined;
- render(
- <ResourcesRatesDrawer resourceId="res-1" resourceName="Anvil CPU" onOpenChange={vi.fn()} />,
- );
+ renderDrawer();
expect(
screen.getByRole("heading", { name: /no rates recorded for this resource/i }),
).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "+ Add rate" })).toBeInTheDocument();
});
});
diff --git a/web/src/features/core/resources/__tests__/ResourcesTab.test.tsx b/web/src/features/core/resources/__tests__/ResourcesTab.test.tsx
index e99c3efb9..218062101 100644
--- a/web/src/features/core/resources/__tests__/ResourcesTab.test.tsx
+++ b/web/src/features/core/resources/__tests__/ResourcesTab.test.tsx
@@ -22,8 +22,8 @@ import type { ComputeAllocationResource } from "../schemas";
let resources: ComputeAllocationResource[] = [];
const clusters: ComputeCluster[] = [
- { id: "cluster-anvil", name: "Anvil" },
- { id: "cluster-delta", name: "Delta" },
+ { id: "cluster-a", name: "ClusterA" },
+ { id: "cluster-b", name: "ClusterB" },
];
vi.mock("../queries", () => ({
@@ -47,18 +47,18 @@ import { ResourcesTab } from "../components/ResourcesTab";
beforeEach(() => {
resources = [
{
- id: "res-anvil-cpu",
- name: "Anvil CPU",
+ id: "res-a-cpu",
+ name: "ClusterA CPU",
resource_type: "CPU",
resource_amount: 1000,
- compute_cluster_id: "cluster-anvil",
+ compute_cluster_id: "cluster-a",
},
{
- id: "res-delta-gpu",
- name: "Delta GPU",
+ id: "res-b-gpu",
+ name: "ClusterB GPU",
resource_type: "GPU",
resource_amount: 200,
- compute_cluster_id: "cluster-delta",
+ compute_cluster_id: "cluster-b",
},
];
});
@@ -66,31 +66,31 @@ beforeEach(() => {
describe("<ResourcesTab />", () => {
it("resolves the cluster name as plain text, not a link", () => {
render(<ResourcesTab />);
- expect(screen.getByText("Anvil CPU")).toBeInTheDocument();
- expect(screen.getAllByText("Anvil", { exact: true }).length).toBeGreaterThan(0);
- expect(screen.queryByRole("link", { name: "Anvil" })).not.toBeInTheDocument();
+ expect(screen.getByText("ClusterA CPU")).toBeInTheDocument();
+ expect(screen.getAllByText("ClusterA", { exact: true }).length).toBeGreaterThan(0);
+ expect(screen.queryByRole("link", { name: "ClusterA" })).not.toBeInTheDocument();
});
it("filters by search text", () => {
render(<ResourcesTab />);
fireEvent.change(screen.getByLabelText("Search resources"), { target: { value: "gpu" } });
- expect(screen.queryByText("Anvil CPU")).not.toBeInTheDocument();
- expect(screen.getByText("Delta GPU")).toBeInTheDocument();
+ expect(screen.queryByText("ClusterA CPU")).not.toBeInTheDocument();
+ expect(screen.getByText("ClusterB GPU")).toBeInTheDocument();
});
it("filters by the selected cluster", () => {
render(<ResourcesTab />);
fireEvent.change(screen.getByLabelText("Filter by cluster"), {
- target: { value: "cluster-delta" },
+ target: { value: "cluster-b" },
});
- expect(screen.queryByText("Anvil CPU")).not.toBeInTheDocument();
- expect(screen.getByText("Delta GPU")).toBeInTheDocument();
+ expect(screen.queryByText("ClusterA CPU")).not.toBeInTheDocument();
+ expect(screen.getByText("ClusterB GPU")).toBeInTheDocument();
});
it("opens the rates drawer for the chosen resource", () => {
render(<ResourcesTab />);
fireEvent.click(screen.getAllByRole("button", { name: "Rates" })[0] as HTMLElement);
- expect(screen.getByText("rates-drawer:Anvil CPU")).toBeInTheDocument();
+ expect(screen.getByText("rates-drawer:ClusterA CPU")).toBeInTheDocument();
});
it("shows the empty state when no resources are registered", () => {
diff --git a/web/src/features/core/resources/__tests__/api.test.ts b/web/src/features/core/resources/__tests__/api.test.ts
index b877fce32..0f6c4f7e9 100644
--- a/web/src/features/core/resources/__tests__/api.test.ts
+++ b/web/src/features/core/resources/__tests__/api.test.ts
@@ -31,15 +31,15 @@ afterEach(() => {
});
const resource = {
- id: "res-anvil-cpu",
- name: "Anvil CPU",
+ id: "res-a-cpu",
+ name: "ClusterA CPU",
resource_type: "CPU",
resource_amount: 1000000,
- compute_cluster_id: "cluster-anvil",
+ compute_cluster_id: "cluster-a",
};
const rate = {
id: "rate-1",
- compute_allocation_resource_id: "res-anvil-cpu",
+ compute_allocation_resource_id: "res-a-cpu",
rate: 0.05,
start_time: "2020-01-01T00:00:00Z",
end_time: "2035-01-01T00:00:00Z",
@@ -49,22 +49,32 @@ describe("listResources", () => {
it("parses a bare array of resources", async () => {
fetchMock.mockResolvedValueOnce(mockResponse(200, [resource]));
const out = await listResources();
- expect(out[0]?.name).toBe("Anvil CPU");
+ expect(out[0]?.name).toBe("ClusterA CPU");
+ });
+
+ it("returns an empty array when the backend sends null", async () => {
+ fetchMock.mockResolvedValueOnce(mockResponse(200, "null"));
+ await expect(listResources()).resolves.toEqual([]);
});
});
describe("listResourceRates", () => {
it("parses a bare array of rates", async () => {
fetchMock.mockResolvedValueOnce(mockResponse(200, [rate]));
- const out = await listResourceRates("res-anvil-cpu");
+ const out = await listResourceRates("res-a-cpu");
expect(out[0]?.rate).toBe(0.05);
});
+
+ it("returns an empty array when the backend sends null", async () => {
+ fetchMock.mockResolvedValueOnce(mockResponse(200, "null"));
+ await expect(listResourceRates("res-a-cpu")).resolves.toEqual([]);
+ });
});
describe("getEffectiveRate", () => {
it("parses a single effective rate and appends the at query when given", async () => {
fetchMock.mockResolvedValueOnce(mockResponse(200, rate));
- await getEffectiveRate("res-anvil-cpu", "2026-06-01T00:00:00Z");
+ await getEffectiveRate("res-a-cpu", "2026-06-01T00:00:00Z");
const url = fetchMock.mock.calls[0]?.[0] as string;
expect(url).toContain("/rates/effective?at=");
});
diff --git a/web/src/features/core/resources/__tests__/queries.test.tsx b/web/src/features/core/resources/__tests__/queries.test.tsx
new file mode 100644
index 000000000..52eb1fb90
--- /dev/null
+++ b/web/src/features/core/resources/__tests__/queries.test.tsx
@@ -0,0 +1,57 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderHook, waitFor } from "@testing-library/react";
+import { http, HttpResponse } from "msw";
+import { setupServer } from "msw/node";
+import type { ReactNode } from "react";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { resourceKeys, useCreateResourceRate } from "../queries";
+
+const server = setupServer(
+ http.post("*/api/v1/compute-allocation-resource-rates", async ({ request }) => {
+ const body = (await request.json()) as Record<string, unknown>;
+ return HttpResponse.json({ id: "rate-new", ...body }, { status: 201 });
+ }),
+);
+
+beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
+afterAll(() => server.close());
+afterEach(() => server.resetHandlers());
+
+describe("useCreateResourceRate", () => {
+ it("invalidates the rates and effective queries for the resource on success", async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const invalidate = vi.spyOn(client, "invalidateQueries");
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+
+ const { result } = renderHook(() => useCreateResourceRate("res-1"), { wrapper });
+ await result.current.mutateAsync({
+ compute_allocation_resource_id: "res-1",
+ rate: 0.07,
+ start_time: "2026-06-01T00:00:00Z",
+ end_time: "2027-06-01T00:00:00Z",
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: resourceKeys.rates("res-1") });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: resourceKeys.effective("res-1") });
+ });
+});
diff --git a/web/src/features/core/resources/__tests__/schemas.test.ts b/web/src/features/core/resources/__tests__/schemas.test.ts
index 7d5035b4e..adfc086b5 100644
--- a/web/src/features/core/resources/__tests__/schemas.test.ts
+++ b/web/src/features/core/resources/__tests__/schemas.test.ts
@@ -22,18 +22,18 @@ describe("computeAllocationResourceSchema", () => {
it("accepts a fully populated resource", () => {
const parsed = computeAllocationResourceSchema.parse({
id: "res-1",
- name: "Anvil CPU",
+ name: "ClusterA CPU",
resource_type: "CPU",
resource_amount: 1000,
- compute_cluster_id: "cluster-anvil",
+ compute_cluster_id: "cluster-a",
});
- expect(parsed.name).toBe("Anvil CPU");
+ expect(parsed.name).toBe("ClusterA CPU");
});
it("rejects a resource missing its cluster id", () => {
const result = computeAllocationResourceSchema.safeParse({
id: "res-1",
- name: "Anvil CPU",
+ name: "ClusterA CPU",
resource_type: "CPU",
resource_amount: 1000,
});
diff --git a/web/src/features/core/resources/api.ts b/web/src/features/core/resources/api.ts
index a75773281..9d5c75510 100644
--- a/web/src/features/core/resources/api.ts
+++ b/web/src/features/core/resources/api.ts
@@ -24,14 +24,18 @@ import {
rateSchema,
} from "./schemas";
+// The backend serializes empty lists as JSON null (Go nil slice).
+const resourceListSchema = z.array(computeAllocationResourceSchema).nullable();
+const rateListSchema = z.array(rateSchema).nullable();
+
export async function listResources(): Promise<ComputeAllocationResource[]> {
const raw = await apiFetch("/compute-allocation-resources");
- return z.array(computeAllocationResourceSchema).parse(raw);
+ return resourceListSchema.parse(raw) ?? [];
}
export async function listResourceRates(id: string): Promise<Rate[]> {
const raw = await apiFetch(`/compute-allocation-resources/${id}/rates`);
- return z.array(rateSchema).parse(raw);
+ return rateListSchema.parse(raw) ?? [];
}
export async function getEffectiveRate(id: string, at?: string): Promise<Rate> {
@@ -39,3 +43,18 @@ export async function getEffectiveRate(id: string, at?: string): Promise<Rate> {
const raw = await apiFetch(`/compute-allocation-resources/${id}/rates/effective${qs}`);
return rateSchema.parse(raw);
}
+
+export type CreateResourceRatePayload = {
+ compute_allocation_resource_id: string;
+ rate: number;
+ start_time: string;
+ end_time: string;
+};
+
+export async function createResourceRate(payload: CreateResourceRatePayload): Promise<Rate> {
+ const raw = await apiFetch("/compute-allocation-resource-rates", {
+ method: "POST",
+ body: payload,
+ });
+ return rateSchema.parse(raw);
+}
diff --git a/web/src/features/core/resources/components/ResourcesRatesDrawer.tsx b/web/src/features/core/resources/components/ResourcesRatesDrawer.tsx
index 5ec208e80..e1fee46a3 100644
--- a/web/src/features/core/resources/components/ResourcesRatesDrawer.tsx
+++ b/web/src/features/core/resources/components/ResourcesRatesDrawer.tsx
@@ -17,13 +17,28 @@
"use client";
+import { zodResolver } from "@hookform/resolvers/zod";
+import * as React from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { useAbility } from "@/shared/casl/AbilityProvider";
+import { Button } from "@/shared/ui/button";
import { EmptyState } from "@/shared/ui/EmptyState";
import { ErrorState } from "@/shared/ui/ErrorState";
+import { Input } from "@/shared/ui/input";
+import { Label } from "@/shared/ui/label";
import { CardSkeleton } from "@/shared/ui/Loading";
import { SideDrawer } from "@/shared/ui/SideDrawer";
-import { StatusBadge } from "@/shared/ui/StatusBadge";
-import { useEffectiveRate, useResourceRates } from "../queries";
-import { isRateActive, type Rate } from "../schemas";
+import { StatusBadge, type StatusBadgeVariant } from "@/shared/ui/StatusBadge";
+import { useCreateResourceRate, useEffectiveRate, useResourceRates } from "../queries";
+import { classifyRate, createRateSchema, type CreateRateForm, type Rate, type RateStatus } from "../schemas";
+
+const STATUS_VARIANT: Record<RateStatus, StatusBadgeVariant> = {
+ ACTIVE: "active",
+ SCHEDULED: "pending",
+ SUPERSEDED: "inactive",
+ EXPIRED: "expired",
+};
function formatDate(iso: string): string {
try {
@@ -37,6 +52,21 @@ function formatDate(iso: string): string {
}
}
+function todayUtc(): string {
+ return new Date().toISOString().slice(0, 10);
+}
+
+function defaultForm(): CreateRateForm {
+ const start = todayUtc();
+ const end = new Date(start);
+ end.setUTCFullYear(end.getUTCFullYear() + 1);
+ return {
+ rate: undefined as unknown as number,
+ start_date: start,
+ end_date: end.toISOString().slice(0, 10),
+ };
+}
+
export type ResourcesRatesDrawerProps = {
resourceId: string | null;
resourceName: string | null;
@@ -48,9 +78,61 @@ export function ResourcesRatesDrawer({
resourceName,
onOpenChange,
}: ResourcesRatesDrawerProps) {
+ const ability = useAbility();
+ const canManage = ability.can("manage", "Allocation");
+
const rates = useResourceRates(resourceId ?? undefined);
const effective = useEffectiveRate(resourceId ?? undefined);
- const history = rates.data ?? [];
+ const createMutation = useCreateResourceRate(resourceId ?? "");
+
+ const history = React.useMemo(
+ () => [...(rates.data ?? [])].sort((a, b) => Date.parse(b.start_time) - Date.parse(a.start_time)),
+ [rates.data],
+ );
+
+ const [formOpen, setFormOpen] = React.useState(false);
+ const [submitError, setSubmitError] = React.useState<string | null>(null);
+ const form = useForm<CreateRateForm>({
+ resolver: zodResolver(createRateSchema),
+ defaultValues: defaultForm(),
+ mode: "onBlur",
+ });
+
+ function openForm() {
+ form.reset(defaultForm());
+ setSubmitError(null);
+ setFormOpen(true);
+ }
+
+ const startDate = form.watch("start_date");
+ const endDate = form.watch("end_date");
+ const isImmediate = startDate === todayUtc();
+ const currentRate = effective.data?.rate;
+ // Backend forces an end date, so warn when nothing starts at or after it.
+ const leavesGap = Boolean(endDate) && !history.some((r) => Date.parse(r.start_time) >= Date.parse(`${endDate}T00:00:00Z`));
+
+ const onSubmit = form.handleSubmit(async (values) => {
+ if (!resourceId) return;
+ const start_time = values.start_date === todayUtc()
+ ? new Date().toISOString()
+ : `${values.start_date}T00:00:00Z`;
+ try {
+ await createMutation.mutateAsync({
+ compute_allocation_resource_id: resourceId,
+ rate: values.rate,
+ start_time,
+ end_time: `${values.end_date}T00:00:00Z`,
+ });
+ toast.success("Rate added.");
+ form.reset(defaultForm());
+ setSubmitError(null);
+ setFormOpen(false);
+ } catch (err) {
+ setSubmitError(err instanceof Error ? err.message : "Failed to add rate");
+ }
+ });
+
+ const errors = form.formState.errors;
return (
<SideDrawer
@@ -74,12 +156,100 @@ export function ResourcesRatesDrawer({
</div>
) : null}
+ {canManage && history.length > 0 ? (
+ <div className="mb-4 flex items-start justify-between gap-4">
+ <p className="text-xs text-muted-foreground">
+ Rates can't be edited. Adding a rate supersedes the current one from its effective
+ date.
+ </p>
+ {!formOpen ? (
+ <Button variant="outline" size="sm" className="shrink-0" onClick={openForm}>
+ + Add rate
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
+
+ {canManage && formOpen ? (
+ <form onSubmit={onSubmit} aria-label="Add rate form" className="mb-6 space-y-4 rounded-lg border border-border bg-card p-4">
+ <div className="space-y-2">
+ <Label htmlFor="rate-value">Rate</Label>
+ <Input
+ id="rate-value"
+ type="number"
+ step="0.01"
+ placeholder="e.g. 0.05"
+ {...form.register("rate", { valueAsNumber: true })}
+ />
+ {errors.rate?.message ? (
+ <p className="text-xs text-destructive">{errors.rate.message}</p>
+ ) : null}
+ </div>
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-2">
+ <Label htmlFor="rate-start">Effective date</Label>
+ <Input id="rate-start" type="date" {...form.register("start_date")} />
+ {errors.start_date?.message ? (
+ <p className="text-xs text-destructive">{errors.start_date.message}</p>
+ ) : null}
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="rate-end">Ends</Label>
+ <Input id="rate-end" type="date" {...form.register("end_date")} />
+ {errors.end_date?.message ? (
+ <p className="text-xs text-destructive">{errors.end_date.message}</p>
+ ) : null}
+ </div>
+ </div>
+
+ <p className="text-xs text-muted-foreground">
+ {isImmediate
+ ? `This becomes the active rate immediately. Current rate (${currentRate ?? "none"}) stays in history.`
+ : `Scheduled to take effect on ${formatDate(`${startDate}T00:00:00Z`)}. The current rate (${currentRate ?? "none"}) stays active until then.`}
+ </p>
+
+ {leavesGap ? (
+ <p className="text-xs text-[color:var(--custos-amber-700)]">
+ No rate is effective after {formatDate(`${endDate}T00:00:00Z`)}. Add a follow-up rate to
+ avoid a pricing gap.
+ </p>
+ ) : null}
+
+ {submitError ? <p className="text-sm text-destructive">{submitError}</p> : null}
+
+ <div className="flex items-center justify-end gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => {
+ setFormOpen(false);
+ setSubmitError(null);
+ }}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={createMutation.isPending}>
+ {createMutation.isPending ? "Adding…" : "Add rate"}
+ </Button>
+ </div>
+ </form>
+ ) : null}
+
{rates.isLoading ? (
<CardSkeleton />
) : rates.error ? (
<ErrorState message={(rates.error as Error).message} onRetry={() => rates.refetch()} />
) : history.length === 0 ? (
- <EmptyState heading="No rates recorded for this resource." />
+ <EmptyState
+ heading="No rates recorded for this resource."
+ cta={
+ canManage && !formOpen ? (
+ <Button variant="outline" size="sm" onClick={openForm}>
+ + Add rate
+ </Button>
+ ) : undefined
+ }
+ />
) : (
<table className="w-full text-left text-sm">
<thead className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
@@ -91,20 +261,19 @@ export function ResourcesRatesDrawer({
</tr>
</thead>
<tbody>
- {history.map((rate: Rate) => (
- <tr key={rate.id} className="border-t border-border/60">
- <td className="py-2 pr-4 font-medium text-foreground">{rate.rate}</td>
- <td className="py-2 pr-4 text-muted-foreground">{formatDate(rate.start_time)}</td>
- <td className="py-2 pr-4 text-muted-foreground">{formatDate(rate.end_time)}</td>
- <td className="py-2">
- {isRateActive(rate) ? (
- <StatusBadge variant="active" label="ACTIVE" />
- ) : (
- <StatusBadge variant="expired" label="EXPIRED" />
- )}
- </td>
- </tr>
- ))}
+ {history.map((rate: Rate) => {
+ const status = classifyRate(rate, history);
+ return (
+ <tr key={rate.id} className="border-t border-border/60">
+ <td className="py-2 pr-4 font-medium text-foreground">{rate.rate}</td>
+ <td className="py-2 pr-4 text-muted-foreground">{formatDate(rate.start_time)}</td>
+ <td className="py-2 pr-4 text-muted-foreground">{formatDate(rate.end_time)}</td>
+ <td className="py-2">
+ <StatusBadge variant={STATUS_VARIANT[status]} label={status} />
+ </td>
+ </tr>
+ );
+ })}
</tbody>
</table>
)}
diff --git a/web/src/features/core/resources/queries.ts b/web/src/features/core/resources/queries.ts
index fab27aae7..607008450 100644
--- a/web/src/features/core/resources/queries.ts
+++ b/web/src/features/core/resources/queries.ts
@@ -17,8 +17,8 @@
"use client";
-import { useQuery } from "@tanstack/react-query";
-import { getEffectiveRate, listResourceRates, listResources } from "./api";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { createResourceRate, getEffectiveRate, listResourceRates, listResources } from "./api";
export const resourceKeys = {
all: ["resources"] as const,
@@ -59,3 +59,14 @@ export function useEffectiveRate(id: string | undefined) {
...DEFAULTS,
});
}
+
+export function useCreateResourceRate(resourceId: string) {
+ const client = useQueryClient();
+ return useMutation({
+ mutationFn: createResourceRate,
+ onSuccess: () => {
+ client.invalidateQueries({ queryKey: resourceKeys.rates(resourceId) });
+ client.invalidateQueries({ queryKey: resourceKeys.effective(resourceId) });
+ },
+ });
+}
diff --git a/web/src/features/core/resources/schemas.ts b/web/src/features/core/resources/schemas.ts
index ae1312adc..12f288feb 100644
--- a/web/src/features/core/resources/schemas.ts
+++ b/web/src/features/core/resources/schemas.ts
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-import type { z } from "zod";
+import { z } from "zod";
import {
zComputeAllocationResource,
zComputeAllocationResourceRate,
@@ -48,3 +48,32 @@ export function isRateActive(rate: Rate, at: Date = new Date()): boolean {
const now = at.getTime();
return now >= start && now < end;
}
+
+export type RateStatus = "ACTIVE" | "SCHEDULED" | "SUPERSEDED" | "EXPIRED";
+
+// Effective = the containing window with the latest start_time, mirroring the
+// backend ORDER BY start_time DESC. Overlaps resolve to SUPERSEDED, not errors.
+export function classifyRate(rate: Rate, all: Rate[], now: number = Date.now()): RateStatus {
+ const start = Date.parse(rate.start_time);
+ const end = Date.parse(rate.end_time);
+ if (start > now) return "SCHEDULED";
+ if (end <= now) return "EXPIRED";
+ const effectiveStart = Math.max(
+ ...all
+ .filter((r) => Date.parse(r.start_time) <= now && Date.parse(r.end_time) > now)
+ .map((r) => Date.parse(r.start_time)),
+ );
+ return start === effectiveStart ? "ACTIVE" : "SUPERSEDED";
+}
+
+export const createRateSchema = z
+ .object({
+ rate: z.number({ message: "Rate is required" }).min(0, "Rate must be zero or greater"),
+ start_date: z.string().min(1, "Start date is required"),
+ end_date: z.string().min(1, "End date is required"),
+ })
+ .refine((d) => d.end_date > d.start_date, {
+ path: ["end_date"],
+ message: "End date must be after the start date",
+ });
+export type CreateRateForm = z.infer<typeof createRateSchema>;
diff --git a/web/src/mocks/handlers/resources.ts b/web/src/mocks/handlers/resources.ts
index d568f3036..3df4bdc6d 100644
--- a/web/src/mocks/handlers/resources.ts
+++ b/web/src/mocks/handlers/resources.ts
@@ -45,4 +45,17 @@ export const resourcesHandlers = [
const id = String(params.id);
return HttpResponse.json(ratesFor(id));
}),
+
+ http.post("*/api/v1/compute-allocation-resource-rates", async ({ request }) => {
+ const body = (await request.json()) as Partial<Rate>;
+ const created: Rate = {
+ id: `rate-${Date.now()}`,
+ compute_allocation_resource_id: String(body.compute_allocation_resource_id),
+ rate: Number(body.rate),
+ start_time: String(body.start_time),
+ end_time: String(body.end_time),
+ };
+ rates.push(created);
+ return HttpResponse.json(created, { status: 201 });
+ }),
];
diff --git a/web/tests/admin-read-only.e2e.ts b/web/tests/admin-read-only.e2e.ts
index 3d96e7956..1ecedf282 100644
--- a/web/tests/admin-read-only.e2e.ts
+++ b/web/tests/admin-read-only.e2e.ts
@@ -27,8 +27,8 @@ test.describe("admin resources & clusters read-only sweep", () => {
});
// Clusters is the default tab.
- await page.getByRole("button", { name: "Anvil", exact: true }).click();
- await expect(page.getByText("Cluster: Anvil")).toBeVisible({ timeout: 15_000 });
+ await page.getByRole("button", { name: "ClusterA", exact: true }).click();
+ await expect(page.getByText("Cluster: ClusterA")).toBeVisible({ timeout: 15_000 });
await expect(page.getByText("ghopper")).toBeVisible();
});
@@ -41,13 +41,38 @@ test.describe("admin resources & clusters read-only sweep", () => {
await page.getByRole("tab", { name: /^resources$/i }).click();
await page
- .getByRole("row", { name: /Anvil CPU/ })
+ .getByRole("row", { name: /ClusterA CPU/ })
.getByRole("button", { name: "Rates" })
.click();
- await expect(page.getByText("Rates: Anvil CPU")).toBeVisible({ timeout: 15_000 });
+ await expect(page.getByText("Rates: ClusterA CPU")).toBeVisible({ timeout: 15_000 });
// History carries the current rate plus the superseded one (client-derived).
await expect(page.getByText("EXPIRED")).toBeVisible();
await expect(page.getByText("0.04")).toBeVisible();
});
+
+ test("admin adds a rate that becomes active and supersedes the current one", async ({ page }) => {
+ await signInAs(page, "admin");
+ await page.goto("/admin/resources");
+ await expect(page.getByRole("heading", { name: /Resources & Clusters/ })).toBeVisible({
+ timeout: 20_000,
+ });
+
+ await page.getByRole("tab", { name: /^resources$/i }).click();
+ await page
+ .getByRole("row", { name: /ClusterA GPU/ })
+ .getByRole("button", { name: "Rates" })
+ .click();
+ await expect(page.getByText("Rates: ClusterA GPU")).toBeVisible({ timeout: 15_000 });
+
+ await page.getByRole("button", { name: "+ Add rate" }).click();
+ await page.getByLabel("Rate", { exact: true }).fill("0.77");
+ await page.getByRole("button", { name: "Add rate" }).click();
+
+ await expect(page.getByText("Rate added.")).toBeVisible({ timeout: 15_000 });
+ const newRow = page.getByRole("row", { name: /0\.77/ });
+ await expect(newRow.getByText("ACTIVE")).toBeVisible();
+ // The former current rate stays in its window but loses the tie-break.
+ await expect(page.getByText("SUPERSEDED")).toBeVisible();
+ });
});
diff --git a/web/tests/admin-viewer.e2e.ts b/web/tests/admin-viewer.e2e.ts
index e301986a3..ede635356 100644
--- a/web/tests/admin-viewer.e2e.ts
+++ b/web/tests/admin-viewer.e2e.ts
@@ -41,5 +41,14 @@ test.describe("admin viewer persona", () => {
await expect(page.getByRole("heading", { name: /Resources & Clusters/ })).toBeVisible();
await expect(page.getByRole("tab", { name: /^clusters$/i })).toBeVisible();
await expect(page.getByRole("tab", { name: /^resources$/i })).toBeVisible();
+
+ // Viewer lacks manage Allocation, so the rates drawer offers no create action.
+ await page.getByRole("tab", { name: /^resources$/i }).click();
+ await page
+ .getByRole("row", { name: /ClusterA CPU/ })
+ .getByRole("button", { name: "Rates" })
+ .click();
+ await expect(page.getByText("Rates: ClusterA CPU")).toBeVisible({ timeout: 15_000 });
+ await expect(page.getByRole("button", { name: "+ Add rate" })).toHaveCount(0);
});
});