Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<typeof import("@/shared/ui/ConfirmDialog")>()),
DeleteButton: () => null,
}));
vi.mock("@/shared/ui/TabsRouter", () => ({ TabsRouter: () => null }));
vi.mock("../components/AllocationDetailHeader", () => ({
AllocationDetailHeader: ({ memberCount }: { memberCount: number }) => (
<p>{memberCount} members</p>
),
}));
vi.mock("../queries", async (importOriginal) => ({
...(await importOriginal<typeof import("../queries")>()),
useAllocation: () => ({
data: { id: "alloc-001", name: "Alpha" },
isLoading: false,
error: null,
}),
useAllocationMembers: () => ({ data: members }),
}));

import { AllocationDetail } from "../components/AllocationDetail";

describe("<AllocationDetail />", () => {
it("counts active members only", () => {
render(
<QueryClientProvider client={new QueryClient()}>
<AllocationDetail allocationId="alloc-001" />
</QueryClientProvider>,
);
expect(screen.getByText("2 members")).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -81,16 +81,16 @@ const allocation: ComputeAllocation = {
};

describe("<AllocationMembersTab />", () => {
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(
<AllocationMembersTab allocation={allocation} canEditAccess canEditRoles canSearchUsers />,
);
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", () => {
Expand All @@ -102,7 +102,7 @@ describe("<AllocationMembersTab />", () => {
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();
});
Expand Down
14 changes: 8 additions & 6 deletions web/src/features/core/allocations/__tests__/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
listChangeRequestEvents,
listChangeRequests,
rejectChangeRequest,
removeMember,
setMemberStatus,
submitChangeRequest,
} from "../api";

Expand Down Expand Up @@ -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"}' });
});
});

Expand Down
7 changes: 5 additions & 2 deletions web/src/features/core/allocations/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,11 @@ export async function addMember(
return zPostComputeAllocationMembershipsResponse.parse(raw);
}

export async function removeMember(id: string): Promise<void> {
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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 (
<section className="space-y-6">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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<AllocationMembership | null>(null);
const [viewing, setViewing] = React.useState<string | null>(null);
const [adding, setAdding] = React.useState(false);
Expand Down Expand Up @@ -171,17 +172,20 @@ export function AllocationMembersTab({
Edit
</GuardedButton>
<GuardedButton
variant="destructive"
variant={isActiveMembership(row) ? "destructive" : "outline"}
size="sm"
allowed={canEditAccess}
reason={requires("allocationsWrite")}
onClick={() =>
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"}
</GuardedButton>
</div>
) : null,
Expand Down
12 changes: 7 additions & 5 deletions web/src/features/core/allocations/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ import {
listChangeRequests,
listUserMemberships,
rejectChangeRequest,
removeMember,
setAllocationResources,
setMemberStatus,
submitChangeRequest,
} from "./api";
import type {
Expand All @@ -54,6 +54,7 @@ import type {
CreateChangeRequestPayload,
CreateMembershipPayload,
} from "./schemas";
import { isActiveMembership } from "./schemas";
import type { AllocationListParams, ChangeRequestListParams } from "./types";

export const allocationKeys = {
Expand Down Expand Up @@ -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),
});
}
Expand All @@ -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({
Expand All @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions web/src/features/core/allocations/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ export const allocationMembershipSchema = zAllocationMembershipResponse.extend({
});
export type AllocationMembership = z.infer<typeof allocationMembershipSchema>;

export const isActiveMembership = (m?: Pick<AllocationMembership, "membership_status">) =>
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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand All @@ -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,
}),
Expand Down Expand Up @@ -109,7 +120,7 @@ describe("<ProjectMembersTab />", () => {
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 }),
);
});

Expand Down
12 changes: 7 additions & 5 deletions web/src/features/core/projects/components/ProjectMembersTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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) => [
Expand All @@ -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 }]
: [];
}),
Expand Down Expand Up @@ -388,7 +390,7 @@ export function ProjectMembersTab({
</TableCell>
{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 (
<TableCell
Expand Down
21 changes: 10 additions & 11 deletions web/src/mocks/handlers/allocations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,17 +179,16 @@ export const allocationsHandlers = [
return HttpResponse.json(member, { status: 201 });
}),

http.delete<{ id: string }>("*/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<AllocationMembership, "membership_status">>(
"*/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);
Expand Down
Loading