This is an automated email from the ASF dual-hosted git repository. yasithdev pushed a commit to branch web-projects-consolidate in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit d9a834f1501455d0fc4cfe8f68209d330ece2758 Author: Yasith Jayawardana <[email protected]> AuthorDate: Fri Nov 6 13:07:48 2026 -0500 Merge allocations into project cards --- .../allocations/AllocationsListContainer.tsx | 82 ------ .../(portal)/allocations/[allocationId]/page.tsx | 19 +- web/src/app/(portal)/allocations/layout.tsx | 23 -- web/src/app/(portal)/allocations/page.tsx | 4 +- web/src/app/(portal)/page.tsx | 2 +- .../(portal)/projects/ProjectsListContainer.tsx | 1 + .../[projectId]}/[allocationId]/page.tsx | 0 .../allocations/__tests__/AllocationList.test.tsx | 61 +++++ .../allocations/__tests__/AllocationsList.test.tsx | 128 ---------- .../allocations/components/AddAllocationButton.tsx | 111 ++++++++ .../allocations/components/AllocationDetail.tsx | 5 +- .../allocations/components/AllocationFields.tsx | 141 +++++++++++ .../core/allocations/components/AllocationList.tsx | 73 ++++++ .../allocations/components/AllocationsList.tsx | 278 --------------------- .../components/CreateAllocationDialog.tsx | 212 ---------------- .../__tests__/CreateProjectDialog.test.tsx | 89 +++++++ .../core/projects/__tests__/ProjectsList.test.tsx | 19 +- .../projects/components/CreateProjectDialog.tsx | 215 ++++++++++++---- .../core/projects/components/ProjectCard.tsx | 87 +++++++ .../core/projects/components/ProjectDetail.tsx | 22 +- .../projects/components/ProjectGroupHeader.tsx | 48 ---- .../core/projects/components/ProjectMembersTab.tsx | 2 +- .../projects/components/ProjectOverviewTab.tsx | 44 +--- .../core/projects/components/ProjectStatusIcon.tsx | 26 -- .../core/projects/components/ProjectsList.tsx | 76 ++---- web/src/mocks/handlers/allocations.ts | 36 +++ web/src/mocks/handlers/resources.ts | 2 +- web/src/shared/hooks/useShallowSearchParams.ts | 9 +- web/src/shared/layout/Sidebar.tsx | 42 +++- web/src/shared/layout/__tests__/Sidebar.test.tsx | 1 + web/src/shared/layout/nav.ts | 25 +- web/tests/agreement-gates.e2e.ts | 4 +- web/tests/allocation-members-edit.e2e.ts | 2 +- web/tests/allocations-detail.e2e.ts | 3 +- web/tests/allocations-list.e2e.ts | 61 ----- web/tests/baseline-live.spec.ts | 12 +- web/tests/change-requests-submit.e2e.ts | 2 +- web/tests/closeout-live-walk.spec.ts | 6 - web/tests/projects-list.e2e.ts | 11 + 39 files changed, 918 insertions(+), 1066 deletions(-) diff --git a/web/src/app/(portal)/allocations/AllocationsListContainer.tsx b/web/src/app/(portal)/allocations/AllocationsListContainer.tsx deleted file mode 100644 index a0d09ab3c..000000000 --- a/web/src/app/(portal)/allocations/AllocationsListContainer.tsx +++ /dev/null @@ -1,82 +0,0 @@ -// 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. - -"use client"; - -import { AllocationsList } from "@/features/core/allocations/components/AllocationsList"; -import { CreateAllocationDialog } from "@/features/core/allocations/components/CreateAllocationDialog"; -import { useAllocations } from "@/features/core/allocations/queries"; -import type { AllocationStatus } from "@/generated/core/zod.gen"; -import { requires, usePermissions } from "@/shared/casl/permissions"; -import { - replaceShallowSearchParams, - useShallowSearchParams, -} from "@/shared/hooks/useShallowSearchParams"; -import { GuardedButton } from "@/shared/ui/GuardedButton"; -import * as React from "react"; - -function statusFilterFromUrl(raw: string | null): AllocationStatus | "all" { - if (raw === "ACTIVE" || raw === "INACTIVE" || raw === "DELETED") return raw; - return "all"; -} - -export function AllocationsListContainer() { - const can = usePermissions(); - const searchParams = useShallowSearchParams(); - const search = searchParams.get("q") ?? ""; - const statusFilter = statusFilterFromUrl(searchParams.get("status")); - - const updateParam = React.useCallback( - (key: string, value: string | null) => { - const params = new URLSearchParams(searchParams.toString()); - if (!value) params.delete(key); - else params.set(key, value); - replaceShallowSearchParams(params); - }, - [searchParams], - ); - - const query = useAllocations({}); - const rows = query.data?.items ?? []; - const [creating, setCreating] = React.useState(false); - - return ( - <AllocationsList - rows={rows} - isLoading={query.isLoading} - error={query.error} - onRetry={() => query.refetch()} - search={search} - onSearchChange={(next) => updateParam("q", next)} - statusFilter={statusFilter} - onStatusFilterChange={(next) => updateParam("status", next === "all" ? null : next)} - canEditResources={can.allocationsWrite} - headerCta={ - <> - <GuardedButton - allowed={can.allocationsWrite && can.clustersRead} - reason={requires("allocationsWrite", "clustersRead")} - onClick={() => setCreating(true)} - > - + Add allocation - </GuardedButton> - {creating ? <CreateAllocationDialog onOpenChange={setCreating} /> : null} - </> - } - /> - ); -} diff --git a/web/src/app/(portal)/allocations/[allocationId]/page.tsx b/web/src/app/(portal)/allocations/[allocationId]/page.tsx index 2d234bdf7..26982a05f 100644 --- a/web/src/app/(portal)/allocations/[allocationId]/page.tsx +++ b/web/src/app/(portal)/allocations/[allocationId]/page.tsx @@ -15,11 +15,22 @@ // specific language governing permissions and limitations // under the License. -import { AllocationDetail } from "@/features/core/allocations/components/AllocationDetail"; +"use client"; -export default async function AllocationDetailPage(props: { +import { useAllocation } from "@/features/core/allocations/queries"; +import { ErrorState } from "@/shared/ui/ErrorState"; +import { useRouter } from "next/navigation"; +import * as React from "react"; + +// Allocation pages live under their project; links that know only the allocation id land here. +export default function AllocationRedirectPage(props: { params: Promise<{ allocationId: string }>; }) { - const { allocationId } = await props.params; - return <AllocationDetail allocationId={allocationId} />; + const { allocationId } = React.use(props.params); + const { data, error, refetch } = useAllocation(allocationId); + const router = useRouter(); + React.useEffect(() => { + if (data) router.replace(`/projects/${data.project_id}/${data.id}`); + }, [data, router]); + return error ? <ErrorState message={error.message} onRetry={() => refetch()} /> : null; } diff --git a/web/src/app/(portal)/allocations/layout.tsx b/web/src/app/(portal)/allocations/layout.tsx deleted file mode 100644 index c49bcb507..000000000 --- a/web/src/app/(portal)/allocations/layout.tsx +++ /dev/null @@ -1,23 +0,0 @@ -// 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 type { ReactNode } from "react"; - -// No gate: the backend scopes these reads to the caller's memberships. -export default function AllocationsLayout({ children }: { children: ReactNode }) { - return <>{children}</>; -} diff --git a/web/src/app/(portal)/allocations/page.tsx b/web/src/app/(portal)/allocations/page.tsx index 5e93babe1..e14c210b9 100644 --- a/web/src/app/(portal)/allocations/page.tsx +++ b/web/src/app/(portal)/allocations/page.tsx @@ -15,8 +15,8 @@ // specific language governing permissions and limitations // under the License. -import { AllocationsListContainer } from "./AllocationsListContainer"; +import { redirect } from "next/navigation"; export default function AllocationsPage() { - return <AllocationsListContainer />; + redirect("/projects"); } diff --git a/web/src/app/(portal)/page.tsx b/web/src/app/(portal)/page.tsx index 18adf34e4..3e677b89d 100644 --- a/web/src/app/(portal)/page.tsx +++ b/web/src/app/(portal)/page.tsx @@ -18,5 +18,5 @@ import { redirect } from "next/navigation"; export default function PortalLandingPage() { - redirect("/allocations"); + redirect("/projects"); } diff --git a/web/src/app/(portal)/projects/ProjectsListContainer.tsx b/web/src/app/(portal)/projects/ProjectsListContainer.tsx index 070ed3c58..c1352d471 100644 --- a/web/src/app/(portal)/projects/ProjectsListContainer.tsx +++ b/web/src/app/(portal)/projects/ProjectsListContainer.tsx @@ -63,6 +63,7 @@ export function ProjectsListContainer() { search={search} onSearchChange={(next) => updateParam("q", next)} statusFilter={statusFilter} + origination={searchParams.get("origination")} onStatusFilterChange={(next) => updateParam("status", next === "all" ? null : next)} headerCta={ <> diff --git a/web/src/app/(portal)/allocations/[allocationId]/page.tsx b/web/src/app/(portal)/projects/[projectId]/[allocationId]/page.tsx similarity index 100% copy from web/src/app/(portal)/allocations/[allocationId]/page.tsx copy to web/src/app/(portal)/projects/[projectId]/[allocationId]/page.tsx diff --git a/web/src/features/core/allocations/__tests__/AllocationList.test.tsx b/web/src/features/core/allocations/__tests__/AllocationList.test.tsx new file mode 100644 index 000000000..46eb5c823 --- /dev/null +++ b/web/src/features/core/allocations/__tests__/AllocationList.test.tsx @@ -0,0 +1,61 @@ +// 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 type { ComputeAllocation } from "@/generated/core/zod.gen"; +import { render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +const allocation: ComputeAllocation = { + id: "alloc-001", + project_id: "project-001", + name: "Genomic GPU Pool", + status: "ACTIVE", + compute_cluster_id: "cluster-a", + initial_su_amount: 250000, + start_time: "2026-04-01T00:00:00.000Z", + end_time: "2027-03-31T00:00:00.000Z", + posix_group: null, + group_provisioned_at: null, +}; + +vi.mock("../queries", () => ({ + useAllocationsByProject: () => ({ data: { items: [allocation], total: 1 } }), + useAllocationUsedSU: () => ({ data: 50000 }), +})); +vi.mock("@/shared/casl/permissions", async (importOriginal) => ({ + ...(await importOriginal<typeof import("@/shared/casl/permissions")>()), + usePermissions: () => ({}), +})); + +import { AllocationList } from "../components/AllocationList"; + +const project = { + id: "project-001", + title: "Genomic Sequencing Pipeline", + ref: "ACCESS-BIO130000", +}; + +describe("<AllocationList />", () => { + it("links each allocation under its project with the SUs left", () => { + render(<AllocationList project={project} />); + expect(screen.getByRole("link", { name: allocation.name })).toHaveAttribute( + "href", + `/projects/${allocation.project_id}/${allocation.id}`, + ); + expect(screen.getByText("200,000")).toBeInTheDocument(); + }); +}); diff --git a/web/src/features/core/allocations/__tests__/AllocationsList.test.tsx b/web/src/features/core/allocations/__tests__/AllocationsList.test.tsx deleted file mode 100644 index 34a88c135..000000000 --- a/web/src/features/core/allocations/__tests__/AllocationsList.test.tsx +++ /dev/null @@ -1,128 +0,0 @@ -// 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 projects from "@/features/core/projects/__fixtures__/projects.json"; -import type { ComputeAllocation } from "@/generated/core/zod.gen"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { render, screen } from "@testing-library/react"; -import { http, HttpResponse } from "msw"; -import { setupServer } from "msw/node"; -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; -import { AllocationsList } from "../components/AllocationsList"; - -vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) })); - -const allocation: ComputeAllocation = { - id: "alloc-001", - project_id: "project-001", - name: "Genomic GPU Pool", - status: "ACTIVE", - compute_cluster_id: "cluster-a", - initial_su_amount: 250000, - start_time: "2026-04-01T00:00:00.000Z", - end_time: "2027-03-31T00:00:00.000Z", - posix_group: null, - group_provisioned_at: null, -}; - -function renderList(overrides: Partial<React.ComponentProps<typeof AllocationsList>> = {}) { - const props = { - rows: [allocation], - isLoading: false, - error: null, - search: "", - onSearchChange: vi.fn(), - statusFilter: "all" as const, - onStatusFilterChange: vi.fn(), - canEditResources: false, - ...overrides, - }; - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - return { - ...render( - <QueryClientProvider client={client}> - <AllocationsList {...props} /> - </QueryClientProvider>, - ), - props, - }; -} - -const server = setupServer( - http.get<{ id: string }>("*/api/v1/projects/:id", ({ params }) => - HttpResponse.json(projects.find((p) => p.id === params.id)), - ), - http.get("*/api/v1/compute-allocations/:id/usages/total", () => - HttpResponse.json({ compute_allocation_id: "alloc-001", total_su_amount: 50000 }), - ), - http.get("*/api/v1/compute-allocations/:id/resources", () => - HttpResponse.json([ - { - id: "res-a", - name: "gpu-a100", - resource_type: "gres/gpu", - resource_amount: 8, - compute_cluster_id: "cluster-a", - }, - ]), - ), -); - -beforeAll(() => server.listen({ onUnhandledRequest: "error" })); -afterAll(() => server.close()); -afterEach(() => server.resetHandlers()); - -describe("<AllocationsList />", () => { - it("renders the allocation name as a link to the detail page", () => { - renderList(); - const link = screen.getByRole("link", { name: allocation.name }); - expect(link).toHaveAttribute("href", `/allocations/${allocation.id}`); - }); - - it("groups rows under a project header with the allocation's resources and remaining SUs", async () => { - renderList(); - expect(await screen.findByRole("link", { name: /Go to project/ })).toHaveAttribute( - "href", - `/projects/${allocation.project_id}`, - ); - expect(await screen.findByText("gpu-a100")).toBeInTheDocument(); - expect(await screen.findByText("200,000")).toBeInTheDocument(); - }); - - it("shows the empty state when no rows match the filters", () => { - renderList({ rows: [] }); - expect(screen.getByText("No allocations match the current filters.")).toBeInTheDocument(); - }); - - it("filters by status", () => { - const inactive: ComputeAllocation = { - ...allocation, - id: "alloc-002", - name: "Legacy Pool", - status: "INACTIVE", - }; - renderList({ rows: [allocation, inactive], statusFilter: "INACTIVE" }); - expect(screen.queryByRole("link", { name: allocation.name })).not.toBeInTheDocument(); - expect(screen.getByRole("link", { name: inactive.name })).toBeInTheDocument(); - }); - - it("surfaces an error state with a retry callback", () => { - const onRetry = vi.fn(); - renderList({ error: new Error("boom"), onRetry }); - expect(screen.getByText(/boom/)).toBeInTheDocument(); - }); -}); diff --git a/web/src/features/core/allocations/components/AddAllocationButton.tsx b/web/src/features/core/allocations/components/AddAllocationButton.tsx new file mode 100644 index 000000000..f72699955 --- /dev/null +++ b/web/src/features/core/allocations/components/AddAllocationButton.tsx @@ -0,0 +1,111 @@ +// 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. + +"use client"; + +import type { ProjectResponse } from "@/generated/core/zod.gen"; +import { requires, usePermissions } from "@/shared/casl/permissions"; +import { GuardedButton } from "@/shared/ui/GuardedButton"; +import { Button } from "@/shared/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/shared/ui/dialog"; +import * as React from "react"; +import { toast } from "sonner"; +import { useCreateAllocation } from "../queries"; +import { + AllocationFields, + draftPayload, + emptyAllocationDraft, + isDraftReady, +} from "./AllocationFields"; + +type Project = Pick<ProjectResponse, "id" | "title" | "ref">; + +// "Add allocation" link that opens the create dialog for one project. +export function AddAllocationButton({ project }: { project: Project }) { + const can = usePermissions(); + const [open, setOpen] = React.useState(false); + return ( + <> + <GuardedButton + variant="link" + className="h-auto border-0 p-0" + allowed={can.allocationsWrite && can.clustersRead} + reason={requires("allocationsWrite", "clustersRead")} + onClick={() => setOpen(true)} + > + Add allocation + </GuardedButton> + {open ? <CreateAllocationDialog onOpenChange={setOpen} project={project} /> : null} + </> + ); +} + +function CreateAllocationDialog({ + onOpenChange, + project, +}: { + onOpenChange: (open: boolean) => void; + project: Project; +}) { + const create = useCreateAllocation(); + const [draft, setDraft] = React.useState(emptyAllocationDraft); + const ready = isDraftReady(draft); + + return ( + <Dialog open onOpenChange={onOpenChange}> + <DialogContent> + <DialogHeader> + <DialogTitle>Add allocation</DialogTitle> + <DialogDescription> + Grant {project.ref}: {project.title} compute time on a cluster. + </DialogDescription> + </DialogHeader> + <form + className="space-y-4" + onSubmit={(e) => { + e.preventDefault(); + if (!ready) return; + create.mutate(draftPayload(project.id, draft), { + onSuccess: (created) => { + toast.success(`Allocation ${created.name} created.`); + onOpenChange(false); + }, + }); + }} + > + <AllocationFields value={draft} onChange={setDraft} /> + {create.error ? <p className="text-destructive text-sm">{create.error.message}</p> : null} + <DialogFooter> + <Button type="button" variant="outline" onClick={() => onOpenChange(false)}> + Cancel + </Button> + <Button type="submit" disabled={create.isPending || !ready}> + {create.isPending ? "Creating…" : "Add allocation"} + </Button> + </DialogFooter> + </form> + </DialogContent> + </Dialog> + ); +} diff --git a/web/src/features/core/allocations/components/AllocationDetail.tsx b/web/src/features/core/allocations/components/AllocationDetail.tsx index 2b8e8bcc5..a351d9e45 100644 --- a/web/src/features/core/allocations/components/AllocationDetail.tsx +++ b/web/src/features/core/allocations/components/AllocationDetail.tsx @@ -17,6 +17,7 @@ "use client"; +import { useProject } from "@/features/core/projects/queries"; import { requires, usePermissions } from "@/shared/casl/permissions"; import { useBreadcrumbLabel } from "@/shared/layout/BreadcrumbLabelsProvider"; import { DeleteButton } from "@/shared/ui/ConfirmDialog"; @@ -42,6 +43,8 @@ export function AllocationDetail({ allocationId }: AllocationDetailProps) { const allocationQuery = useAllocation(allocationId); const membersQuery = useAllocationMembers(allocationId); const remove = useDeleteAllocation(); + const projectId = allocationQuery.data?.project_id; + useBreadcrumbLabel(projectId, useProject(projectId).data?.title); useBreadcrumbLabel(allocationId, allocationQuery.data?.name); if (allocationQuery.isLoading) return <CardSkeleton />; @@ -67,7 +70,7 @@ export function AllocationDetail({ allocationId }: AllocationDetailProps) { id={allocation.id} name={allocation.name} mutation={remove} - redirectTo="/allocations" + redirectTo={`/projects/${allocation.project_id}`} allowed={can.allocationsWrite} reason={requires("allocationsWrite")} > diff --git a/web/src/features/core/allocations/components/AllocationFields.tsx b/web/src/features/core/allocations/components/AllocationFields.tsx new file mode 100644 index 000000000..c95dd98cc --- /dev/null +++ b/web/src/features/core/allocations/components/AllocationFields.tsx @@ -0,0 +1,141 @@ +// 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. + +"use client"; + +import { useClusters } from "@/features/core/clusters/queries"; +import { Input } from "@/shared/ui/input"; +import { Label } from "@/shared/ui/label"; +import * as React from "react"; +import { ResourcePicker } from "./ResourcePicker"; + +export type AllocationDraft = { + name: string; + clusterId: string; + sus: string; + start: string; + end: string; + resourceIds: string[]; +}; + +// Date inputs are local calendar days, so both directions stay in local time. +const isoDate = (d: Date) => d.toLocaleDateString("en-CA"); +const startOfDay = (day: string) => new Date(`${day}T00:00:00`).toISOString(); + +export const emptyAllocationDraft = (): AllocationDraft => ({ + name: "", + clusterId: "", + sus: "", + start: isoDate(new Date()), + end: isoDate(new Date(Date.now() + 365 * 24 * 3600 * 1000)), + resourceIds: [], +}); + +export const isDraftReady = (d: AllocationDraft) => + Boolean(d.name.trim() && d.clusterId && d.sus !== "" && d.start && d.end && d.start <= d.end); + +export const draftPayload = (projectId: string, d: AllocationDraft) => ({ + project_id: projectId, + name: d.name.trim(), + compute_cluster_id: d.clusterId, + initial_su_amount: Number(d.sus), + start_time: startOfDay(d.start), + end_time: startOfDay(d.end), + resourceIds: d.resourceIds, +}); + +// Fields of one allocation; an unset cluster falls back to the first one listed. +export function AllocationFields({ + value, + onChange, +}: { + value: AllocationDraft; + onChange: (next: AllocationDraft) => void; +}) { + const clusters = useClusters().data ?? []; + const first = clusters[0]?.id; + React.useEffect(() => { + if (!value.clusterId && first) onChange({ ...value, clusterId: first }); + }, [value, first, onChange]); + const set = (patch: Partial<AllocationDraft>) => onChange({ ...value, ...patch }); + return ( + <> + <div className="space-y-2"> + <Label htmlFor="allocation-name">Name</Label> + <Input + id="allocation-name" + value={value.name} + onChange={(e) => set({ name: e.target.value })} + /> + </div> + <div className="grid grid-cols-2 gap-3"> + <div className="space-y-2"> + <Label htmlFor="allocation-cluster">Cluster</Label> + <select + id="allocation-cluster" + value={value.clusterId} + onChange={(e) => set({ clusterId: e.target.value, resourceIds: [] })} + className="h-9 w-full rounded-md border bg-background px-3 text-sm" + > + {clusters.map((c) => ( + <option key={c.id} value={c.id}> + {c.name} + </option> + ))} + </select> + </div> + <div className="space-y-2"> + <Label htmlFor="allocation-sus">Initial SUs</Label> + <Input + id="allocation-sus" + type="number" + min={0} + value={value.sus} + onChange={(e) => set({ sus: e.target.value })} + /> + </div> + <div className="space-y-2"> + <Label htmlFor="allocation-start">Start date</Label> + <Input + id="allocation-start" + type="date" + value={value.start} + onChange={(e) => set({ start: e.target.value })} + /> + </div> + <div className="space-y-2"> + <Label htmlFor="allocation-end">End date</Label> + <Input + id="allocation-end" + type="date" + min={value.start} + value={value.end} + onChange={(e) => set({ end: e.target.value })} + /> + </div> + </div> + <div className="space-y-2"> + <Label>Resources</Label> + <ResourcePicker + clusterId={value.clusterId} + value={value.resourceIds} + onChange={(resourceIds) => set({ resourceIds })} + /> + </div> + </> + ); +} diff --git a/web/src/features/core/allocations/components/AllocationList.tsx b/web/src/features/core/allocations/components/AllocationList.tsx new file mode 100644 index 000000000..55f8e2f67 --- /dev/null +++ b/web/src/features/core/allocations/components/AllocationList.tsx @@ -0,0 +1,73 @@ +// 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. + +"use client"; + +import type { ComputeAllocation, ProjectResponse } from "@/generated/core/zod.gen"; +import { StatusIcon } from "@/shared/ui/StatusIcon"; +import { Server } from "lucide-react"; +import Link from "next/link"; +import { useAllocationUsedSU, useAllocationsByProject } from "../queries"; +import { AddAllocationButton } from "./AddAllocationButton"; + +function RemainingSU({ allocation }: { allocation: ComputeAllocation }) { + const used = useAllocationUsedSU(allocation.id).data; + return ( + <span className="tabular-nums" title={`of ${allocation.initial_su_amount.toLocaleString()}`}> + {used === undefined ? "…" : (allocation.initial_su_amount - used).toLocaleString()} + </span> + ); +} + +// One project's allocations as a list, ending with the add control. +export function AllocationList({ + project, +}: { + project: Pick<ProjectResponse, "id" | "title" | "ref">; +}) { + const { data, error } = useAllocationsByProject(project.id); + return ( + <ul className="space-y-1 text-sm"> + {error ? <li className="text-destructive">{error.message}</li> : null} + {(data?.items ?? []).map((row) => ( + <li key={row.id} className="flex flex-wrap items-center gap-x-2 gap-y-1"> + <StatusIcon + icon={Server} + active={row.status === "ACTIVE"} + label={row.status.toLowerCase()} + /> + <Link + href={`/projects/${row.project_id}/${row.id}`} + className="font-medium text-foreground hover:underline" + > + {row.name} + </Link> + <span className="text-xs text-muted-foreground"> + <RemainingSU allocation={row} /> SUs left · ends{" "} + {new Date(row.end_time).toLocaleDateString(undefined, { dateStyle: "medium" })} + </span> + </li> + ))} + <li className="flex items-center gap-2"> + <span aria-hidden className="w-4 text-center text-muted-foreground"> + + + </span> + <AddAllocationButton project={project} /> + </li> + </ul> + ); +} diff --git a/web/src/features/core/allocations/components/AllocationsList.tsx b/web/src/features/core/allocations/components/AllocationsList.tsx deleted file mode 100644 index f0afd62ad..000000000 --- a/web/src/features/core/allocations/components/AllocationsList.tsx +++ /dev/null @@ -1,278 +0,0 @@ -// 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. - -"use client"; - -import { ProjectGroupHeader } from "@/features/core/projects/components/ProjectGroupHeader"; -import type { AllocationStatus, ComputeAllocation } from "@/generated/core/zod.gen"; -import { DataTable, type DataTableColumn } from "@/shared/ui/DataTable"; -import { ErrorState } from "@/shared/ui/ErrorState"; -import { TableSkeleton } from "@/shared/ui/Loading"; -import { StatusIcon } from "@/shared/ui/StatusIcon"; -import { Input } from "@/shared/ui/input"; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/ui/select"; -import { Server } from "lucide-react"; -import Link from "next/link"; -import { useRouter } from "next/navigation"; -import * as React from "react"; -import { toast } from "sonner"; -import { useAllocationResources, useAllocationUsedSU, useSetAllocationResources } from "../queries"; -import { AllocationResourcesDialog } from "./AllocationResourcesDialog"; - -function formatDate(iso: string): string { - try { - return new Date(iso).toLocaleDateString(undefined, { - year: "numeric", - month: "short", - day: "numeric", - }); - } catch { - return iso; - } -} - -function statusLabelFor(value: string): string { - switch (value) { - case "ACTIVE": - return "Active"; - case "INACTIVE": - return "Inactive"; - case "DELETED": - return "Deleted"; - default: - return "All statuses"; - } -} - -function formatSU(n: number): string { - return new Intl.NumberFormat().format(n); -} - -export type AllocationsListProps = { - rows: ComputeAllocation[]; - isLoading: boolean; - error: Error | null; - onRetry?: () => void; - search: string; - onSearchChange: (next: string) => void; - statusFilter: AllocationStatus | "all"; - onStatusFilterChange: (next: AllocationStatus | "all") => void; - canEditResources: boolean; - headerCta?: React.ReactNode; -}; - -function RemainingSU({ allocation }: { allocation: ComputeAllocation }) { - const used = useAllocationUsedSU(allocation.id).data; - return ( - <span className="tabular-nums" title={`of ${formatSU(allocation.initial_su_amount)}`}> - {used === undefined ? "…" : formatSU(allocation.initial_su_amount - used)} - </span> - ); -} - -const PILL = "rounded-full border bg-card px-2 py-0.5 text-xs"; - -function ResourcePills({ - allocation, - canEdit, -}: { allocation: ComputeAllocation; canEdit: boolean }) { - const resources = useAllocationResources(allocation.id).data ?? []; - const save = useSetAllocationResources(allocation.id); - const [editing, setEditing] = React.useState(false); - return ( - <div className="flex items-center gap-1"> - {resources.map((r) => ( - <span key={r.id} className={`${PILL} inline-flex items-center gap-1`}> - {r.name} - {canEdit ? ( - <button - type="button" - aria-label={`Unassign ${r.name}`} - className="text-muted-foreground hover:text-foreground" - disabled={save.isPending} - onClick={() => - save.mutate( - resources.filter((x) => x.id !== r.id).map((x) => x.id), - { onError: (err) => toast.error(err.message) }, - ) - } - > - × - </button> - ) : null} - </span> - ))} - {canEdit ? ( - <button - type="button" - className={`${PILL} text-muted-foreground hover:text-foreground`} - onClick={() => setEditing(true)} - > - + Add resource - </button> - ) : null} - {editing ? ( - <AllocationResourcesDialog - allocation={allocation} - granted={resources} - onOpenChange={setEditing} - /> - ) : null} - </div> - ); -} - -export function AllocationsList({ - rows, - isLoading, - error, - onRetry, - search, - onSearchChange, - statusFilter, - onStatusFilterChange, - canEditResources, - headerCta, -}: AllocationsListProps) { - const router = useRouter(); - const filtered = React.useMemo(() => { - const needle = search.trim().toLowerCase(); - return rows.filter((row) => { - if (statusFilter !== "all" && row.status !== statusFilter) return false; - if (needle) { - const hay = `${row.name} ${row.project_id} ${row.id}`.toLowerCase(); - if (!hay.includes(needle)) return false; - } - return true; - }); - }, [rows, search, statusFilter]); - - const columns: Array<DataTableColumn<ComputeAllocation>> = [ - { - key: "name", - header: "Allocation", - sortable: true, - sortValue: (row) => row.name, - cell: (row) => ( - <span className="-ml-7 inline-flex items-center gap-3 whitespace-nowrap"> - <StatusIcon - icon={Server} - active={row.status === "ACTIVE"} - label={statusLabelFor(row.status)} - /> - <Link href={`/allocations/${row.id}`} className="font-medium text-foreground"> - {row.name} - </Link> - </span> - ), - }, - { - key: "resources", - header: "Resources", - width: "16rem", - cell: (row) => <ResourcePills allocation={row} canEdit={canEditResources} />, - }, - { - key: "remaining", - header: "Remaining SUs", - width: "9rem", - cell: (row) => <RemainingSU allocation={row} />, - }, - { - key: "endDate", - header: "End date", - width: "9rem", - sortable: true, - sortValue: (row) => new Date(row.end_time), - cell: (row) => ( - <span className="text-sm text-muted-foreground">{formatDate(row.end_time)}</span> - ), - }, - ]; - - return ( - <div className="space-y-6"> - <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between"> - <div> - <h1 className="font-display text-[28px] font-bold leading-tight">Allocations</h1> - <p className="mt-1 text-sm text-muted-foreground"> - Compute resources granted to you across projects. - </p> - </div> - {headerCta ? <div>{headerCta}</div> : null} - </div> - - <div className="flex flex-col gap-3 rounded-md border bg-card p-4 sm:flex-row sm:items-center"> - <Input - type="search" - placeholder="Search by allocation name, project, or ID" - value={search} - onChange={(e) => onSearchChange(e.target.value)} - aria-label="Search allocations" - className="sm:w-72" - /> - <Select - value={statusFilter} - onValueChange={(value) => value !== null && onStatusFilterChange(value)} - > - <SelectTrigger aria-label="Filter by status" className="h-9 w-36 px-3"> - <SelectValue>{(value: string) => statusLabelFor(value)}</SelectValue> - </SelectTrigger> - <SelectContent> - <SelectItem value="all">All statuses</SelectItem> - <SelectItem value="ACTIVE">Active</SelectItem> - <SelectItem value="INACTIVE">Inactive</SelectItem> - <SelectItem value="DELETED">Deleted</SelectItem> - </SelectContent> - </Select> - </div> - - {isLoading ? ( - <TableSkeleton rows={6} columns={5} /> - ) : error ? ( - <ErrorState message={error.message} onRetry={onRetry} /> - ) : filtered.length === 0 ? ( - <DataTable - columns={columns} - rows={[]} - rowKey={(row) => row.id} - empty="No allocations match the current filters." - /> - ) : ( - <div className="space-y-3"> - {[...Map.groupBy(filtered, (row) => row.project_id)].map(([projectId, rows]) => ( - <section - key={projectId} - className="overflow-hidden rounded-lg border border-foreground/20 bg-card" - > - <div className="border-b border-border bg-muted px-4 py-2.5"> - <ProjectGroupHeader id={projectId} /> - </div> - <DataTable - className="rounded-none border-0 [&_th]:py-1.5 [&_thead]:bg-muted/40 [&_td:first-child]:pl-11 [&_th:first-child]:pl-11 [&_td]:align-middle [&_td]:whitespace-nowrap" - columns={columns} - rows={rows} - rowKey={(row) => row.id} - onRowClick={(row) => router.push(`/allocations/${row.id}`)} - /> - </section> - ))} - </div> - )} - </div> - ); -} diff --git a/web/src/features/core/allocations/components/CreateAllocationDialog.tsx b/web/src/features/core/allocations/components/CreateAllocationDialog.tsx deleted file mode 100644 index 1dc86de6b..000000000 --- a/web/src/features/core/allocations/components/CreateAllocationDialog.tsx +++ /dev/null @@ -1,212 +0,0 @@ -// 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. - -"use client"; - -import { useClusters } from "@/features/core/clusters/queries"; -import { useProjects } from "@/features/core/projects/queries"; -import type { ProjectResponse } from "@/generated/core/zod.gen"; -import { useDebounce } from "@/shared/hooks/useDebounce"; -import { SuggestInput } from "@/shared/ui/SuggestInput"; -import { Button } from "@/shared/ui/button"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/shared/ui/dialog"; -import { Input } from "@/shared/ui/input"; -import { Label } from "@/shared/ui/label"; -import * as React from "react"; -import { toast } from "sonner"; -import { useCreateAllocation } from "../queries"; -import { ResourcePicker } from "./ResourcePicker"; - -export type CreateAllocationDialogProps = { - onOpenChange: (open: boolean) => void; - // Fixes the project when opened from a project page. - project?: Pick<ProjectResponse, "id" | "title" | "ref">; -}; - -const projectLabel = (p: Pick<ProjectResponse, "title" | "ref">) => `${p.ref}: ${p.title}`; - -// Date inputs are local calendar days, so both directions stay in local time. -const isoDate = (d: Date) => d.toLocaleDateString("en-CA"); -const startOfDay = (day: string) => new Date(`${day}T00:00:00`).toISOString(); - -export function CreateAllocationDialog({ onOpenChange, project }: CreateAllocationDialogProps) { - const create = useCreateAllocation(); - const clusters = useClusters(); - const [projectText, setProjectText] = React.useState(""); - const [chosen, setChosen] = React.useState<ProjectResponse | null>(null); - const query = useDebounce(projectText.trim(), 200); - const projects = useProjects({ q: query, limit: 8 }); - const [name, setName] = React.useState(""); - const [clusterId, setClusterId] = React.useState(""); - const [sus, setSus] = React.useState(""); - const [resourceIds, setResourceIds] = React.useState<string[]>([]); - const [start, setStart] = React.useState(() => isoDate(new Date())); - const [end, setEnd] = React.useState(() => - isoDate(new Date(Date.now() + 365 * 24 * 3600 * 1000)), - ); - - // Results for an older query would let Enter pick a project the typed text no longer names. - const found = project || query !== projectText.trim() ? [] : (projects.data?.items ?? []); - const picked = project ?? chosen; - const cluster = clusterId || clusters.data?.[0]?.id || ""; - const ready = Boolean( - picked && name.trim() && cluster && sus !== "" && start && end && start <= end, - ); - - return ( - <Dialog open onOpenChange={onOpenChange}> - <DialogContent> - <DialogHeader> - <DialogTitle>Add allocation</DialogTitle> - <DialogDescription>Grant a project compute time on a cluster.</DialogDescription> - </DialogHeader> - <form - className="space-y-4" - onSubmit={(e) => { - e.preventDefault(); - if (!picked || !ready) return; - create.mutate( - { - project_id: picked.id, - name: name.trim(), - compute_cluster_id: cluster, - initial_su_amount: Number(sus), - start_time: startOfDay(start), - end_time: startOfDay(end), - resourceIds, - }, - { - onSuccess: (created) => { - toast.success(`Allocation ${created.name} created.`); - onOpenChange(false); - }, - }, - ); - }} - > - <div className="space-y-2"> - <Label htmlFor="new-allocation-project">Project</Label> - {project ? ( - <p id="new-allocation-project" className="text-sm"> - {projectLabel(project)} - </p> - ) : ( - <SuggestInput - id="new-allocation-project" - value={projectText} - onValueChange={(next) => { - setProjectText(next); - setChosen(found.find((p) => projectLabel(p) === next) ?? null); - }} - suggestions={found.map((p) => ({ value: projectLabel(p) }))} - emptyMessage={ - !projectText.trim() - ? "Type to search" - : query === projectText.trim() && !projects.isFetching - ? "No matching project." - : "Searching…" - } - placeholder="Search by title or ID" - /> - )} - </div> - <div className="space-y-2"> - <Label htmlFor="new-allocation-name">Name</Label> - <Input - id="new-allocation-name" - value={name} - onChange={(e) => setName(e.target.value)} - required - /> - </div> - <div className="grid grid-cols-2 gap-3"> - <div className="space-y-2"> - <Label htmlFor="new-allocation-cluster">Cluster</Label> - <select - id="new-allocation-cluster" - value={cluster} - onChange={(e) => { - setClusterId(e.target.value); - setResourceIds([]); - }} - className="h-9 w-full rounded-md border bg-background px-3 text-sm" - > - {(clusters.data ?? []).map((c) => ( - <option key={c.id} value={c.id}> - {c.name} - </option> - ))} - </select> - </div> - <div className="space-y-2"> - <Label htmlFor="new-allocation-sus">Initial SUs</Label> - <Input - id="new-allocation-sus" - type="number" - min={0} - value={sus} - onChange={(e) => setSus(e.target.value)} - required - /> - </div> - <div className="space-y-2"> - <Label htmlFor="new-allocation-start">Start date</Label> - <Input - id="new-allocation-start" - type="date" - value={start} - onChange={(e) => setStart(e.target.value)} - required - /> - </div> - <div className="space-y-2"> - <Label htmlFor="new-allocation-end">End date</Label> - <Input - id="new-allocation-end" - type="date" - min={start} - value={end} - onChange={(e) => setEnd(e.target.value)} - required - /> - </div> - </div> - <div className="space-y-2"> - <Label>Resources</Label> - <ResourcePicker clusterId={cluster} value={resourceIds} onChange={setResourceIds} /> - </div> - {create.error ? <p className="text-destructive text-sm">{create.error.message}</p> : null} - <DialogFooter> - <Button type="button" variant="outline" onClick={() => onOpenChange(false)}> - Cancel - </Button> - <Button type="submit" disabled={create.isPending || !ready}> - {create.isPending ? "Creating…" : "Add allocation"} - </Button> - </DialogFooter> - </form> - </DialogContent> - </Dialog> - ); -} diff --git a/web/src/features/core/projects/__tests__/CreateProjectDialog.test.tsx b/web/src/features/core/projects/__tests__/CreateProjectDialog.test.tsx new file mode 100644 index 000000000..12854bbd2 --- /dev/null +++ b/web/src/features/core/projects/__tests__/CreateProjectDialog.test.tsx @@ -0,0 +1,89 @@ +// 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 { act, fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +const { createProject, createAllocation, toastError, push } = vi.hoisted(() => ({ + createProject: vi.fn(async () => ({ id: "project-new", title: "Climate" })), + createAllocation: vi.fn(), + toastError: vi.fn(), + push: vi.fn(), +})); + +vi.mock("next/navigation", () => ({ useRouter: () => ({ push }) })); + +vi.mock("../queries", () => ({ + useCreateProject: () => ({ mutateAsync: createProject }), +})); +vi.mock("@/features/core/allocations/queries", () => ({ + useCreateAllocation: () => ({ mutateAsync: createAllocation }), +})); +vi.mock("@/features/core/users/queries", () => ({ + useUserEmailSearch: () => ({ match: { id: "user-pi" }, suggestions: [], emptyMessage: "" }), +})); +vi.mock("@/features/core/clusters/queries", () => ({ + useClusters: () => ({ data: [{ id: "cluster-a", name: "ClusterA" }] }), + useCluster: () => ({ data: { name: "ClusterA" } }), +})); +vi.mock("@/features/core/resources/queries", () => ({ + useResourceSummaries: () => ({ data: [] }), +})); +vi.mock("sonner", () => ({ toast: { error: toastError, success: vi.fn() } })); + +import { CreateProjectDialog } from "../components/CreateProjectDialog"; + +const click = (name: string) => fireEvent.click(screen.getByRole("button", { name })); + +function addDraft(name: string) { + fireEvent.change(screen.getByLabelText("Name"), { target: { value: name } }); + fireEvent.change(screen.getByLabelText("Initial SUs"), { target: { value: "1000" } }); + click("Add allocation"); +} + +describe("<CreateProjectDialog />", () => { + it("creates nothing until confirmed, then the project and each allocation under it", async () => { + createAllocation.mockResolvedValueOnce({}).mockRejectedValueOnce(new Error("quota")); + render( + <QueryClientProvider client={new QueryClient()}> + <CreateProjectDialog onOpenChange={vi.fn()} /> + </QueryClientProvider>, + ); + + fireEvent.change(screen.getByLabelText("Title"), { target: { value: "Climate" } }); + fireEvent.change(screen.getByLabelText("PI"), { target: { value: "[email protected]" } }); + click("Next"); + addDraft("GPU"); + addDraft("CPU"); + click("Next"); + expect(createProject).not.toHaveBeenCalled(); + + await act(async () => click("Confirm and create")); + expect(createProject).toHaveBeenCalledWith({ + title: "Climate", + origination: "internal", + project_pi_id: "user-pi", + }); + expect(createAllocation.mock.calls.map(([p]) => [p.project_id, p.name])).toEqual([ + ["project-new", "GPU"], + ["project-new", "CPU"], + ]); + expect(toastError).toHaveBeenCalledWith("Project Climate created; 1 allocation(s) failed."); + expect(push).toHaveBeenCalledWith("/projects/project-new"); + }); +}); diff --git a/web/src/features/core/projects/__tests__/ProjectsList.test.tsx b/web/src/features/core/projects/__tests__/ProjectsList.test.tsx index bc264fa9a..79b6b82c6 100644 --- a/web/src/features/core/projects/__tests__/ProjectsList.test.tsx +++ b/web/src/features/core/projects/__tests__/ProjectsList.test.tsx @@ -20,7 +20,11 @@ import { render, screen } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; import { ProjectsList } from "../components/ProjectsList"; -vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) })); +vi.mock("../components/ProjectCard", () => ({ + ProjectCard: ({ project }: { project: ProjectResponse }) => ( + <a href={`/projects/${project.id}`}>{project.title}</a> + ), +})); const project: ProjectResponse = { id: "project-001", @@ -41,6 +45,7 @@ function renderList(overrides: Partial<React.ComponentProps<typeof ProjectsList> search: "", onSearchChange: vi.fn(), statusFilter: "all" as const, + origination: null, onStatusFilterChange: vi.fn(), ...overrides, }; @@ -71,6 +76,18 @@ describe("<ProjectsList />", () => { expect(screen.getByRole("link", { name: inactive.title })).toBeInTheDocument(); }); + it("filters by origination, ignoring case", () => { + const nairr: ProjectResponse = { + ...project, + id: "project-003", + title: "NAIRR Project", + origination: "NAIRR", + }; + renderList({ rows: [project, nairr], origination: "nairr" }); + expect(screen.queryByRole("link", { name: project.title })).not.toBeInTheDocument(); + expect(screen.getByRole("link", { name: nairr.title })).toBeInTheDocument(); + }); + it("surfaces an error state with a retry callback", () => { const onRetry = vi.fn(); renderList({ error: new Error("boom"), onRetry }); diff --git a/web/src/features/core/projects/components/CreateProjectDialog.tsx b/web/src/features/core/projects/components/CreateProjectDialog.tsx index a8ec333da..0c17ca98f 100644 --- a/web/src/features/core/projects/components/CreateProjectDialog.tsx +++ b/web/src/features/core/projects/components/CreateProjectDialog.tsx @@ -17,6 +17,16 @@ "use client"; +import { + type AllocationDraft, + AllocationFields, + draftPayload, + emptyAllocationDraft, + isDraftReady, +} from "@/features/core/allocations/components/AllocationFields"; +import { useCreateAllocation } from "@/features/core/allocations/queries"; +import { ClusterName } from "@/features/core/clusters/components/ClusterName"; +import { useResourceSummaries } from "@/features/core/resources/queries"; import { useUserEmailSearch } from "@/features/core/users/queries"; import { SuggestInput } from "@/shared/ui/SuggestInput"; import { Button } from "@/shared/ui/button"; @@ -30,79 +40,190 @@ import { } from "@/shared/ui/dialog"; import { Input } from "@/shared/ui/input"; import { Label } from "@/shared/ui/label"; +import { useMutation } from "@tanstack/react-query"; +import { Server } from "lucide-react"; import { useRouter } from "next/navigation"; import * as React from "react"; +import { toast } from "sonner"; import { useCreateProject } from "../queries"; export type CreateProjectDialogProps = { onOpenChange: (open: boolean) => void; }; +const STEPS = [ + "Name the project and its PI.", + "Add its allocations; more can be added later.", + "Review, then confirm. Nothing is created before this.", +]; + +const day = (d: string) => + new Date(`${d}T00:00:00`).toLocaleDateString(undefined, { dateStyle: "medium" }); + export function CreateProjectDialog({ onOpenChange }: CreateProjectDialogProps) { const router = useRouter(); - const create = useCreateProject(); + const createProject = useCreateProject(); + const createAllocation = useCreateAllocation(); + const [step, setStep] = React.useState(0); const [title, setTitle] = React.useState(""); const [piEmail, setPiEmail] = React.useState(""); const pi = useUserEmailSearch(piEmail, true); + const [drafts, setDrafts] = React.useState<AllocationDraft[]>([]); + const [draft, setDraft] = React.useState(emptyAllocationDraft); + // One mutation spans every create, so Confirm stays disabled until all of them settle. + const submit = useMutation({ + mutationFn: async (piId: string) => { + const project = await createProject.mutateAsync({ + title: title.trim(), + origination: "internal", + project_pi_id: piId, + }); + const results = await Promise.allSettled( + drafts.map((d) => createAllocation.mutateAsync(draftPayload(project.id, d))), + ); + const failed = results.filter((r) => r.status === "rejected").length; + if (failed) toast.error(`Project ${project.title} created; ${failed} allocation(s) failed.`); + else toast.success(`Project ${project.title} created with ${drafts.length} allocation(s).`); + router.push(`/projects/${project.id}`); + }, + }); return ( <Dialog open onOpenChange={onOpenChange}> - <DialogContent> + <DialogContent className="sm:max-w-2xl"> <DialogHeader> <DialogTitle>New project</DialogTitle> <DialogDescription> - Create a project; add allocations and members after. + Step {step + 1} of {STEPS.length} · {STEPS[step]} </DialogDescription> </DialogHeader> - <form - className="space-y-4" - onSubmit={(e) => { - e.preventDefault(); - if (!title.trim() || !pi.match) return; - create.mutate( - { - title: title.trim(), - origination: "internal", - project_pi_id: pi.match.id, - }, - { onSuccess: (project) => router.push(`/projects/${project.id}`) }, - ); - }} - > - <div className="space-y-2"> - <Label htmlFor="new-project-title">Title</Label> - <Input - id="new-project-title" - value={title} - onChange={(e) => setTitle(e.target.value)} - maxLength={200} - required - /> + + {step === 0 ? ( + <div className="space-y-4"> + <div className="space-y-2"> + <Label htmlFor="new-project-title">Title</Label> + <Input + id="new-project-title" + value={title} + onChange={(e) => setTitle(e.target.value)} + maxLength={200} + /> + </div> + <div className="space-y-2"> + <Label htmlFor="new-project-pi">PI</Label> + <SuggestInput + id="new-project-pi" + type="email" + value={piEmail} + onValueChange={setPiEmail} + suggestions={pi.suggestions} + emptyMessage={pi.emptyMessage} + placeholder="[email protected]" + /> + </div> </div> - <div className="space-y-2"> - <Label htmlFor="new-project-pi">PI</Label> - <SuggestInput - id="new-project-pi" - type="email" - value={piEmail} - onValueChange={setPiEmail} - suggestions={pi.suggestions} - emptyMessage={pi.emptyMessage} - placeholder="[email protected]" - required - /> + ) : step === 1 ? ( + <div className="space-y-4"> + <DraftList drafts={drafts} onRemove={(i) => setDrafts(drafts.toSpliced(i, 1))} /> + <div className="space-y-4 rounded-lg border p-4"> + <AllocationFields value={draft} onChange={setDraft} /> + <div className="flex justify-end"> + <Button + type="button" + variant="outline" + disabled={!isDraftReady(draft)} + onClick={() => { + setDrafts([...drafts, draft]); + setDraft({ ...emptyAllocationDraft(), clusterId: draft.clusterId }); + }} + > + Add allocation + </Button> + </div> + </div> </div> - {create.error ? <p className="text-destructive text-sm">{create.error.message}</p> : null} - <DialogFooter> - <Button type="button" variant="outline" onClick={() => onOpenChange(false)}> - Cancel + ) : ( + <dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-2 text-sm"> + <dt className="text-muted-foreground">Title</dt> + <dd>{title.trim()}</dd> + <dt className="text-muted-foreground">PI</dt> + <dd>{piEmail}</dd> + <dt className="text-muted-foreground">Allocations</dt> + <dd> + <DraftList drafts={drafts} /> + </dd> + </dl> + )} + + {submit.error ? <p className="text-destructive text-sm">{submit.error.message}</p> : null} + <DialogFooter> + <Button + type="button" + variant="outline" + onClick={() => (step === 0 ? onOpenChange(false) : setStep(step - 1))} + > + {step === 0 ? "Cancel" : "Back"} + </Button> + {step < 2 ? ( + <Button + type="button" + disabled={step === 0 && (!title.trim() || !pi.match)} + onClick={() => setStep(step + 1)} + > + Next </Button> - <Button type="submit" disabled={create.isPending || !title.trim() || !pi.match}> - {create.isPending ? "Creating…" : "Create project"} + ) : ( + <Button + type="button" + disabled={submit.isPending} + onClick={() => pi.match && submit.mutate(pi.match.id)} + > + {submit.isPending ? "Creating…" : "Confirm and create"} </Button> - </DialogFooter> - </form> + )} + </DialogFooter> </DialogContent> </Dialog> ); } + +function DraftLine({ draft }: { draft: AllocationDraft }) { + const resources = useResourceSummaries().data ?? []; + const names = resources.filter((r) => draft.resourceIds.includes(r.id)).map((r) => r.name); + return ( + <span className="text-xs text-muted-foreground"> + <ClusterName id={draft.clusterId} /> · {Number(draft.sus).toLocaleString()} SUs ·{" "} + {day(draft.start)} – {day(draft.end)} + {names.length ? ` · ${names.join(", ")}` : ""} + </span> + ); +} + +function DraftList({ + drafts, + onRemove, +}: { + drafts: AllocationDraft[]; + onRemove?: (i: number) => void; +}) { + if (drafts.length === 0) + return <p className="text-sm text-muted-foreground">No allocations added.</p>; + return ( + <ul className="divide-y rounded-md border"> + {drafts.map((d, i) => ( + <li key={i} className="flex items-center gap-3 px-3 py-2"> + <Server className="size-4 text-muted-foreground" aria-hidden /> + <div className="flex min-w-0 flex-1 flex-col"> + <span className="text-sm font-medium">{d.name}</span> + <DraftLine draft={d} /> + </div> + {onRemove ? ( + <Button type="button" variant="ghost" size="sm" onClick={() => onRemove(i)}> + Remove + </Button> + ) : null} + </li> + ))} + </ul> + ); +} diff --git a/web/src/features/core/projects/components/ProjectCard.tsx b/web/src/features/core/projects/components/ProjectCard.tsx new file mode 100644 index 000000000..a1cd493df --- /dev/null +++ b/web/src/features/core/projects/components/ProjectCard.tsx @@ -0,0 +1,87 @@ +// 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. + +"use client"; + +import { AllocationList } from "@/features/core/allocations/components/AllocationList"; +import type { ProjectResponse } from "@/generated/core/zod.gen"; +import { cn } from "@/lib/utils"; +import { Badge } from "@/shared/ui/badge"; +import { ChevronRight } from "lucide-react"; +import Link from "next/link"; +import { ProjectPI } from "./ProjectPI"; + +// Colours per origination, so ACCESS, NAIRR and internal projects read apart at a glance. +const ORIGINATION_COLOR: Record<string, { outline: string; pill: string }> = { + access: { + outline: "border-custos-blue-300 border-l-custos-blue-500", + pill: "border-custos-blue-300 bg-custos-blue-50 text-custos-blue-700", + }, + nairr: { + outline: "border-custos-green-400 border-l-custos-green-600", + pill: "border-custos-green-400 bg-custos-green-50 text-custos-green-800", + }, + internal: { + outline: "border-custos-amber-500/60 border-l-custos-amber-600", + pill: "border-custos-amber-500/60 bg-custos-amber-50 text-custos-amber-800", + }, +}; + +export function ProjectCard({ project }: { project: ProjectResponse }) { + const color = ORIGINATION_COLOR[project.origination.toLowerCase()]; + return ( + <section + className={cn( + "relative overflow-hidden rounded-lg border border-l-4 bg-card", + color?.outline ?? "border-foreground/20", + )} + > + <Link + href={`/projects/${project.id}`} + className="group flex items-center gap-3 border-b bg-muted px-4 py-2 hover:bg-brand/10" + > + <div className="min-w-0 flex-1"> + <h2 className="truncate font-display text-sm font-semibold leading-tight text-foreground"> + {project.ref.slice(project.ref.indexOf("-") + 1)}: {project.title} + </h2> + <Badge variant="outline" className={cn("mt-1", color?.pill ?? "bg-card")}> + {project.origination} + </Badge> + </div> + <span className="inline-flex shrink-0 items-center gap-0.5 text-xs font-medium text-muted-foreground group-hover:text-foreground"> + Go to project + <ChevronRight className="size-3.5" aria-hidden /> + </span> + </Link> + <dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1 px-4 py-2 text-sm"> + <dt className="text-muted-foreground">PI</dt> + <dd> + <ProjectPI project={project} /> + </dd> + <dt className="text-muted-foreground">Allocations</dt> + <dd> + <AllocationList project={project} /> + </dd> + </dl> + {project.status === "ACTIVE" ? null : ( + <div className="pointer-events-none absolute inset-0 grid select-none place-items-center bg-[repeating-linear-gradient(-45deg,transparent_0_3px,rgb(0_0_0/0.06)_3px_4px)] font-display text-4xl font-bold tracking-[0.3em] text-foreground/15"> + {project.status} + </div> + )} + </section> + ); +} diff --git a/web/src/features/core/projects/components/ProjectDetail.tsx b/web/src/features/core/projects/components/ProjectDetail.tsx index ad08cacb0..60b82ce3b 100644 --- a/web/src/features/core/projects/components/ProjectDetail.tsx +++ b/web/src/features/core/projects/components/ProjectDetail.tsx @@ -17,14 +17,11 @@ "use client"; -import { CreateAllocationDialog } from "@/features/core/allocations/components/CreateAllocationDialog"; import { requires, usePermissions } from "@/shared/casl/permissions"; import { useBreadcrumbLabel } from "@/shared/layout/BreadcrumbLabelsProvider"; import { DeleteButton } from "@/shared/ui/ConfirmDialog"; import { ErrorState } from "@/shared/ui/ErrorState"; -import { GuardedButton } from "@/shared/ui/GuardedButton"; import { CardSkeleton } from "@/shared/ui/Loading"; -import * as React from "react"; import { useDeleteProject, useProject } from "../queries"; import { ProjectDetailHeader } from "./ProjectDetailHeader"; import { ProjectMembersTab } from "./ProjectMembersTab"; @@ -37,7 +34,6 @@ export type ProjectDetailProps = { export function ProjectDetail({ projectId }: ProjectDetailProps) { const can = usePermissions(); const projectQuery = useProject(projectId); - const [addingAllocation, setAddingAllocation] = React.useState(false); const remove = useDeleteProject(); useBreadcrumbLabel(projectId, projectQuery.data?.title); @@ -66,29 +62,13 @@ export function ProjectDetail({ projectId }: ProjectDetailProps) { A project can be deleted only once it has no allocations. This cannot be undone. </DeleteButton> </div> - <ProjectOverviewTab - project={project} - addAllocation={ - <GuardedButton - variant="link" - className="h-auto border-0 p-0" - allowed={can.allocationsWrite && can.clustersRead} - reason={requires("allocationsWrite", "clustersRead")} - onClick={() => setAddingAllocation(true)} - > - Add allocation - </GuardedButton> - } - /> + <ProjectOverviewTab project={project} /> <ProjectMembersTab projectId={project.id} canEditRoles={can.projectsWrite} canEditAccess={can.allocationsWrite} canSearchUsers={can.usersRead} /> - {addingAllocation ? ( - <CreateAllocationDialog onOpenChange={setAddingAllocation} project={project} /> - ) : null} </section> ); } diff --git a/web/src/features/core/projects/components/ProjectGroupHeader.tsx b/web/src/features/core/projects/components/ProjectGroupHeader.tsx deleted file mode 100644 index 0faf20115..000000000 --- a/web/src/features/core/projects/components/ProjectGroupHeader.tsx +++ /dev/null @@ -1,48 +0,0 @@ -// 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. - -"use client"; - -import { ChevronRight } from "lucide-react"; -import Link from "next/link"; -import { useProject } from "../queries"; -import { ProjectRef } from "./ProjectRef"; -import { ProjectStatusIcon } from "./ProjectStatusIcon"; - -// Header of a project's card for rows that carry only its id; fetched once and cached per project. -export function ProjectGroupHeader({ id }: { id: string }) { - const { data: project, isLoading } = useProject(id); - if (!project) return <>{isLoading ? "—" : "Unknown project"}</>; - return ( - <div className="flex items-center gap-3"> - <ProjectStatusIcon status={project.status} /> - <div className="flex min-w-0 flex-1 items-center gap-2"> - <span className="truncate text-xs font-semibold uppercase tracking-wide text-foreground"> - {project.title} - </span> - <ProjectRef project={project} /> - </div> - <Link - href={`/projects/${id}`} - className="inline-flex shrink-0 items-center gap-0.5 text-xs font-medium text-muted-foreground hover:text-foreground" - > - Go to project - <ChevronRight className="size-3.5" aria-hidden /> - </Link> - </div> - ); -} diff --git a/web/src/features/core/projects/components/ProjectMembersTab.tsx b/web/src/features/core/projects/components/ProjectMembersTab.tsx index f57436204..5a10d682f 100644 --- a/web/src/features/core/projects/components/ProjectMembersTab.tsx +++ b/web/src/features/core/projects/components/ProjectMembersTab.tsx @@ -347,7 +347,7 @@ export function ProjectMembersTab({ <TableHead className="w-48">Role</TableHead> {allocations.map((a) => ( <TableHead key={a.id} className="text-center"> - <Link href={`/allocations/${a.id}`} className="hover:underline"> + <Link href={`/projects/${a.project_id}/${a.id}`} className="hover:underline"> {a.name} </Link> </TableHead> diff --git a/web/src/features/core/projects/components/ProjectOverviewTab.tsx b/web/src/features/core/projects/components/ProjectOverviewTab.tsx index d4c790595..0f5785760 100644 --- a/web/src/features/core/projects/components/ProjectOverviewTab.tsx +++ b/web/src/features/core/projects/components/ProjectOverviewTab.tsx @@ -17,24 +17,15 @@ "use client"; -import { useAllocationsByProject } from "@/features/core/allocations/queries"; -import { ClusterName } from "@/features/core/clusters/components/ClusterName"; +import { AllocationList } from "@/features/core/allocations/components/AllocationList"; import type { ProjectResponse } from "@/generated/core/zod.gen"; -import { usePermissions } from "@/shared/casl/permissions"; -import { StatusIcon } from "@/shared/ui/StatusIcon"; -import { Server } from "lucide-react"; -import Link from "next/link"; -import type * as React from "react"; import { ProjectPI } from "./ProjectPI"; export type ProjectOverviewTabProps = { project: ProjectResponse; - addAllocation: React.ReactNode; }; -export function ProjectOverviewTab({ project, addAllocation }: ProjectOverviewTabProps) { - const can = usePermissions(); - const allocations = useAllocationsByProject(project.id).data?.items ?? []; +export function ProjectOverviewTab({ project }: ProjectOverviewTabProps) { return ( <dl className="grid gap-x-8 gap-y-3 rounded-lg border border-border bg-muted/40 p-4 text-sm sm:grid-cols-[max-content_1fr]"> <dt className="text-muted-foreground">Ref</dt> @@ -47,36 +38,7 @@ export function ProjectOverviewTab({ project, addAllocation }: ProjectOverviewTa <dt className="text-muted-foreground">Allocations</dt> <dd className="text-foreground"> - <ul className="space-y-0.5"> - {allocations.map((a) => ( - <li key={a.id} className="flex items-center gap-2"> - <StatusIcon - icon={Server} - active={a.status === "ACTIVE"} - label={a.status.toLowerCase()} - /> - <Link href={`/allocations/${a.id}`} className="hover:underline"> - {a.name} - </Link> - <span className="text-xs text-muted-foreground"> - {can.clustersRead ? ( - <> - <ClusterName id={a.compute_cluster_id} /> - {" · "} - </> - ) : null} - {a.initial_su_amount.toLocaleString()} SUs · ends{" "} - {new Date(a.end_time).toLocaleDateString(undefined, { dateStyle: "medium" })} - </span> - </li> - ))} - <li className="flex gap-2"> - <span aria-hidden className="w-4 text-center"> - + - </span> - {addAllocation} - </li> - </ul> + <AllocationList project={project} /> </dd> </dl> ); diff --git a/web/src/features/core/projects/components/ProjectStatusIcon.tsx b/web/src/features/core/projects/components/ProjectStatusIcon.tsx deleted file mode 100644 index 3f2a57832..000000000 --- a/web/src/features/core/projects/components/ProjectStatusIcon.tsx +++ /dev/null @@ -1,26 +0,0 @@ -// 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 type { ProjectStatus } from "@/generated/core/zod.gen"; -import { StatusIcon } from "@/shared/ui/StatusIcon"; -import { FolderKanban } from "lucide-react"; - -export function ProjectStatusIcon({ status }: { status: ProjectStatus }) { - return ( - <StatusIcon icon={FolderKanban} active={status === "ACTIVE"} label={status.toLowerCase()} /> - ); -} diff --git a/web/src/features/core/projects/components/ProjectsList.tsx b/web/src/features/core/projects/components/ProjectsList.tsx index 4a11193c8..1b63388d3 100644 --- a/web/src/features/core/projects/components/ProjectsList.tsx +++ b/web/src/features/core/projects/components/ProjectsList.tsx @@ -19,16 +19,14 @@ import type { ProjectResponse, ProjectStatus } from "@/generated/core/zod.gen"; import { requires } from "@/shared/casl/permissions"; -import { DataTable, type DataTableColumn } from "@/shared/ui/DataTable"; +import { EmptyState } from "@/shared/ui/EmptyState"; import { ErrorState } from "@/shared/ui/ErrorState"; import { GuardedButton } from "@/shared/ui/GuardedButton"; import { TableSkeleton } from "@/shared/ui/Loading"; import { Input } from "@/shared/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/ui/select"; -import Link from "next/link"; -import { useRouter } from "next/navigation"; import * as React from "react"; -import { ProjectStatusIcon } from "./ProjectStatusIcon"; +import { ProjectCard } from "./ProjectCard"; function statusLabelFor(value: string): string { switch (value) { @@ -51,6 +49,7 @@ export type ProjectsListProps = { search: string; onSearchChange: (next: string) => void; statusFilter: ProjectStatus | "all"; + origination: string | null; onStatusFilterChange: (next: ProjectStatus | "all") => void; headerCta?: React.ReactNode; }; @@ -63,71 +62,32 @@ export function ProjectsList({ search, onSearchChange, statusFilter, + origination, onStatusFilterChange, headerCta, }: ProjectsListProps) { - const router = useRouter(); const filtered = React.useMemo(() => { const needle = search.trim().toLowerCase(); return rows.filter((row) => { if (statusFilter !== "all" && row.status !== statusFilter) return false; + if (origination && row.origination.toLowerCase() !== origination.toLowerCase()) return false; if (needle) { const hay = `${row.title} ${row.ref}`.toLowerCase(); if (!hay.includes(needle)) return false; } return true; }); - }, [rows, search, statusFilter]); - - const columns: Array<DataTableColumn<ProjectResponse>> = [ - { - key: "title", - header: "Project", - sortable: true, - sortValue: (row) => row.title, - cell: (row) => ( - <div className="flex items-center gap-2"> - <ProjectStatusIcon status={row.status} /> - <div className="flex flex-col items-start gap-0.5"> - <Link href={`/projects/${row.id}`} className="font-medium text-foreground"> - {row.title} - </Link> - <span className="text-xs text-muted-foreground">{row.ref}</span> - </div> - </div> - ), - }, - { - key: "pi", - header: "PI", - sortable: true, - sortValue: (row) => row.project_pi_display_name ?? row.project_pi_id, - cell: (row) => ( - <div className="flex flex-col gap-0.5"> - <span className="text-sm text-muted-foreground"> - {row.project_pi_display_name ?? row.project_pi_id} - </span> - {row.project_pi_email ? ( - <span className="text-xs text-muted-foreground">{row.project_pi_email}</span> - ) : null} - </div> - ), - }, - { - key: "origination", - header: "Origination", - width: "8rem", - sortable: true, - sortValue: (row) => row.origination, - cell: (row) => <span className="text-sm">{row.origination}</span>, - }, - ]; + }, [rows, search, statusFilter, origination]); return ( <div className="space-y-6"> <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between"> <div> - <h1 className="font-display text-[28px] font-bold leading-tight">Projects</h1> + <h1 className="font-display text-[28px] font-bold leading-tight"> + {origination + ? `${origination[0]?.toUpperCase()}${origination.slice(1)} projects` + : "Projects"} + </h1> <p className="mt-1 text-sm text-muted-foreground"> Projects you own, manage, or belong to. </p> @@ -164,14 +124,14 @@ export function ProjectsList({ <TableSkeleton rows={6} columns={4} /> ) : error ? ( <ErrorState message={error.message} onRetry={onRetry} /> + ) : filtered.length === 0 ? ( + <EmptyState heading="No projects match the current filters." /> ) : ( - <DataTable - columns={columns} - rows={filtered} - rowKey={(row) => row.id} - onRowClick={(row) => router.push(`/projects/${row.id}`)} - empty="No projects match the current filters." - /> + <div className="space-y-4"> + {filtered.map((project) => ( + <ProjectCard key={project.id} project={project} /> + ))} + </div> )} </div> ); diff --git a/web/src/mocks/handlers/allocations.ts b/web/src/mocks/handlers/allocations.ts index 328759a5f..43e9c1440 100644 --- a/web/src/mocks/handlers/allocations.ts +++ b/web/src/mocks/handlers/allocations.ts @@ -27,6 +27,7 @@ import { type ChangeRequest, allocationMembershipSchema, changeRequestSchema, + createAllocationPayloadSchema, createChangeRequestPayloadSchema, createMembershipPayloadSchema, updateChangeRequestPayloadSchema, @@ -42,6 +43,7 @@ import { } from "@/generated/core/zod.gen"; import { http, HttpResponse } from "msw"; import { z } from "zod"; +import { resources } from "./resources"; const byId = <T extends z.ZodType>(row: T) => z.record(z.string(), z.array(row)); @@ -89,6 +91,40 @@ export const allocationsHandlers = [ return HttpResponse.json({ items, total: matched.length }); }), + http.post("*/api/v1/compute-allocations", async ({ request }) => { + const payload = createAllocationPayloadSchema.parse(await request.json()); + const created: ComputeAllocation = { + ...payload, + id: `alloc-${Date.now()}-${allocations.length}`, + status: "ACTIVE", + posix_group: null, + group_provisioned_at: null, + }; + allocations.push(created); + return HttpResponse.json(created, { status: 201 }); + }), + + http.put<{ id: string }>( + "*/api/v1/compute-allocations/:id/resources", + async ({ params, request }) => { + const { resource_ids } = z + .object({ resource_ids: z.array(z.string()) }) + .parse(await request.json()); + resourcesByAlloc[String(params.id)] = resources.filter((r) => resource_ids.includes(r.id)); + return new HttpResponse(null, { status: 204 }); + }, + ), + + http.get<{ id: string }>("*/api/v1/compute-allocations/:id/usages/total", ({ params }) => + HttpResponse.json({ + compute_allocation_id: String(params.id), + total_su_amount: (usageByAlloc[String(params.id)] ?? []).reduce( + (n, u) => n + u.used_su_amount, + 0, + ), + }), + ), + http.get<{ id: string }>("*/api/v1/compute-allocations/:id", ({ params }) => { const id = String(params.id); const found = allocations.find((a) => a.id === id); diff --git a/web/src/mocks/handlers/resources.ts b/web/src/mocks/handlers/resources.ts index 34cc99d57..dfe5ff651 100644 --- a/web/src/mocks/handlers/resources.ts +++ b/web/src/mocks/handlers/resources.ts @@ -26,7 +26,7 @@ import { import { http, HttpResponse } from "msw"; import { z } from "zod"; -const resources = z.array(zComputeAllocationResource).parse(resourcesFixture); +export const resources = z.array(zComputeAllocationResource).parse(resourcesFixture); const rates = z.array(zComputeAllocationResourceRate).parse(ratesFixture); function ratesFor(resourceId: string): ComputeAllocationResourceRate[] { diff --git a/web/src/shared/hooks/useShallowSearchParams.ts b/web/src/shared/hooks/useShallowSearchParams.ts index 163570800..224933822 100644 --- a/web/src/shared/hooks/useShallowSearchParams.ts +++ b/web/src/shared/hooks/useShallowSearchParams.ts @@ -37,13 +37,12 @@ function readCurrent(): URLSearchParams { * shallow setter via a custom event. */ export function useShallowSearchParams(): URLSearchParams { - const nextParams = useNextSearchParams(); - const [params, setParams] = React.useState<URLSearchParams>( - () => new URLSearchParams(nextParams?.toString() ?? ""), - ); + const nextQuery = useNextSearchParams()?.toString() ?? ""; + const [params, setParams] = React.useState<URLSearchParams>(() => new URLSearchParams(nextQuery)); + // Next navigations, such as a Link to the same page with another query, bypass the shallow event. + React.useEffect(() => setParams(new URLSearchParams(nextQuery)), [nextQuery]); React.useEffect(() => { const sync = () => setParams(readCurrent()); - sync(); window.addEventListener(SHALLOW_EVENT, sync); window.addEventListener("popstate", sync); return () => { diff --git a/web/src/shared/layout/Sidebar.tsx b/web/src/shared/layout/Sidebar.tsx index 90772f268..58fb9682f 100644 --- a/web/src/shared/layout/Sidebar.tsx +++ b/web/src/shared/layout/Sidebar.tsx @@ -20,6 +20,7 @@ import { cn } from "@/lib/utils"; import { brand } from "@/shared/brand"; import { useAbility } from "@/shared/casl/AbilityProvider"; +import { useShallowSearchParams } from "@/shared/hooks/useShallowSearchParams"; import Link from "next/link"; import { usePathname } from "next/navigation"; import { NAV_GROUP_LABELS, type NavGroup, type NavItem, portalNav } from "./nav"; @@ -72,7 +73,7 @@ function isActive(pathname: string, href: string): boolean { function SidebarLink({ item, active }: { item: NavItem; active: boolean }) { const Icon = item.icon; - return ( + const link = ( <Link href={item.href} aria-current={active ? "page" : undefined} @@ -88,4 +89,43 @@ function SidebarLink({ item, active }: { item: NavItem; active: boolean }) { {active && <span className="absolute top-2 right-0 bottom-2 w-1 rounded-l-full bg-brand" />} </Link> ); + if (!item.children) return link; + return ( + <> + {link} + <SidebarChildren items={item.children} /> + </> + ); +} + +// Sub-links that narrow their parent by query; a child is active while the URL carries its query. +function SidebarChildren({ items }: { items: NonNullable<NavItem["children"]> }) { + const pathname = usePathname(); + const params = useShallowSearchParams(); + return ( + <ul className="mb-1 ml-[2.125rem] list-disc pl-6"> + {items.map((child) => { + const [path, query] = child.href.split("?"); + const active = + pathname === path && + [...new URLSearchParams(query)].every(([key, value]) => params.get(key) === value); + return ( + <li key={child.href} className={child.marker}> + <Link + href={child.href} + aria-current={active ? "page" : undefined} + className={cn( + "block py-1 text-sm", + active + ? "font-semibold text-foreground" + : "text-muted-foreground hover:text-foreground", + )} + > + {child.label} + </Link> + </li> + ); + })} + </ul> + ); } diff --git a/web/src/shared/layout/__tests__/Sidebar.test.tsx b/web/src/shared/layout/__tests__/Sidebar.test.tsx index 76f46f5e2..713b87a50 100644 --- a/web/src/shared/layout/__tests__/Sidebar.test.tsx +++ b/web/src/shared/layout/__tests__/Sidebar.test.tsx @@ -29,6 +29,7 @@ vi.mock("@/shared/casl/AbilityProvider", () => ({ vi.mock("next/navigation", () => ({ usePathname: () => "/", + useSearchParams: () => new URLSearchParams(), })); const NEW_ADMIN_LABELS = ["Organizations", "Resources"]; diff --git a/web/src/shared/layout/nav.ts b/web/src/shared/layout/nav.ts index 90f035254..e9dc58d97 100644 --- a/web/src/shared/layout/nav.ts +++ b/web/src/shared/layout/nav.ts @@ -26,7 +26,6 @@ import { type LucideIcon, ScrollText, Send, - Server, UserCog, } from "lucide-react"; @@ -39,6 +38,7 @@ export type NavItem = { label: string; icon: LucideIcon; group: NavGroup; + children?: Array<{ href: string; label: string; marker: string }>; ability?: AbilityCheck; }; @@ -50,17 +50,28 @@ export const NAV_GROUP_LABELS: Record<NavGroup, string> = { export const portalNav: NavItem[] = [ // No ability gates on this group: the backend scopes these reads to the // caller's own memberships. - { - href: "/allocations", - label: "Allocations", - icon: Server, - group: "allocations", - }, { href: "/projects", label: "Projects", icon: FolderKanban, group: "allocations", + children: [ + { + href: "/projects?origination=ACCESS", + label: "ACCESS", + marker: "marker:text-custos-blue-500", + }, + { + href: "/projects?origination=NAIRR", + label: "NAIRR", + marker: "marker:text-custos-green-600", + }, + { + href: "/projects?origination=internal", + label: "Internal", + marker: "marker:text-custos-amber-600", + }, + ], }, { href: "/analytics", diff --git a/web/tests/agreement-gates.e2e.ts b/web/tests/agreement-gates.e2e.ts index c238aa396..e74124f2e 100644 --- a/web/tests/agreement-gates.e2e.ts +++ b/web/tests/agreement-gates.e2e.ts @@ -22,7 +22,7 @@ test.describe("agreement gates", () => { // Checks that a first sign-in sees the setup page with the suggested username instead of the portal. test("shows the onboarding page", async ({ page }) => { await signInAs(page, "researcher", "onboarding"); - await page.goto("/allocations"); + await page.goto("/projects"); await expect(page.getByRole("heading", { name: "Set up your account" })).toBeVisible({ timeout: 20_000, @@ -33,7 +33,7 @@ test.describe("agreement gates", () => { // Checks that a user with a newer version pending sees the policy update page. test("shows the policy update page", async ({ page }) => { await signInAs(page, "researcher", "consent"); - await page.goto("/allocations"); + await page.goto("/projects"); await expect(page.getByRole("heading", { name: "Accept the updated agreement" })).toBeVisible({ timeout: 20_000, diff --git a/web/tests/allocation-members-edit.e2e.ts b/web/tests/allocation-members-edit.e2e.ts index 2d0ec5194..3d7fa44bc 100644 --- a/web/tests/allocation-members-edit.e2e.ts +++ b/web/tests/allocation-members-edit.e2e.ts @@ -21,7 +21,7 @@ import { signInAs } from "./fixtures/auth"; test.describe("allocation members tab", () => { test("admin adds, edits, and removes a member", async ({ page }) => { await signInAs(page, "admin"); - await page.goto("/allocations/alloc-002"); + await page.goto("/projects/project-001/alloc-002"); await expect( page.getByRole("heading", { name: /Genomic Sequencing - CPU Pool/i }), ).toBeVisible(); diff --git a/web/tests/allocations-detail.e2e.ts b/web/tests/allocations-detail.e2e.ts index 7b09c2a3c..3aea303f1 100644 --- a/web/tests/allocations-detail.e2e.ts +++ b/web/tests/allocations-detail.e2e.ts @@ -23,6 +23,7 @@ test.describe("allocation detail", () => { test("renders header and tabs", async ({ page }) => { await signInAs(page, "admin"); await page.goto("/allocations/alloc-001"); + await expect(page).toHaveURL(/\/projects\/project-001\/alloc-001$/); await expect( page.getByRole("heading", { name: /Genomic Sequencing - GPU Pool/i }), ).toBeVisible(); @@ -46,7 +47,7 @@ test.describe("allocation detail", () => { test("axe sweep on allocation detail", async ({ page }) => { await signInAs(page, "admin"); - await page.goto("/allocations/alloc-001"); + await page.goto("/projects/project-001/alloc-001"); await expect( page.getByRole("heading", { name: /Genomic Sequencing - GPU Pool/i }), ).toBeVisible(); diff --git a/web/tests/allocations-list.e2e.ts b/web/tests/allocations-list.e2e.ts deleted file mode 100644 index c3bc94073..000000000 --- a/web/tests/allocations-list.e2e.ts +++ /dev/null @@ -1,61 +0,0 @@ -// 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 AxeBuilder from "@axe-core/playwright"; -import { expect, test } from "@playwright/test"; -import { signInAs } from "./fixtures/auth"; - -test.describe("allocations list", () => { - test("renders the list and navigates to a detail page", async ({ page }) => { - await signInAs(page, "admin"); - await page.goto("/allocations"); - await expect(page.getByRole("heading", { name: /^Allocations$/ })).toBeVisible(); - - const firstRow = page.locator('a[href^="/allocations/alloc-"]').first(); - await expect(firstRow).toBeVisible({ timeout: 15_000 }); - await firstRow.click(); - await expect(page).toHaveURL(/\/allocations\/alloc-/); - }); - - // Make sure a user with no privileges can open their allocations. - test("a user with no privileges sees the allocations list", async ({ page }) => { - await signInAs(page, "researcher"); - await page.goto("/allocations"); - await expect(page.getByRole("heading", { name: /^Allocations$/ })).toBeVisible(); - await expect(page.locator('a[href^="/allocations/alloc-"]').first()).toBeVisible({ - timeout: 15_000, - }); - }); - - test("status filter updates URL state", async ({ page }) => { - await signInAs(page, "admin"); - await page.goto("/allocations"); - await page.getByLabel(/filter by status/i).selectOption("INACTIVE"); - await expect(page).toHaveURL(/[?&]status=INACTIVE/); - }); - - test("axe sweep on allocations list", async ({ page }) => { - await signInAs(page, "admin"); - await page.goto("/allocations"); - await expect(page.getByRole("heading", { name: /^Allocations$/ })).toBeVisible(); - const results = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa"]).analyze(); - const blocking = results.violations.filter( - (v) => v.impact === "serious" || v.impact === "critical", - ); - expect(blocking, JSON.stringify(blocking, null, 2)).toEqual([]); - }); -}); diff --git a/web/tests/baseline-live.spec.ts b/web/tests/baseline-live.spec.ts index 67b6e5a59..cbbd206a0 100644 --- a/web/tests/baseline-live.spec.ts +++ b/web/tests/baseline-live.spec.ts @@ -105,7 +105,7 @@ test.describe("baseline live walk", () => { test("allocations: 2 baseline allocations render", async ({ page }) => { await signInAdmin(page); - await goto(page, "/allocations"); + await goto(page, "/projects"); await expect(page.getByRole("link", { name: "BL-001" }).first()).toBeVisible({ timeout: 15_000, }); @@ -114,9 +114,9 @@ test.describe("baseline live walk", () => { test("allocation detail: Overview shows BL-001 with ACTIVE status", async ({ page }) => { await signInAdmin(page); - await goto(page, "/allocations"); + await goto(page, "/projects"); await page.getByRole("link", { name: "BL-001" }).first().click(); - await expect(page).toHaveURL(/\/allocations\/[a-f0-9-]+/); + await expect(page).toHaveURL(/\/projects\/[a-f0-9-]+\/[a-f0-9-]+/); await expect(page.getByRole("heading", { name: /BL-001/ })).toBeVisible(); await expect(page.getByText(/ACTIVE/i).first()).toBeVisible(); }); @@ -125,7 +125,7 @@ test.describe("baseline live walk", () => { page, }) => { await signInAdmin(page); - await goto(page, "/allocations"); + await goto(page, "/projects"); await page.getByRole("link", { name: "BL-001" }).first().click(); await page.getByRole("tab", { name: /members/i }).click(); // Baseline produces exactly one ACTIVE membership for the survivor (Pat). @@ -137,7 +137,7 @@ test.describe("baseline live walk", () => { page, }) => { await signInAdmin(page); - await goto(page, "/allocations"); + await goto(page, "/projects"); await page.getByRole("link", { name: "BL-001" }).first().click(); await page.getByRole("tab", { name: /change requests/i }).click(); await expect(page.getByText(/1 request/i)).toBeVisible({ timeout: 15_000 }); @@ -146,7 +146,7 @@ test.describe("baseline live walk", () => { test("allocation usage tab: BL-001 has at least one usage row from seed", async ({ page }) => { await signInAdmin(page); - await goto(page, "/allocations"); + await goto(page, "/projects"); await page.getByRole("link", { name: "BL-001" }).first().click(); await page.getByRole("tab", { name: /usage/i }).click(); await expect(page.getByText(/No usage data/i)).toHaveCount(0, { timeout: 15_000 }); diff --git a/web/tests/change-requests-submit.e2e.ts b/web/tests/change-requests-submit.e2e.ts index 49ce42cf4..2489b1d9e 100644 --- a/web/tests/change-requests-submit.e2e.ts +++ b/web/tests/change-requests-submit.e2e.ts @@ -21,7 +21,7 @@ import { signInAs } from "./fixtures/auth"; test.describe("change request submit", () => { test("PI persona opens drawer, fills, submits", async ({ page }) => { await signInAs(page, "manager"); - await page.goto("/allocations/alloc-001"); + await page.goto("/projects/project-001/alloc-001"); await expect( page.getByRole("heading", { name: /Genomic Sequencing - GPU Pool/i }), ).toBeVisible(); diff --git a/web/tests/closeout-live-walk.spec.ts b/web/tests/closeout-live-walk.spec.ts index 7f94beab9..55e1c0747 100644 --- a/web/tests/closeout-live-walk.spec.ts +++ b/web/tests/closeout-live-walk.spec.ts @@ -58,12 +58,6 @@ test.describe("closeout live walk", () => { await expect(page.getByRole("heading", { name: /^Projects$/ })).toBeVisible(); }); - test("allocations renders against live backend", async ({ page }) => { - await signInAdmin(page); - await gotoAndAssertNoRuntimeError(page, "/allocations"); - await expect(page.getByRole("heading", { name: /^Allocations$/ })).toBeVisible(); - }); - test("admin/traces renders against live backend (graceful empty/404)", async ({ page }) => { await signInAdmin(page); await gotoAndAssertNoRuntimeError(page, "/admin/traces"); diff --git a/web/tests/projects-list.e2e.ts b/web/tests/projects-list.e2e.ts index a36809555..5028c4bcd 100644 --- a/web/tests/projects-list.e2e.ts +++ b/web/tests/projects-list.e2e.ts @@ -31,6 +31,17 @@ test.describe("projects list", () => { await expect(page).toHaveURL(/\/projects\/project-/); }); + // Make sure a user with no privileges can open their allocations. + test("a user with no privileges sees their allocations", async ({ page }) => { + await signInAs(page, "researcher"); + await page.goto("/projects"); + await expect( + page.locator('a[href^="/projects/project-"][href*="/alloc-"]').first(), + ).toBeVisible({ + timeout: 15_000, + }); + }); + test("status filter updates URL state", async ({ page }) => { await signInAs(page, "admin"); await page.goto("/projects");
