From 91873e3d5935cfb872955b5ff465e2465baa5a71 Mon Sep 17 00:00:00 2001 From: Yasith Jayawardana Date: Sat, 21 Nov 2026 16:30:45 -0500 Subject: [PATCH] Deactivate members in the web UI --- .../__tests__/AllocationDetail.test.tsx | 63 +++++++++++++++++++ .../__tests__/AllocationMembersTab.test.tsx | 10 +-- .../core/allocations/__tests__/api.test.ts | 14 +++-- web/src/features/core/allocations/api.ts | 7 ++- .../components/AllocationDetail.tsx | 3 +- .../components/AllocationMembersTab.tsx | 18 +++--- web/src/features/core/allocations/queries.ts | 12 ++-- web/src/features/core/allocations/schemas.ts | 3 + .../__tests__/ProjectMembersTab.test.tsx | 17 ++++- .../projects/components/ProjectMembersTab.tsx | 12 ++-- web/src/mocks/handlers/allocations.ts | 21 +++---- web/tests/allocation-members-edit.e2e.ts | 10 +-- 12 files changed, 140 insertions(+), 50 deletions(-) create mode 100644 web/src/features/core/allocations/__tests__/AllocationDetail.test.tsx diff --git a/web/src/features/core/allocations/__tests__/AllocationDetail.test.tsx b/web/src/features/core/allocations/__tests__/AllocationDetail.test.tsx new file mode 100644 index 000000000..a793ca502 --- /dev/null +++ b/web/src/features/core/allocations/__tests__/AllocationDetail.test.tsx @@ -0,0 +1,63 @@ +// 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 { render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +const members = [ + { id: "m-1", membership_status: "ACTIVE" }, + { id: "m-2", membership_status: "INACTIVE" }, + { id: "m-3", membership_status: "ACTIVE" }, +]; + +vi.mock("@/shared/casl/permissions", () => ({ usePermissions: () => ({}), requires: () => "" })); +vi.mock("next-auth/react", () => ({ useSession: () => ({ data: null }) })); +vi.mock("@/shared/layout/BreadcrumbLabelsProvider", () => ({ useBreadcrumbLabel: vi.fn() })); +vi.mock("@/features/core/projects/queries", () => ({ useProject: () => ({ data: undefined }) })); +vi.mock("@/shared/ui/ConfirmDialog", async (importOriginal) => ({ + ...(await importOriginal()), + DeleteButton: () => null, +})); +vi.mock("@/shared/ui/TabsRouter", () => ({ TabsRouter: () => null })); +vi.mock("../components/AllocationDetailHeader", () => ({ + AllocationDetailHeader: ({ memberCount }: { memberCount: number }) => ( +

{memberCount} members

