All files / pages/superadmin UserManagementPage.tsx

90% Statements 36/40
88.23% Branches 45/51
81.25% Functions 13/16
92.3% Lines 36/39

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                                                                                                                  1x           1x                     124x 124x 124x         124x           124x 124x   124x   124x   296x     296x 296x     124x 2x     124x 5x     124x 3x     124x 2x   2x     1x 1x     1x 1x       124x 48x             76x 1x             75x                                             40x                     2x                                                         203x                                                                     4x                       1x                                                                                                                                                                                  
import type {ReactElement} from 'react';
import {useState} from 'react';
import {
	Alert,
	Box,
	Button,
	Chip,
	CircularProgress,
	Container,
	Dialog,
	DialogActions,
	DialogContent,
	DialogContentText,
	DialogTitle,
	FormControl,
	InputLabel,
	MenuItem,
	Paper,
	Select,
	type SelectChangeEvent,
	Snackbar,
	Table,
	TableBody,
	TableCell,
	TableContainer,
	TableHead,
	TableRow,
	TextField,
	Typography
} from '@mui/material';
import {AdminPanelSettings as AdminIcon} from '@mui/icons-material';
import {
	type UserListItem,
	useListUsersQuery,
	useUpdateUserRoleMutation
} 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'
};
 
// ============================================================================
// 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 {data, isLoading, isError} = useListUsersQuery();
	const [updateRole, {isLoading: isUpdating}] = useUpdateUserRoleMutation();
 
	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 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();
			});
	};
 
	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="lg">
				{/* Header */}
				<Box sx={{mb: 4}}>
					<Box sx={{display: 'flex', alignItems: 'center', mb: 1}}>
						<AdminIcon sx={{mr: 1, fontSize: 32}} color="primary"/>
						<Typography variant="h4" fontWeight="bold">
							User Management
						</Typography>
					</Box>
					<Typography variant="body1" 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" color="text.secondary" sx={{ml: 'auto'}}>
						{String(filteredUsers.length)} user{filteredUsers.length !== 1 ? 's' : ''}
					</Typography>
				</Paper>
 
				{/* Users Table */}
				<TableContainer component={Paper}>
					<Table>
						<TableHead>
							<TableRow>
								<TableCell>Username</TableCell>
								<TableCell>Email</TableCell>
								<TableCell>Current Role</TableCell>
								<TableCell>Status</TableCell>
								<TableCell>Last Login</TableCell>
								<TableCell align="right">Actions</TableCell>
							</TableRow>
						</TableHead>
						<TableBody>
							{filteredUsers.map((user) => (
								<TableRow key={user.userId} hover>
									<TableCell>
										<Typography variant="body2" fontWeight={500}>
											{user.username}
										</Typography>
									</TableCell>
									<TableCell>{user.email}</TableCell>
									<TableCell>
										<Chip
											label={ROLE_LABELS[user.role] ?? user.role}
											color={ROLE_COLORS[user.role] ?? 'default'}
											size="small"
										/>
									</TableCell>
									<TableCell>
										<Chip
											label={user.isActive ? 'Active' : 'Inactive'}
											color={user.isActive ? 'success' : 'default'}
											size="small"
											variant="outlined"
										/>
									</TableCell>
									<TableCell>
										{user.lastLogin !== null
											? new Date(user.lastLogin).toLocaleString()
											: 'Never'}
									</TableCell>
									<TableCell align="right">
										<Box sx={{display: 'flex', gap: 1, justifyContent: 'flex-end'}}>
											{user.role !== 'admin' && (
												<Button
													size="small"
													variant="outlined"
													color="primary"
													onClick={() => {
														handleOpenDialog(user, 'admin');
													}}
												>
													Make Admin
												</Button>
											)}
											{user.role !== 'super_admin' && (
												<Button
													size="small"
													variant="outlined"
													color="error"
													onClick={() => {
														handleOpenDialog(user, 'super_admin');
													}}
												>
													Make Super Admin
												</Button>
											)}
											{user.role !== 'investor' && (
												<Button
													size="small"
													variant="outlined"
													onClick={() => {
														handleOpenDialog(user, 'investor');
													}}
												>
													Demote to Investor
												</Button>
											)}
										</Box>
									</TableCell>
								</TableRow>
							))}
							{filteredUsers.length === 0 && (
								<TableRow>
									<TableCell colSpan={6} align="center" sx={{py: 4}}>
										<Typography color="text.secondary">No users found</Typography>
									</TableCell>
								</TableRow>
							)}
						</TableBody>
					</Table>
				</TableContainer>
 
				{/* 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>&apos;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>
 
				{/* 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>
	);
}