Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | 4x 104x 104x 42x 50x 7x 5x 104x 1x 1x 1x 1x 1x 104x 1x 4x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 7x 7x 6x 1x 1x 1x 18x 151x 73x 10x 7x 18x 18x 9x 5x 5x 5x 18x 12x 6x 6x 18x 1x 1x 18x 1x 1x 1x 1x 1x 1x 1x 1x 18x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 151x 151x | import { EllipsisVerticalIcon } from "@heroicons/react/24/outline";
import { useQueryClient } from "@tanstack/react-query";
import { ExportToCsv } from "export-to-csv";
import LZ from "lz-string";
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router";
import { formatDate, formatDateToET } from "shared-utils";
import { userRoleMap } from "shared-utils";
import { RoleRequest, useGetRoleRequests, useGetUserDetails, useSubmitRoleRequests } from "@/api";
import {
banner,
Button,
ConfirmationDialog,
LoadingSpinner,
Popover,
PopoverContent,
PopoverTrigger,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components";
import { cn } from "@/utils";
import { initSortUserData, sortUserData, UserRoleType } from "./utils";
type headingType = { [key: string]: keyof UserRoleType | null };
type SelectedUser = RoleRequest & { fullName: string };
const pendingCircle = (
<svg
className="mr-2"
width="9"
height="9"
viewBox="0 0 9 9"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<circle cx="4.5" cy="4.5" r="4.5" fill="#3D94D0" />
</svg>
);
export const renderCellActions = (
userRole: UserRoleType,
setModalText: React.Dispatch<React.SetStateAction<string>>,
setSelectedUserRole: React.Dispatch<React.SetStateAction<object>>,
isPopoverDisabled: boolean,
) => {
const actions = (function () {
switch (userRole.status) {
case "pending":
return ["Grant Access", "Deny Access"];
case "active":
return ["Revoke Access"];
case "denied":
return ["Grant Access"];
case "revoked":
return ["Grant Access"];
default:
return [];
}
})();
const actionChosen = (action: string) => {
const modalAction: Record<string, string> = {
"Grant Access": "grant",
"Deny Access": "deny",
"Revoke Access": "revoke",
};
const requestFor = userRole.status === "pending" ? " request for" : "";
const statusMap: Record<string, UserRoleType["status"]> = {
"Grant Access": "active",
"Deny Access": "denied",
"Revoke Access": "revoked",
};
setModalText(
`This will ${modalAction[action]} ${userRole.fullName}'s${requestFor} access to OneMac.`,
);
setSelectedUserRole({
email: userRole.email,
fullName: userRole.fullName,
state: userRole.territory,
role: userRole.role,
grantAccess: statusMap[action],
eventType: userRole.eventType,
group: userRole.group ?? null,
division: userRole.division ?? null,
requestRoleChange: false,
});
};
const isDisabled = isPopoverDisabled || actions.length === 0;
return (
<Popover>
<PopoverTrigger disabled={isDisabled} aria-label="Available actions">
<EllipsisVerticalIcon
aria-label="record actions"
className={cn("w-8", isDisabled ? "text-gray-400 cursor-not-allowed" : "text-blue-700")}
/>
</PopoverTrigger>
{!isDisabled && (
<PopoverContent className="w-auto">
<div className="flex flex-col">
{actions.map((action, idx) => (
<div
className="text-blue-500 cursor-pointer relative flex select-none items-center rounded-sm px-2 py-2 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground"
key={idx}
onClick={() => actionChosen(action)}
>
{action}
</div>
))}
</div>
</PopoverContent>
)}
</Popover>
);
};
export const UserManagement = () => {
const queryClient = useQueryClient();
const { data: userDetails } = useGetUserDetails();
const { data, isLoading, isFetching } = useGetRoleRequests();
const { mutateAsync: submitRequest, isLoading: processSubmit } = useSubmitRoleRequests();
const [userRoles, setUserRoles] = useState<UserRoleType[] | null>(null);
const [selectedUserRole, setSelectedUserRole] = useState<SelectedUser>(null);
const [modalText, setModalText] = useState<string | null>(null);
const isHelpDesk = userDetails?.role === "helpdesk";
const isStateSystemAdmin = userDetails?.role === "statesystemadmin";
const isSystemAdmin = userDetails?.role === "systemadmin";
const isCmsRoleApprover = userDetails?.role === "cmsroleapprover";
// Policy: SSAs can manage users, just not other parallel SSA accounts.
const canManageUsers = isSystemAdmin || isStateSystemAdmin || isCmsRoleApprover;
const [sortBy, setSortBy] = useState<{ title: keyof headingType | ""; direction: boolean }>({
title: "",
direction: false,
});
const headings = useMemo(() => {
const baseHeadings: headingType = {
Name: "fullName",
State: "territory",
Status: "status",
Role: "role",
"Last Modified": "lastModifiedDate",
"Modified By": "doneByName",
};
if (isHelpDesk) return baseHeadings;
if (!isStateSystemAdmin) return { Actions: null, ...baseHeadings };
// state sys admin view removes State/Role columns
delete baseHeadings.State;
delete baseHeadings.Role;
return { Actions: null, ...baseHeadings };
}, [isHelpDesk, isStateSystemAdmin]);
const renderStatus = (value: string) => {
switch (value) {
case "pending":
return <>{pendingCircle} Pending</>;
case "active":
return "Granted";
case "denied":
return "Denied";
case "revoked":
return "Revoked";
default:
return value;
}
};
const sortByHeading = (heading: string) => {
if (heading === "Actions") return;
let direction = false;
if (sortBy.title === heading) {
direction = !sortBy.direction;
setSortBy({ title: heading, direction });
} else {
setSortBy({ title: heading, direction: false });
}
setUserRoles((prev) => (prev ? sortUserData(headings[heading], direction, prev) : prev));
};
useEffect(() => {
if (!data) return;
Iif (!data.length) {
setUserRoles([]);
return;
}
Iif (sortBy.title) {
setUserRoles(sortUserData(headings[sortBy.title], sortBy.direction, [...data]));
} else {
setUserRoles(initSortUserData([...data]));
}
}, [data, sortBy, headings]);
const visibleUserRoles = useMemo(() => {
if (!userRoles) return [];
if (!isStateSystemAdmin) return userRoles;
return userRoles.filter((r) => r.role !== "statesystemadmin");
}, [userRoles, isStateSystemAdmin]);
const getBannerText = (selectedUser: SelectedUser) => {
switch (selectedUser.grantAccess) {
case "active":
return `${selectedUser.fullName} has been granted access`;
case "denied":
return `${selectedUser.fullName} has been denied access`;
case "revoked":
return `${selectedUser.fullName}'s access has been revoked`;
default:
return `${selectedUser.fullName}'s access is pending`;
}
};
const applyLocalStatusUpdate = (updated: SelectedUser) => {
const now = Date.now();
setUserRoles((prev) => {
Iif (!prev) return prev;
return prev.map((r) => {
Iif (r.email !== updated.email || r.territory !== updated.state || r.role !== updated.role) {
return r;
}
return {
...r,
status: updated.grantAccess,
lastModifiedDate: now,
doneByName: userDetails?.fullName ?? r.doneByName,
doneByEmail: userDetails?.email ?? r.doneByEmail,
};
});
});
queryClient.setQueryData<UserRoleType[]>(["roleRequests"], (old) => {
Eif (!old) return old;
return old.map((r) => {
if (r.email !== updated.email || r.territory !== updated.state || r.role !== updated.role) {
return r;
}
return {
...r,
status: updated.grantAccess,
lastModifiedDate: now,
doneByName: userDetails?.fullName ?? r.doneByName,
doneByEmail: userDetails?.email ?? r.doneByEmail,
};
});
});
};
const onAcceptRoleChange = async () => {
try {
setModalText(null);
await submitRequest(selectedUserRole);
applyLocalStatusUpdate(selectedUserRole);
await queryClient.invalidateQueries({ queryKey: ["roleRequests"], refetchType: "none" });
banner({
header: "Status Change",
body: `${getBannerText(selectedUserRole)}, a notification has been sent to their email.`,
variant: "success",
pathnameToDisplayOn: window.location.pathname,
});
setSelectedUserRole(null);
window.scrollTo(0, 0);
} catch (error) {
console.error(error);
banner({
header: "An unexpected error has occurred:",
body: error instanceof Error ? error.message : String(error),
variant: "destructive",
pathnameToDisplayOn: window.location.pathname,
});
}
};
const handleExport = async () => {
const modifiedUserRoles =
visibleUserRoles.map((role) => ({
Name: role.fullName,
Email: role.email,
State: role.territory,
Status: role.status,
Role: userRoleMap[role.role],
["Last Modified"]: formatDate(role.lastModifiedDate),
["Modified By"]: role.doneByName,
})) ?? [];
const csvExporter = new ExportToCsv({
useKeysAsHeaders: true,
filename: `Role-Requests-${formatDate(Date.now())}`,
});
csvExporter.generateCsv(modifiedUserRoles);
};
if (!userDetails || isLoading || processSubmit || isFetching || !userRoles) {
return <LoadingSpinner />;
}
return (
<div>
<ConfirmationDialog
open={modalText !== null}
title="Modify User's Access?"
body={modalText}
acceptButtonText="Confirm"
aria-labelledby="Modify User's Access Modal"
onAccept={onAcceptRoleChange}
onCancel={() => setModalText(null)}
/>
<div className="bg-sky-100/75" data-testid="sub-nav-header">
<div className="max-w-screen-xl m-auto px-4 lg:px-8 flex items-center py-4 justify-between">
<h1 className="text-xl font-medium">User Management</h1>
{(isHelpDesk || isSystemAdmin) && (
<Button variant="outline" onClick={handleExport}>
Export to Excel (CSV)
</Button>
)}
</div>
</div>
<div className="py-5 px-10">
<Table>
<TableHeader className="[&_tr]:border-b sticky top-0 bg-white">
<TableRow className="border-b transition-colors hover:bg-muted/50 ">
{Object.keys(headings).map((title) => (
<TableHead
key={title}
className="py-5 px-2 font-bold cursor-pointer max-w-fit"
onClick={() => sortByHeading(title)}
isActive={sortBy.title === title}
desc={sortBy.direction}
>
{title}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{visibleUserRoles.map((userRole) => {
console.log(userDetails, userRole);
const isPopoverDisabled =
!canManageUsers ||
(!["systemadmin", "cmsroleapprover"].includes(userDetails.role) &&
userRole.territory?.toLocaleUpperCase() !== "N/A" &&
!userDetails.states?.includes(userRole.territory));
return (
<TableRow key={userRole.id}>
{canManageUsers && (
<TableCell>
{renderCellActions(
userRole,
setModalText,
setSelectedUserRole,
isPopoverDisabled,
)}
</TableCell>
)}
<TableCell>
<Link
to={`/profile/${LZ.compressToEncodedURIComponent(userRole.email).replaceAll(
"+",
"_",
)}`}
className="cursor-pointer text-blue-600 hover:underline flex select-none items-center px-2 py-2"
>
{userRole.fullName}
</Link>
</TableCell>
{!isStateSystemAdmin && <TableCell>{userRole.territory}</TableCell>}
<TableCell>
<span className="font-bold flex items-center">
{renderStatus(userRole.status)}
</span>
</TableCell>
{!isStateSystemAdmin && <TableCell>{userRoleMap[userRole.role]}</TableCell>}
<TableCell>{formatDateToET(userRole.lastModifiedDate)}</TableCell>
<TableCell>{userRole.doneByName}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
</div>
);
};
|