+ ), +})); +vi.mock("../queries", async (importOriginal) => ({ + ...(await importOriginal()), + useAllocation: () => ({ + data: { id: "alloc-001", name: "Alpha" }, + isLoading: false, + error: null, + }), + useAllocationMembers: () => ({ data: members }), +})); + +import { AllocationDetail } from "../components/AllocationDetail"; + +describe("", () => { + it("counts active members only", () => { + render( + + + , + ); + expect(screen.getByText("2 members")).toBeInTheDocument(); + }); +}); diff --git a/web/src/features/core/allocations/__tests__/AllocationMembersTab.test.tsx b/web/src/features/core/allocations/__tests__/AllocationMembersTab.test.tsx index debe5e918..1c89e242e 100644 --- a/web/src/features/core/allocations/__tests__/AllocationMembersTab.test.tsx +++ b/web/src/features/core/allocations/__tests__/AllocationMembersTab.test.tsx @@ -56,7 +56,7 @@ vi.mock("@/features/core/users/components/UserDetailsDrawer", () => ({ vi.mock("../queries", () => ({ useAllocationMembers: () => ({ data: members, isLoading: false, error: null, refetch: vi.fn() }), useAddMember: () => mutation, - useRemoveMember: () => mutation, + useSetMemberStatus: () => mutation, })); vi.mock("@/features/core/projects/queries", () => ({ useUpdateProjectMember: () => mutation, @@ -81,16 +81,16 @@ const allocation: ComputeAllocation = { }; describe("", () => { - it("offers no Edit or Remove for PI or Co-PI members", () => { + it("offers no Edit or Deactivate for PI or Co-PI members", () => { render( , ); for (const name of ["Paula Ivey", "Carl Osei"]) { expect(screen.queryByRole("button", { name: `Edit ${name}` })).not.toBeInTheDocument(); - expect(screen.queryByRole("button", { name: `Remove ${name}` })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: `Deactivate ${name}` })).not.toBeInTheDocument(); } expect(screen.getByRole("button", { name: "Edit Mina Frey" })).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Remove Mina Frey" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Deactivate Mina Frey" })).toBeInTheDocument(); }); it("disables each action whose privilege is missing", () => { @@ -102,7 +102,7 @@ describe("", () => { canSearchUsers />, ); - expect(screen.getByRole("button", { name: "Remove Mina Frey" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Deactivate Mina Frey" })).toBeDisabled(); expect(screen.getByRole("button", { name: "Edit Mina Frey" })).toBeEnabled(); expect(screen.getByRole("button", { name: "+ Add member" })).toBeDisabled(); }); diff --git a/web/src/features/core/allocations/__tests__/api.test.ts b/web/src/features/core/allocations/__tests__/api.test.ts index be97e2036..af94d7440 100644 --- a/web/src/features/core/allocations/__tests__/api.test.ts +++ b/web/src/features/core/allocations/__tests__/api.test.ts @@ -28,7 +28,7 @@ import { listChangeRequestEvents, listChangeRequests, rejectChangeRequest, - removeMember, + setMemberStatus, submitChangeRequest, } from "../api"; @@ -177,11 +177,13 @@ describe("addMember", () => { }); }); -describe("removeMember", () => { - it("DELETEs the membership", async () => { - fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 })); - await removeMember("mem-001"); - expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("DELETE"); +describe("setMemberStatus", () => { + it("PUTs INACTIVE to deactivate the membership", async () => { + fetchMock.mockResolvedValueOnce(mockResponse(200, {})); + await setMemberStatus("mem-001", "INACTIVE"); + const [url, init] = fetchMock.mock.calls[0] ?? []; + expect(String(url)).toMatch(/\/compute-allocation-memberships\/mem-001\/status$/); + expect(init).toMatchObject({ method: "PUT", body: '{"membership_status":"INACTIVE"}' }); }); }); diff --git a/web/src/features/core/allocations/api.ts b/web/src/features/core/allocations/api.ts index 4589ddc5c..66f34223f 100644 --- a/web/src/features/core/allocations/api.ts +++ b/web/src/features/core/allocations/api.ts @@ -125,8 +125,11 @@ export async function addMember( return zPostComputeAllocationMembershipsResponse.parse(raw); } -export async function removeMember(id: string): Promise { - await apiFetch(`/compute-allocation-memberships/${id}`, { method: "DELETE" }); +export async function setMemberStatus(id: string, status: "ACTIVE" | "INACTIVE") { + await apiFetch(`/compute-allocation-memberships/${id}/status`, { + method: "PUT", + body: { membership_status: status }, + }); } export async function listChangeRequests( diff --git a/web/src/features/core/allocations/components/AllocationDetail.tsx b/web/src/features/core/allocations/components/AllocationDetail.tsx index 22c90d2e9..50c92ca17 100644 --- a/web/src/features/core/allocations/components/AllocationDetail.tsx +++ b/web/src/features/core/allocations/components/AllocationDetail.tsx @@ -26,6 +26,7 @@ import { CardSkeleton } from "@/shared/ui/Loading"; import { TabsRouter } from "@/shared/ui/TabsRouter"; import { useSession } from "next-auth/react"; import { useAllocation, useAllocationMembers, useDeleteAllocation } from "../queries"; +import { isActiveMembership } from "../schemas"; import { AllocationChangeRequestsTab } from "./AllocationChangeRequestsTab"; import { AllocationDetailHeader } from "./AllocationDetailHeader"; import { AllocationHistoryTab } from "./AllocationHistoryTab"; @@ -59,7 +60,7 @@ export function AllocationDetail({ allocationId }: AllocationDetailProps) { const allocation = allocationQuery.data; if (!allocation) return null; - const memberCount = membersQuery.data?.length ?? 0; + const memberCount = membersQuery.data?.filter(isActiveMembership).length ?? 0; return (
diff --git a/web/src/features/core/allocations/components/AllocationMembersTab.tsx b/web/src/features/core/allocations/components/AllocationMembersTab.tsx index 08220f184..aca7b2a25 100644 --- a/web/src/features/core/allocations/components/AllocationMembersTab.tsx +++ b/web/src/features/core/allocations/components/AllocationMembersTab.tsx @@ -29,12 +29,13 @@ import { StatusBadge } from "@/shared/ui/StatusBadge"; import { Avatar, AvatarFallback } from "@/shared/ui/avatar"; import * as React from "react"; import { toast } from "sonner"; -import { useAddMember, useAllocationMembers, useRemoveMember } from "../queries"; +import { useAddMember, useAllocationMembers, useSetMemberStatus } from "../queries"; import type { AllocationMembership, AllocationMembershipRole, CreateMembershipPayload, } from "../schemas"; +import { isActiveMembership } from "../schemas"; import { AddMemberDialog, type Role } from "./AddMemberDialog"; import { MemberEditDialog, type MemberEditPayload } from "./MemberEditDialog"; @@ -67,7 +68,7 @@ export function AllocationMembersTab({ const query = useAllocationMembers(allocation.id); const addMutation = useAddMember(allocation.id); const roleMutation = useUpdateProjectMember(allocation.project_id); - const removeMutation = useRemoveMember(allocation.id); + const statusMutation = useSetMemberStatus(allocation.id); const [editing, setEditing] = React.useState(null); const [viewing, setViewing] = React.useState(null); const [adding, setAdding] = React.useState(false); @@ -171,17 +172,20 @@ export function AllocationMembersTab({ Edit - removeMutation.mutate(row.id, { onError: (err) => toast.error(err.message) }) + statusMutation.mutate( + { id: row.id, status: isActiveMembership(row) ? "INACTIVE" : "ACTIVE" }, + { onError: (err) => toast.error(err.message) }, + ) } - aria-label={`Remove ${row.display_name ?? row.user_id}`} - disabled={removeMutation.isPending} + aria-label={`${isActiveMembership(row) ? "Deactivate" : "Reactivate"} ${row.display_name ?? row.user_id}`} + disabled={statusMutation.isPending} > - Remove + {isActiveMembership(row) ? "Deactivate" : "Reactivate"} ) : null, diff --git a/web/src/features/core/allocations/queries.ts b/web/src/features/core/allocations/queries.ts index 6745aff99..fd03eae9b 100644 --- a/web/src/features/core/allocations/queries.ts +++ b/web/src/features/core/allocations/queries.ts @@ -44,8 +44,8 @@ import { listChangeRequests, listUserMemberships, rejectChangeRequest, - removeMember, setAllocationResources, + setMemberStatus, submitChangeRequest, } from "./api"; import type { @@ -54,6 +54,7 @@ import type { CreateChangeRequestPayload, CreateMembershipPayload, } from "./schemas"; +import { isActiveMembership } from "./schemas"; import type { AllocationListParams, ChangeRequestListParams } from "./types"; export const allocationKeys = { @@ -199,10 +200,11 @@ export function useAddMember(allocationId: string) { }); } -export function useRemoveMember(allocationId: string) { +export function useSetMemberStatus(allocationId: string) { const client = useQueryClient(); return useMutation({ - mutationFn: (id: string) => removeMember(id), + mutationFn: ({ id, status }: { id: string; status: "ACTIVE" | "INACTIVE" }) => + setMemberStatus(id, status), onSuccess: () => invalidateMembers(client, allocationId), }); } @@ -224,7 +226,7 @@ export function useMembershipsByAllocation(allocationIds: string[]) { }); } -// Revokes access by deleting the membership, or grants it for the allocation's remaining term. +// Reactivates or deactivates an existing membership, or adds one for the allocation's remaining term. export function useToggleAllocationAccess() { const client = useQueryClient(); return useMutation({ @@ -238,7 +240,7 @@ export function useToggleAllocationAccess() { membership: AllocationMembership | undefined; }) => membership - ? removeMember(membership.id) + ? setMemberStatus(membership.id, isActiveMembership(membership) ? "INACTIVE" : "ACTIVE") : addMember({ compute_allocation_id: allocation.id, user_id: userId, diff --git a/web/src/features/core/allocations/schemas.ts b/web/src/features/core/allocations/schemas.ts index e291ba00e..d47960f6e 100644 --- a/web/src/features/core/allocations/schemas.ts +++ b/web/src/features/core/allocations/schemas.ts @@ -42,6 +42,9 @@ export const allocationMembershipSchema = zAllocationMembershipResponse.extend({ }); export type AllocationMembership = z.infer; +export const isActiveMembership = (m?: Pick) => + m?.membership_status === "ACTIVE"; + // ChangeStatus is a free-form string on the Go side; we narrow to the documented enum. export const changeRequestSchema = zComputeAllocationChangeRequest.extend({ change_status: changeRequestStatusSchema, diff --git a/web/src/features/core/projects/__tests__/ProjectMembersTab.test.tsx b/web/src/features/core/projects/__tests__/ProjectMembersTab.test.tsx index a8e088c6b..4e01e3a13 100644 --- a/web/src/features/core/projects/__tests__/ProjectMembersTab.test.tsx +++ b/web/src/features/core/projects/__tests__/ProjectMembersTab.test.tsx @@ -42,7 +42,18 @@ const allocations = [ { id: "a-1", name: "Alpha", end_time: "2027-01-01T00:00:00Z" }, { id: "a-2", name: "Beta", end_time: "2027-01-01T00:00:00Z" }, ]; -const ciraInAlpha = { id: "m-1", compute_allocation_id: "a-1", user_id: "u-3" }; +const ciraInAlpha = { + id: "m-1", + compute_allocation_id: "a-1", + user_id: "u-3", + membership_status: "ACTIVE", +}; +const ciraInBeta = { + id: "m-2", + compute_allocation_id: "a-2", + user_id: "u-3", + membership_status: "INACTIVE", +}; const roleMutation = { mutateAsync: vi.fn(async () => undefined), isPending: false }; const toggle = { mutateAsync: vi.fn(async () => undefined), isPending: false }; @@ -56,7 +67,7 @@ vi.mock("../queries", () => ({ vi.mock("@/features/core/allocations/queries", () => ({ useAllocationsByProject: () => ({ data: { items: allocations }, isLoading: false, error: null }), useMembershipsByAllocation: () => ({ - byAllocation: { "a-1": [ciraInAlpha], "a-2": [] }, + byAllocation: { "a-1": [ciraInAlpha], "a-2": [ciraInBeta] }, isLoading: false, error: null, }), @@ -109,7 +120,7 @@ describe("", () => { expect.objectContaining({ userId: "u-3", membership: ciraInAlpha }), ); expect(toggle.mutateAsync).toHaveBeenCalledWith( - expect.objectContaining({ userId: "u-3", membership: undefined }), + expect.objectContaining({ userId: "u-3", membership: ciraInBeta }), ); }); diff --git a/web/src/features/core/projects/components/ProjectMembersTab.tsx b/web/src/features/core/projects/components/ProjectMembersTab.tsx index 5a10d682f..a4516ace2 100644 --- a/web/src/features/core/projects/components/ProjectMembersTab.tsx +++ b/web/src/features/core/projects/components/ProjectMembersTab.tsx @@ -22,7 +22,7 @@ import { useMembershipsByAllocation, useToggleAllocationAccess, } from "@/features/core/allocations/queries"; -import type { AllocationMembership } from "@/features/core/allocations/schemas"; +import { type AllocationMembership, isActiveMembership } from "@/features/core/allocations/schemas"; import { UserDetailsDrawer } from "@/features/core/users/components/UserDetailsDrawer"; import { useUserEmailSearch } from "@/features/core/users/queries"; import type { ComputeAllocation, User } from "@/generated/core/zod.gen"; @@ -178,7 +178,7 @@ function describe(change: Change, changes: Change[]): string { }`; } if (change.kind === "role") return `${change.row.name}: role → ${ROLE_LABELS[change.to]}`; - return `${change.row.name}: ${change.membership ? "remove from" : "add to"} ${change.allocation.name}`; + return `${change.row.name}: ${isActiveMembership(change.membership) ? "remove from" : "add to"} ${change.allocation.name}`; } export function ProjectMembersTab({ @@ -240,10 +240,12 @@ export function ProjectMembersTab({ ]; const membershipOf = (allocationId: string, userId: string) => memberships.byAllocation[allocationId]?.find((m) => m.user_id === userId); + const hasActiveMembership = (allocationId: string, userId: string) => + isActiveMembership(membershipOf(allocationId, userId)); const accessKey = (allocationId: string, userId: string) => `${allocationId}:${userId}`; const roleOf = (row: GridRow) => draft.roles[row.userId] ?? row.role; const hasAccess = (allocationId: string, userId: string) => - draft.access[accessKey(allocationId, userId)] ?? Boolean(membershipOf(allocationId, userId)); + draft.access[accessKey(allocationId, userId)] ?? hasActiveMembership(allocationId, userId); const isNew = (row: GridRow) => draft.added.some((a) => a.userId === row.userId); const changes: Change[] = rows.flatMap((row) => [ @@ -252,7 +254,7 @@ export function ProjectMembersTab({ : []), ...allocations.flatMap((allocation) => { const membership = membershipOf(allocation.id, row.userId); - return hasAccess(allocation.id, row.userId) !== Boolean(membership) + return hasAccess(allocation.id, row.userId) !== isActiveMembership(membership) ? [{ kind: "access" as const, row, allocation, membership }] : []; }), @@ -388,7 +390,7 @@ export function ProjectMembersTab({ {allocations.map((a) => { const checked = hasAccess(a.id, row.userId); - const changed = checked !== Boolean(membershipOf(a.id, row.userId)); + const changed = checked !== hasActiveMembership(a.id, row.userId); const label = `${row.name} in ${a.name}`; return ( ("*/api/v1/compute-allocation-memberships/:id", ({ params }) => { - const id = String(params.id); - for (const bucket of Object.values(membersByAlloc)) { - const idx = bucket.findIndex((m) => m.id === id); - if (idx !== -1) { - bucket.splice(idx, 1); - return new HttpResponse(null, { status: 204 }); - } - } - return HttpResponse.json({ error: "membership not found" }, { status: 404 }); - }), + http.put<{ id: string }, Pick>( + "*/api/v1/compute-allocation-memberships/:id/status", + async ({ params, request }) => { + const all = Object.values(membersByAlloc).flat(); + const member = all.find((m) => m.id === String(params.id)); + if (!member) return HttpResponse.json({ error: "membership not found" }, { status: 404 }); + member.membership_status = (await request.json()).membership_status; + return HttpResponse.json(member); + }, + ), http.get<{ id: string }>("*/api/v1/compute-allocations/:id/change-requests", ({ params }) => { const id = String(params.id); diff --git a/web/tests/allocation-members-edit.e2e.ts b/web/tests/allocation-members-edit.e2e.ts index 3d7fa44bc..c0bbe212c 100644 --- a/web/tests/allocation-members-edit.e2e.ts +++ b/web/tests/allocation-members-edit.e2e.ts @@ -45,13 +45,13 @@ test.describe("allocation members tab", () => { timeout: 15_000, }); - // Remove - const removeButtons = page.getByRole("button", { name: /^remove /i }); - const initialCount = await removeButtons.count(); + // Deactivate + const deactivateButtons = page.getByRole("button", { name: /^deactivate /i }); + const initialCount = await deactivateButtons.count(); expect(initialCount).toBeGreaterThan(0); - await removeButtons.first().click(); + await deactivateButtons.first().click(); await expect - .poll(async () => removeButtons.count(), { timeout: 15_000 }) + .poll(async () => deactivateButtons.count(), { timeout: 15_000 }) .toBeLessThan(initialCount); }); });