Skip to content

Commit e045707

Browse files
authored
feat(admin): list and remove pending invites from organization members (#1862)
1 parent 562e230 commit e045707

7 files changed

Lines changed: 561 additions & 53 deletions

File tree

‎web/sdk/admin/hooks/useOrganizationRoles.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,21 @@ import {
88
} from "@raystack/proton/frontier";
99
import { SCOPES } from "~/admin/utils/constants";
1010

11+
interface UseOrganizationRolesOptions {
12+
/** Skip both fetches while false. Defaults to true. */
13+
enabled?: boolean;
14+
}
15+
1116
/*
1217
Roles assignable within an org: the platform's defaults plus the org's custom
1318
ones. Both halves are needed — a role id can come from either.
1419
- react-query caches per key, so repeat callers share one fetch
1520
- pass undefined/empty to skip the org-scoped half
1621
*/
17-
export const useOrganizationRoles = (orgId?: string) => {
22+
export const useOrganizationRoles = (
23+
orgId?: string,
24+
{ enabled = true }: UseOrganizationRolesOptions = {},
25+
) => {
1826
const {
1927
data: defaultRoles = [],
2028
isLoading: isDefaultRolesLoading,
@@ -23,6 +31,7 @@ export const useOrganizationRoles = (orgId?: string) => {
2331
FrontierServiceQueries.listRoles,
2432
create(ListRolesRequestSchema, { scopes: [SCOPES.ORG] }),
2533
{
34+
enabled,
2635
select: (data) => data?.roles || [],
2736
},
2837
);
@@ -38,7 +47,7 @@ export const useOrganizationRoles = (orgId?: string) => {
3847
scopes: [SCOPES.ORG],
3948
}),
4049
{
41-
enabled: !!orgId,
50+
enabled: enabled && !!orgId,
4251
select: (data) => data?.roles || [],
4352
},
4453
);

‎web/sdk/admin/views/organizations/details/index.tsx‎

Lines changed: 6 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ import { useQueryClient } from "@tanstack/react-query";
88
import { create } from "@bufbuild/protobuf";
99

1010
import { OrganizationDetailsLayout } from "./layout";
11-
import { ORG_NAMESPACE } from "./types";
1211
import { OrganizationContext } from "./contexts/organization-context";
12+
import { useOrganizationRoles } from "~/admin/hooks/useOrganizationRoles";
1313
import {
1414
FrontierServiceQueries,
1515
GetBillingAccountRequestSchema,
@@ -112,36 +112,12 @@ export const OrganizationDetailsView = ({
112112
);
113113
}
114114

115-
// Fetch default roles
116-
const {
117-
data: defaultRoles = [],
118-
isLoading: isDefaultRolesLoading,
119-
error: defaultRolesError,
120-
} = useQuery(
121-
FrontierServiceQueries.listRoles,
122-
{ scopes: [ORG_NAMESPACE] },
123-
{
124-
enabled: !!organizationId,
125-
select: (data) => data?.roles || [],
126-
},
115+
// Fetch roles assignable in this org (platform defaults + org custom)
116+
const { roles, isLoading: isRolesLoading } = useOrganizationRoles(
117+
organizationId,
118+
{ enabled: !!organizationId },
127119
);
128120

129-
// Fetch organization-specific roles
130-
const {
131-
data: organizationRoles = [],
132-
isLoading: isOrgRolesLoading,
133-
error: orgRolesError,
134-
} = useQuery(
135-
FrontierServiceQueries.listOrganizationRoles,
136-
{ orgId: organizationId || "", scopes: [ORG_NAMESPACE] },
137-
{
138-
enabled: !!organizationId,
139-
select: (data) => data?.roles || [],
140-
},
141-
);
142-
143-
const roles = [...defaultRoles, ...organizationRoles];
144-
145121
// Fetch organization members
146122
const {
147123
data: orgMembersMap = {},
@@ -226,12 +202,6 @@ export const OrganizationDetailsView = ({
226202
if (kycError) {
227203
console.error("Failed to fetch KYC details:", kycError);
228204
}
229-
if (defaultRolesError) {
230-
console.error("Failed to fetch default roles:", defaultRolesError);
231-
}
232-
if (orgRolesError) {
233-
console.error("Failed to fetch organization roles:", orgRolesError);
234-
}
235205
if (orgMembersError) {
236206
console.error("Failed to fetch organization members:", orgMembersError);
237207
}
@@ -250,19 +220,14 @@ export const OrganizationDetailsView = ({
250220
}, [
251221
organizationError,
252222
kycError,
253-
defaultRolesError,
254-
orgRolesError,
255223
orgMembersError,
256224
billingAccountsError,
257225
billingAccountError,
258226
tokenBalanceError,
259227
]);
260228

261229
const isLoading =
262-
isOrganizationLoading ||
263-
isDefaultRolesLoading ||
264-
isOrgRolesLoading ||
265-
isBillingAccountLoading;
230+
isOrganizationLoading || isRolesLoading || isBillingAccountLoading;
266231
return (
267232
<OrganizationContext.Provider
268233
value={{

‎web/sdk/admin/views/organizations/details/members/index.tsx‎

Lines changed: 88 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
1-
import { AlertDialog, DataTable, EmptyState, Flex } from "@raystack/apsara";
1+
import { AlertDialog, Button, DataTable, EmptyState, Flex } from "@raystack/apsara";
22
import type { DataTableQuery, DataTableSort } from "@raystack/apsara";
33
import { PageTitle } from "~/admin/components/PageTitle";
44
import styles from "./members.module.css";
55
import { useContext, useEffect, useMemo, useState } from "react";
66
import { getColumns } from "./columns";
7-
import type { SearchOrganizationUsersResponse_OrganizationUser } from "@raystack/proton/frontier";
8-
import { AdminServiceQueries } from "@raystack/proton/frontier";
7+
import type {
8+
Invitation,
9+
SearchOrganizationUsersResponse_OrganizationUser,
10+
} from "@raystack/proton/frontier";
11+
import {
12+
AdminServiceQueries,
13+
FrontierServiceQueries,
14+
ListOrganizationInvitationsRequestSchema,
15+
} from "@raystack/proton/frontier";
16+
import { create } from "@bufbuild/protobuf";
917
import {
1018
useInfiniteQuery,
19+
useQuery,
1120
createConnectQueryKey,
1221
useTransport
1322
} from '@connectrpc/connect-query';
@@ -24,9 +33,13 @@ import {
2433
import { transformDataTableQueryToRQLRequest } from '~/utils/transform-query';
2534
import { useDebouncedValue } from '~hooks';
2635
import { useTerminology } from "~/admin/hooks/useTerminology";
36+
import { InvitedMembersDialog } from './invited-members-dialog';
2737

2838
const updateRoleDialogHandle = AlertDialog.createHandle<UpdateRolePayload>();
2939

40+
// Stable ref: a fresh [] each render would remount the invites table.
41+
const NO_INVITATIONS: Invitation[] = [];
42+
3043
const DEFAULT_SORT: DataTableSort = { name: 'orgJoinedAt', order: 'desc' };
3144
const INITIAL_QUERY: DataTableQuery = {
3245
offset: 0,
@@ -103,6 +116,24 @@ export function OrganizationMembersView() {
103116
user: SearchOrganizationUsersResponse_OrganizationUser | null;
104117
}>({ isOpen: false, user: null });
105118

119+
const [isInvitesDialogOpen, setIsInvitesDialogOpen] = useState(false);
120+
121+
// Not in the dialog: the toolbar needs the count before it mounts.
122+
const {
123+
data: invitations = NO_INVITATIONS,
124+
isLoading: isInvitationsLoading,
125+
error: invitationsError,
126+
} = useQuery(
127+
FrontierServiceQueries.listOrganizationInvitations,
128+
create(ListOrganizationInvitationsRequestSchema, {
129+
orgId: organizationId,
130+
}),
131+
{
132+
enabled: !!organizationId,
133+
select: data => data?.invitations || NO_INVITATIONS,
134+
},
135+
);
136+
106137
const title = `${t.member({ plural: true, case: "capital" })} | ${organization?.title} | ${t.organization({ plural: true, case: "capital" })}`;
107138

108139
const [tableQuery, setTableQuery] = useState<DataTableQuery>(INITIAL_QUERY);
@@ -155,6 +186,16 @@ export function OrganizationMembersView() {
155186
const showZeroState =
156187
!isLoading && !isError && !hasActiveQuery && data.length === 0;
157188

189+
// DataTable.Toolbar's own rule: hidden in the zero state.
190+
const showToolbar = data.length > 0 || Boolean(tableQuery.filters?.length);
191+
/*
192+
* - an org always has at least one member, so the toolbar-less branch below
193+
* is a safeguard, not a state to expect
194+
* - the trigger is the count: a failed fetch leaves nothing to label, so it
195+
* stays hidden and only logs
196+
*/
197+
const showInvitesBtn = invitations.length > 0;
198+
158199
const onTableQueryChange = (newQuery: DataTableQuery) => {
159200
setTableQuery(newQuery);
160201
};
@@ -165,6 +206,15 @@ export function OrganizationMembersView() {
165206
}
166207
};
167208

209+
useEffect(() => {
210+
if (invitationsError) {
211+
console.error(
212+
"Failed to fetch organization invitations:",
213+
invitationsError,
214+
);
215+
}
216+
}, [invitationsError]);
217+
168218
useEffect(() => {
169219
setSearchVisibility(true);
170220
return () => {
@@ -230,6 +280,15 @@ export function OrganizationMembersView() {
230280
onClose={closeRemoveMemberDialog}
231281
/>
232282
) : null}
283+
284+
{isInvitesDialogOpen ? (
285+
<InvitedMembersDialog
286+
organizationId={organizationId}
287+
invitations={invitations}
288+
isLoading={isInvitationsLoading}
289+
onClose={() => setIsInvitesDialogOpen(false)}
290+
/>
291+
) : null}
233292
<Flex justify="center" className={styles["container"]}>
234293
<PageTitle title={title} />
235294
<DataTable
@@ -242,7 +301,32 @@ export function OrganizationMembersView() {
242301
onLoadMore={fetchMore}
243302
query={tableQuery}>
244303
<Flex direction="column" style={{ width: "100%" }}>
245-
<DataTable.Toolbar />
304+
{/* DataTable.Toolbar takes no children, so the row is rebuilt from
305+
its parts to seat the invites trigger left of Display. */}
306+
{(showToolbar || showInvitesBtn) && (
307+
<Flex
308+
justify={showToolbar ? "between" : "end"}
309+
align="start"
310+
gap={3}
311+
className={styles["toolbar"]}>
312+
{showToolbar && <DataTable.Filters />}
313+
<Flex align="center" gap={3}>
314+
{showInvitesBtn && (
315+
<Button
316+
variant="text"
317+
color="neutral"
318+
size="small"
319+
onClick={() => setIsInvitesDialogOpen(true)}
320+
data-test-id="admin-org-members-invites">
321+
{/* Expired invites come back too, so "Pending" would
322+
overstate the count — Status labels each row. */}
323+
{`${invitations.length} Invite${invitations.length === 1 ? "" : "s"}`}
324+
</Button>
325+
)}
326+
{showToolbar && <DataTable.DisplayControls />}
327+
</Flex>
328+
</Flex>
329+
)}
246330
<DataTable.Content
247331
emptyState={showZeroState ? <ZeroState /> : isError ? <ErrorState /> : <NoMembers />}
248332
classNames={{
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import {
2+
AlertDialog,
3+
IconButton,
4+
Menu,
5+
type DataTableColumnDef,
6+
} from "@raystack/apsara";
7+
import { DotsHorizontalIcon } from "@radix-ui/react-icons";
8+
import type { Invitation } from "@raystack/proton/frontier";
9+
import { DeleteIcon } from "~/admin/assets/icons/DeleteIcon";
10+
import {
11+
formatInviteExpiry,
12+
formatTimestamp,
13+
type TimeStamp,
14+
} from "~/admin/utils/connect-timestamp";
15+
import type { RemoveInvitePayload } from "./remove-invite-dialog";
16+
import styles from "./members.module.css";
17+
18+
interface GetColumnsOptions {
19+
/** Role id → title, from useOrganizationRoles. */
20+
roleTitleById: Map<string, string>;
21+
removeInviteHandle: ReturnType<
22+
typeof AlertDialog.createHandle<RemoveInvitePayload>
23+
>;
24+
}
25+
26+
const seconds = (timestamp?: TimeStamp) => Number(timestamp?.seconds ?? 0);
27+
28+
export const getInvitedMembersColumns = ({
29+
roleTitleById,
30+
removeInviteHandle,
31+
}: GetColumnsOptions): DataTableColumnDef<Invitation, unknown>[] => [
32+
{
33+
// Invitations carry no user record — user_id is the invited email.
34+
accessorKey: "userId",
35+
header: "Email",
36+
classNames: {
37+
header: styles["invites-email-column"],
38+
cell: styles["invites-email-column"],
39+
},
40+
cell: ({ getValue }) => (getValue() as string) || "-",
41+
enableSorting: true,
42+
},
43+
{
44+
accessorKey: "roleIds",
45+
header: "Role",
46+
cell: ({ getValue }) => {
47+
const titles = (getValue() as string[])
48+
.map((id) => roleTitleById.get(id))
49+
.filter(Boolean);
50+
return titles.join(", ") || "-";
51+
},
52+
},
53+
{
54+
accessorKey: "expiresAt",
55+
id: "status",
56+
header: "Status",
57+
cell: ({ row }) =>
58+
formatInviteExpiry(row.original.expiresAt).isExpired
59+
? "Expired"
60+
: "Pending",
61+
},
62+
{
63+
accessorKey: "createdAt",
64+
header: "Invited on",
65+
cell: ({ row }) => formatTimestamp(row.original.createdAt),
66+
// Timestamps are objects, so the default comparator can't order them.
67+
sortingFn: (a, b) =>
68+
seconds(a.original.createdAt) - seconds(b.original.createdAt),
69+
enableSorting: true,
70+
},
71+
{
72+
accessorKey: "expiresAt",
73+
header: "Expiry",
74+
cell: ({ row }) => formatInviteExpiry(row.original.expiresAt).text,
75+
sortingFn: (a, b) =>
76+
seconds(a.original.expiresAt) - seconds(b.original.expiresAt),
77+
enableSorting: true,
78+
},
79+
{
80+
accessorKey: "id",
81+
header: "",
82+
// Its accessor is a string, so search would match invite ids without this.
83+
enableGlobalFilter: false,
84+
classNames: {
85+
header: styles["invites-action-column"],
86+
cell: styles["invites-action-column"],
87+
},
88+
cell: ({ row }) => {
89+
// Offered on every row; only the confirmation copy differs.
90+
const { isExpired } = formatInviteExpiry(row.original.expiresAt);
91+
92+
return (
93+
<Menu>
94+
<Menu.Trigger
95+
render={
96+
<IconButton
97+
size={3}
98+
data-test-id="admin-org-invites-action-menu">
99+
<DotsHorizontalIcon />
100+
</IconButton>
101+
}
102+
/>
103+
<Menu.Content align="end">
104+
<Menu.Item
105+
leadingIcon={<DeleteIcon />}
106+
className={styles["invites-remove-item"]}
107+
onClick={() =>
108+
removeInviteHandle.openWithPayload({
109+
inviteId: row.original.id,
110+
email: row.original.userId,
111+
isExpired,
112+
})
113+
}
114+
data-test-id="admin-org-invites-remove-action"
115+
>
116+
Remove
117+
</Menu.Item>
118+
</Menu.Content>
119+
</Menu>
120+
);
121+
},
122+
},
123+
];

0 commit comments

Comments
 (0)