Add paginated users/roles, user status, frontend permissions, profile pictures, identifier file storage
- Users page: paginated, searchable, sortable with inline roles (no N+1) - Roles page: paginated, searchable, sortable + /roles/all for dropdowns - User is_active field with migration, PATCH toggle, auth check (disabled=401) - Frontend permission checks: auth store loads permissions, sidebar/buttons conditional - Profile pictures via file storage for users and members, avatar component - Identifier images use file storage API instead of base64 - Fix TypeScript errors across admin UI - 64 API tests passing (10 new)
This commit is contained in:
@@ -1,12 +1,14 @@
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { roleListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { userRolesOptions, type UserRecord } from '@/api/users'
|
||||
import { userListOptions, userRolesOptions, userKeys, userMutations, type UserRecord } from '@/api/users'
|
||||
import { roleListOptions, rbacMutations } from '@/api/rbac'
|
||||
import { usePagination } from '@/hooks/use-pagination'
|
||||
import { DataTable, type Column } from '@/components/shared/data-table'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import {
|
||||
@@ -15,38 +17,21 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { MoreVertical, Shield, Plus, X, KeyRound } from 'lucide-react'
|
||||
import { MoreVertical, Shield, Plus, X, KeyRound, Search, UserCheck, UserX } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
|
||||
function userListOptions() {
|
||||
return queryOptions({
|
||||
queryKey: ['users'],
|
||||
queryFn: () => api.get<{ data: UserRecord[] }>('/v1/users'),
|
||||
})
|
||||
}
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/users')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
page: Number(search.page) || 1,
|
||||
limit: Number(search.limit) || 25,
|
||||
q: (search.q as string) || undefined,
|
||||
sort: (search.sort as string) || undefined,
|
||||
order: (search.order as 'asc' | 'desc') || 'asc',
|
||||
}),
|
||||
component: UsersPage,
|
||||
})
|
||||
|
||||
function UserRoleBadges({ userId }: { userId: string }) {
|
||||
const { data } = useQuery(userRolesOptions(userId))
|
||||
const roles = data?.data ?? []
|
||||
|
||||
if (roles.length === 0) return <span className="text-sm text-muted-foreground">No roles</span>
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{roles.map((r) => (
|
||||
<Badge key={r.id} variant={r.isSystem ? 'secondary' : 'default'} className="text-xs">
|
||||
{r.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: boolean; onClose: () => void }) {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: userRolesData } = useQuery(userRolesOptions(user.id))
|
||||
@@ -61,7 +46,7 @@ function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: bo
|
||||
const assignMutation = useMutation({
|
||||
mutationFn: (roleId: string) => rbacMutations.assignRole(user.id, roleId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users', user.id, 'roles'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] })
|
||||
setSelectedRoleId('')
|
||||
toast.success('Role assigned')
|
||||
},
|
||||
@@ -71,7 +56,7 @@ function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: bo
|
||||
const removeMutation = useMutation({
|
||||
mutationFn: (roleId: string) => rbacMutations.removeRole(user.id, roleId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users', user.id, 'roles'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] })
|
||||
toast.success('Role removed')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
@@ -135,10 +120,131 @@ function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: bo
|
||||
}
|
||||
|
||||
function UsersPage() {
|
||||
const { data, isLoading } = useQuery(userListOptions())
|
||||
const queryClient = useQueryClient()
|
||||
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
const [managingUser, setManagingUser] = useState<UserRecord | null>(null)
|
||||
|
||||
const allUsers = data?.data ?? []
|
||||
const { data, isLoading } = useQuery(userListOptions(params))
|
||||
|
||||
const statusMutation = useMutation({
|
||||
mutationFn: ({ userId, isActive }: { userId: string; isActive: boolean }) =>
|
||||
userMutations.toggleStatus(userId, isActive),
|
||||
onSuccess: (_data, vars) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] })
|
||||
toast.success(vars.isActive ? 'User enabled' : 'User disabled')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
function handleSearchSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setSearch(searchInput)
|
||||
}
|
||||
|
||||
const userColumns: Column<UserRecord>[] = [
|
||||
{
|
||||
key: 'name',
|
||||
header: 'Name',
|
||||
sortable: true,
|
||||
render: (row) => (
|
||||
<span className={`font-medium ${!row.isActive ? 'text-muted-foreground' : ''}`}>
|
||||
{row.firstName} {row.lastName}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'email',
|
||||
header: 'Email',
|
||||
sortable: true,
|
||||
render: (row) => <span className={!row.isActive ? 'text-muted-foreground' : ''}>{row.email}</span>,
|
||||
},
|
||||
{
|
||||
key: 'roles',
|
||||
header: 'Roles',
|
||||
render: (row) =>
|
||||
row.roles.length === 0 ? (
|
||||
<span className="text-sm text-muted-foreground">No roles</span>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{row.roles.map((r) => (
|
||||
<Badge key={r.id} variant={r.isSystem ? 'secondary' : 'default'} className="text-xs">
|
||||
{r.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Status',
|
||||
render: (row) =>
|
||||
row.isActive ? (
|
||||
<Badge variant="secondary" className="text-xs">Active</Badge>
|
||||
) : (
|
||||
<Badge variant="destructive" className="text-xs">Disabled</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'created_at',
|
||||
header: 'Created',
|
||||
sortable: true,
|
||||
render: (row) => new Date(row.createdAt).toLocaleDateString(),
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: '',
|
||||
render: (row) => (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{hasPermission('users.edit') && (
|
||||
<DropdownMenuItem onClick={() => setManagingUser(row)}>
|
||||
<Shield className="mr-2 h-4 w-4" />
|
||||
Manage Roles
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{hasPermission('users.admin') && (
|
||||
<DropdownMenuItem onClick={async () => {
|
||||
try {
|
||||
const res = await api.post<{ resetLink: string }>(`/v1/auth/reset-password/${row.id}`, {})
|
||||
await navigator.clipboard.writeText(res.resetLink)
|
||||
toast.success('Reset link copied to clipboard')
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to generate link')
|
||||
}
|
||||
}}>
|
||||
<KeyRound className="mr-2 h-4 w-4" />
|
||||
Reset Password Link
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{hasPermission('users.admin') && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => statusMutation.mutate({ userId: row.id, isActive: !row.isActive })}
|
||||
>
|
||||
{row.isActive ? (
|
||||
<>
|
||||
<UserX className="mr-2 h-4 w-4" />
|
||||
Disable User
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<UserCheck className="mr-2 h-4 w-4" />
|
||||
Enable User
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -148,60 +254,31 @@ function UsersPage() {
|
||||
<ManageRolesDialog user={managingUser} open={!!managingUser} onClose={() => setManagingUser(null)} />
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
) : allUsers.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">No users found</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Roles</TableHead>
|
||||
<TableHead className="w-12"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{allUsers.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell className="font-medium">{user.firstName} {user.lastName}</TableCell>
|
||||
<TableCell>{user.email}</TableCell>
|
||||
<TableCell><UserRoleBadges userId={user.id} /></TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setManagingUser(user)}>
|
||||
<Shield className="mr-2 h-4 w-4" />
|
||||
Manage Roles
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={async () => {
|
||||
try {
|
||||
const res = await api.post<{ resetLink: string }>(`/v1/auth/reset-password/${user.id}`, {})
|
||||
await navigator.clipboard.writeText(res.resetLink)
|
||||
toast.success('Reset link copied to clipboard')
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to generate link')
|
||||
}
|
||||
}}>
|
||||
<KeyRound className="mr-2 h-4 w-4" />
|
||||
Reset Password Link
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search users..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Button type="submit" variant="secondary">Search</Button>
|
||||
</form>
|
||||
|
||||
<DataTable
|
||||
columns={userColumns}
|
||||
data={data?.data ?? []}
|
||||
loading={isLoading}
|
||||
page={params.page}
|
||||
totalPages={data?.pagination?.totalPages ?? 1}
|
||||
total={data?.pagination?.total ?? 0}
|
||||
sort={params.sort}
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user