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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 | 1x 1x 31x 124x 124x 124x 124x 124x 124x 124x 124x 124x 124x 296x 296x 296x 124x 2x 124x 5x 124x 3x 124x 124x 2x 2x 1x 1x 1x 1x 124x 333x 333x 333x 333x 333x 341x 341x 4x 1x 124x 48x 76x 1x 75x 40x 2x 6305x | import type {ReactElement} from 'react';
import {useState} from 'react';
import {
Alert,
Box,
Button,
Chip,
CircularProgress,
Container,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
FormControl,
IconButton,
InputLabel,
MenuItem,
Paper,
Select,
type SelectChangeEvent,
Snackbar,
TextField,
Tooltip,
Typography
} from '@mui/material';
import {
AdminPanelSettings as AdminIcon,
Delete as DeleteIcon,
PersonOutlined as PersonOutlineIcon,
Security as SecurityIcon
} from '@mui/icons-material';
import {
DataGridPremium,
type GridColDef,
type GridRenderCellParams
} from '@mui/x-data-grid-premium';
import {
type UserListItem,
useListUsersQuery,
useUpdateUserRoleMutation,
useDeleteUserMutation
} from '../../services/SuperAdminApi';
// ============================================================================
// Types
// ============================================================================
interface SnackbarState {
open: boolean;
message: string;
severity: 'success' | 'error';
}
interface RoleChangeDialogState {
open: boolean;
user: UserListItem | null;
newRole: 'investor' | 'admin' | 'super_admin';
}
// ============================================================================
// Constants
// ============================================================================
const ROLE_COLORS: Record<string, 'default' | 'primary' | 'error'> = {
investor: 'default',
admin: 'primary',
super_admin: 'error'
};
const ROLE_LABELS: Record<string, string> = {
investor: 'Investor',
admin: 'Admin',
super_admin: 'Super Admin'
};
function NoUsersOverlay(): ReactElement {
return (
<Box sx={{display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%'}}>
<Typography sx={{
color: "text.secondary"
}}>No users found</Typography>
</Box>
);
}
// ============================================================================
// Main Component
// ============================================================================
export default function UserManagementPage(): ReactElement {
const [searchTerm, setSearchTerm] = useState('');
const [roleFilter, setRoleFilter] = useState<string>('all');
const [dialog, setDialog] = useState<RoleChangeDialogState>({
open: false,
user: null,
newRole: 'admin'
});
const [snackbar, setSnackbar] = useState<SnackbarState>({
open: false,
message: '',
severity: 'success'
});
const [deleteDialog, setDeleteDialog] = useState<{open: boolean; user: UserListItem | null}>({
open: false,
user: null
});
const {data, isLoading, isFetching, isError} = useListUsersQuery();
const [updateRole, {isLoading: isUpdating}] = useUpdateUserRoleMutation();
const [deleteUser, {isLoading: isDeleting}] = useDeleteUserMutation();
const users: UserListItem[] = data?.data.users ?? [];
const filteredUsers = users.filter((user) => {
const matchesSearch =
searchTerm === '' ||
user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
user.email.toLowerCase().includes(searchTerm.toLowerCase());
const matchesRole = roleFilter === 'all' || user.role === roleFilter;
return matchesSearch && matchesRole;
});
const showSnackbar = (message: string, severity: 'success' | 'error'): void => {
setSnackbar({open: true, message, severity});
};
const handleOpenDialog = (user: UserListItem, newRole: 'investor' | 'admin' | 'super_admin'): void => {
setDialog({open: true, user, newRole});
};
const handleCloseDialog = (): void => {
setDialog({open: false, user: null, newRole: 'admin'});
};
const handleConfirmDelete = (): void => {
if (deleteDialog.user === null) return;
deleteUser(deleteDialog.user.userId)
.unwrap()
.then((result) => {
showSnackbar(result.message, 'success');
setDeleteDialog({open: false, user: null});
})
.catch((error: {data?: {message?: string}}) => {
showSnackbar(error.data?.message ?? 'Failed to delete user', 'error');
setDeleteDialog({open: false, user: null});
});
};
const handleConfirmRoleChange = (): void => {
Iif (dialog.user === null) return;
updateRole({userId: dialog.user.userId, role: dialog.newRole})
.unwrap()
.then((result) => {
showSnackbar(result.message, 'success');
handleCloseDialog();
})
.catch((error: {data?: {message?: string}}) => {
showSnackbar(error.data?.message ?? 'Failed to update user role', 'error');
handleCloseDialog();
});
};
const columns: GridColDef<UserListItem>[] = [
{
field: 'username',
headerName: 'Username',
width: 160,
renderCell: (params: GridRenderCellParams<UserListItem, string>) => (
<Typography variant="body2" sx={{
fontWeight: 500
}}>
{params.value}
</Typography>
)
},
{
field: 'email',
headerName: 'Email',
flex: 1,
minWidth: 200
},
{
field: 'role',
headerName: 'Current Role',
width: 140,
renderCell: (params: GridRenderCellParams<UserListItem, string>) => {
const value = params.value ?? '';
return (
<Chip
label={ROLE_LABELS[value] ?? value}
color={ROLE_COLORS[value] ?? 'default'}
size="small"
/>
);
}
},
{
field: 'isActive',
headerName: 'Status',
width: 110,
renderCell: (params: GridRenderCellParams<UserListItem, boolean>) => (
<Chip
label={params.value === true ? 'Active' : 'Inactive'}
color={params.value === true ? 'success' : 'default'}
size="small"
variant="outlined"
/>
)
},
{
field: 'lastLogin',
headerName: 'Last Login',
width: 180,
valueFormatter: (value: string | null) =>
value !== null ? new Date(value).toLocaleString() : 'Never'
},
{
field: 'actions',
headerName: 'Actions',
width: 200,
sortable: false,
filterable: false,
align: 'right',
headerAlign: 'right',
renderCell: (params: GridRenderCellParams<UserListItem>) => {
const user = params.row;
return (
<Box sx={{
display: 'flex',
gap: 0.5,
justifyContent: 'flex-end',
alignItems: 'center',
height: '100%',
width: '100%'
}}>
{user.role !== 'admin' && (
<Tooltip title="Make Admin">
<IconButton
size="small"
color="primary"
aria-label="Make Admin"
onClick={() => { handleOpenDialog(user, 'admin'); }}
>
<AdminIcon fontSize="small"/>
</IconButton>
</Tooltip>
)}
{user.role !== 'super_admin' && (
<Tooltip title="Make Super Admin">
<IconButton
size="small"
color="error"
aria-label="Make Super Admin"
onClick={() => { handleOpenDialog(user, 'super_admin'); }}
>
<SecurityIcon fontSize="small"/>
</IconButton>
</Tooltip>
)}
{user.role !== 'investor' && (
<Tooltip title="Demote to Investor">
<IconButton
size="small"
aria-label="Demote to Investor"
onClick={() => { handleOpenDialog(user, 'investor'); }}
>
<PersonOutlineIcon fontSize="small"/>
</IconButton>
</Tooltip>
)}
<Tooltip title="Delete user">
<IconButton
size="small"
color="error"
aria-label="Delete user"
onClick={() => { setDeleteDialog({open: true, user}); }}
>
<DeleteIcon fontSize="small"/>
</IconButton>
</Tooltip>
</Box>
);
}
}
];
if (isLoading) {
return (
<Box sx={{display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '50vh'}}>
<CircularProgress/>
</Box>
);
}
if (isError) {
return (
<Container maxWidth="lg" sx={{py: 4}}>
<Alert severity="error">Failed to load users</Alert>
</Container>
);
}
return (
<Box sx={{backgroundColor: 'background.default', minHeight: '100vh', py: 4}}>
<Container maxWidth={false} sx={{px: {xs: 2, sm: 3, md: 4}}}>
{/* Header */}
<Box sx={{mb: 4}}>
<Box sx={{display: 'flex', alignItems: 'center', mb: 1}}>
<AdminIcon sx={{mr: 1, fontSize: 32}} color="primary"/>
<Typography variant="h4" sx={{
fontWeight: "bold"
}}>
User Management
</Typography>
</Box>
<Typography variant="body1" sx={{
color: "text.secondary"
}}>
Manage user roles — promote users to Admin or Super Admin
</Typography>
</Box>
{/* Filters */}
<Paper sx={{p: 2, mb: 3, display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap'}}>
<TextField
size="small"
placeholder="Search by username or email..."
value={searchTerm}
onChange={(e) => { setSearchTerm(e.target.value); }}
sx={{minWidth: 280}}
/>
<FormControl size="small" sx={{minWidth: 150}}>
<InputLabel id="role-filter-label">Role</InputLabel>
<Select
labelId="role-filter-label"
value={roleFilter}
label="Role"
onChange={(e: SelectChangeEvent) => { setRoleFilter(e.target.value); }}
>
<MenuItem value="all">All Roles</MenuItem>
<MenuItem value="investor">Investor</MenuItem>
<MenuItem value="admin">Admin</MenuItem>
<MenuItem value="super_admin">Super Admin</MenuItem>
</Select>
</FormControl>
<Typography
variant="body2"
sx={{
color: "text.secondary",
ml: 'auto'
}}>
{String(filteredUsers.length)} user{filteredUsers.length !== 1 ? 's' : ''}
</Typography>
</Paper>
{/* Users DataGrid */}
<Paper sx={{p: 2}}>
<Box sx={{
height: 600,
width: '100%',
'& .MuiDataGrid-columnHeaders': {backgroundColor: 'action.hover'},
'& .MuiDataGrid-columnHeaderTitle': {fontWeight: 700},
'& .MuiDataGrid-row:hover': {backgroundColor: 'action.hover'},
'& .MuiDataGrid-row:nth-of-type(even)': {backgroundColor: 'action.selected'},
'& .MuiDataGrid-row:nth-of-type(even):hover': {backgroundColor: 'action.hover'}
}}>
<DataGridPremium
rows={filteredUsers}
columns={columns}
getRowId={(row) => row.userId}
loading={isFetching}
pageSizeOptions={[10, 25, 50, 100]}
initialState={{pagination: {paginationModel: {pageSize: 25}}}}
pagination
disableRowSelectionOnClick
density="comfortable"
showToolbar
slots={{noRowsOverlay: NoUsersOverlay}}
/>
</Box>
</Paper>
{/* Confirmation Dialog */}
<Dialog open={dialog.open} onClose={handleCloseDialog}>
<DialogTitle>Confirm Role Change</DialogTitle>
<DialogContent>
<DialogContentText component="div">
Are you sure you want to change <strong>{dialog.user?.username}</strong>'s
role from <Chip label={ROLE_LABELS[dialog.user?.role ?? ''] ?? dialog.user?.role}
size="small" sx={{mx: 0.5}}/> to <Chip
label={ROLE_LABELS[dialog.newRole]} size="small"
color={ROLE_COLORS[dialog.newRole] ?? 'default'} sx={{mx: 0.5}}/>?
</DialogContentText>
{dialog.newRole === 'super_admin' && (
<Alert severity="warning" sx={{mt: 2}}>
Super Admin has full system access including test data management, error logs, system
settings, and user management.
</Alert>
)}
</DialogContent>
<DialogActions>
<Button onClick={handleCloseDialog} disabled={isUpdating}>
Cancel
</Button>
<Button
onClick={handleConfirmRoleChange}
variant="contained"
color={dialog.newRole === 'investor' ? 'inherit' : 'primary'}
disabled={isUpdating}
startIcon={isUpdating ? <CircularProgress size={16}/> : undefined}
>
{isUpdating ? 'Updating...' : 'Confirm'}
</Button>
</DialogActions>
</Dialog>
{/* Delete Confirmation Dialog */}
<Dialog open={deleteDialog.open} onClose={() => { setDeleteDialog({open: false, user: null}); }}>
<DialogTitle>Delete User</DialogTitle>
<DialogContent>
<DialogContentText component="div">
Are you sure you want to permanently delete <strong>{deleteDialog.user?.username}</strong> ({deleteDialog.user?.email})?
</DialogContentText>
<Alert severity="error" sx={{mt: 2}}>
This will delete the user and all associated data: investor profile, account, loans, transactions, and sessions. This cannot be undone.
</Alert>
</DialogContent>
<DialogActions>
<Button onClick={() => { setDeleteDialog({open: false, user: null}); }} disabled={isDeleting}>
Cancel
</Button>
<Button
onClick={handleConfirmDelete}
variant="contained"
color="error"
disabled={isDeleting}
startIcon={isDeleting ? <CircularProgress size={16}/> : <DeleteIcon/>}
>
{isDeleting ? 'Deleting...' : 'Delete User'}
</Button>
</DialogActions>
</Dialog>
{/* Snackbar */}
<Snackbar
open={snackbar.open}
autoHideDuration={6000}
onClose={() => {
setSnackbar({...snackbar, open: false});
}}
anchorOrigin={{vertical: 'bottom', horizontal: 'right'}}
>
<Alert
onClose={() => {
setSnackbar({...snackbar, open: false});
}}
severity={snackbar.severity}
variant="filled"
>
{snackbar.message}
</Alert>
</Snackbar>
</Container>
</Box>
);
}
|