Add roles and users admin UI with role management API
Backend: - GET /v1/users (list company users) - GET/POST/PATCH/DELETE /v1/roles (role CRUD with permissions) - GET/POST/DELETE /v1/users/:userId/roles (role assignment) - GET /v1/me/permissions (current user's effective permissions) Frontend: - Roles list page with kebab menu (edit permissions, delete custom) - Role detail page with grouped permission checkboxes and inheritance note - New role page with auto-generated slug - Users list page showing assigned roles per user - Manage Roles dialog for adding/removing roles per user - Sidebar: Admin section with Users, Roles, Help links
This commit is contained in:
@@ -14,7 +14,7 @@ import {
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Users, UserRound, HelpCircle, Sun, Moon, Monitor, LogOut, User, Palette } from 'lucide-react'
|
||||
import { Users, UserRound, HelpCircle, Shield, UserCog, Sun, Moon, Monitor, LogOut, User, Palette } from 'lucide-react'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated')({
|
||||
beforeLoad: () => {
|
||||
@@ -69,6 +69,25 @@ function AuthenticatedLayout() {
|
||||
<UserRound className="h-4 w-4" />
|
||||
Members
|
||||
</Link>
|
||||
<div className="mt-4 mb-1 px-3">
|
||||
<span className="text-xs font-semibold text-sidebar-foreground/50 uppercase tracking-wide">Admin</span>
|
||||
</div>
|
||||
<Link
|
||||
to="/users"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
>
|
||||
<UserCog className="h-4 w-4" />
|
||||
Users
|
||||
</Link>
|
||||
<Link
|
||||
to="/roles"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
>
|
||||
<Shield className="h-4 w-4" />
|
||||
Roles
|
||||
</Link>
|
||||
<Link
|
||||
to="/help"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
|
||||
186
packages/admin/src/routes/_authenticated/roles/$roleId.tsx
Normal file
186
packages/admin/src/routes/_authenticated/roles/$roleId.tsx
Normal file
@@ -0,0 +1,186 @@
|
||||
import { createFileRoute, useParams, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { roleDetailOptions, permissionListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { ArrowLeft } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/roles/$roleId')({
|
||||
component: RoleDetailPage,
|
||||
})
|
||||
|
||||
function RoleDetailPage() {
|
||||
const { roleId } = useParams({ from: '/_authenticated/roles/$roleId' })
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const { data: role, isLoading: roleLoading } = useQuery(roleDetailOptions(roleId))
|
||||
const { data: permsData } = useQuery(permissionListOptions())
|
||||
|
||||
const [name, setName] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [selectedPerms, setSelectedPerms] = useState<Set<string>>(new Set())
|
||||
|
||||
useEffect(() => {
|
||||
if (role) {
|
||||
setName(role.name)
|
||||
setDescription(role.description ?? '')
|
||||
setSelectedPerms(new Set(role.permissions ?? []))
|
||||
}
|
||||
}, [role])
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => rbacMutations.updateRole(roleId, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.role(roleId) })
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||
toast.success('Role updated')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
function togglePermission(slug: string) {
|
||||
const next = new Set(selectedPerms)
|
||||
if (next.has(slug)) {
|
||||
next.delete(slug)
|
||||
} else {
|
||||
next.add(slug)
|
||||
}
|
||||
setSelectedPerms(next)
|
||||
}
|
||||
|
||||
function toggleDomain(domain: string, allSlugs: string[]) {
|
||||
const allSelected = allSlugs.every((s) => selectedPerms.has(s))
|
||||
const next = new Set(selectedPerms)
|
||||
for (const slug of allSlugs) {
|
||||
if (allSelected) next.delete(slug)
|
||||
else next.add(slug)
|
||||
}
|
||||
setSelectedPerms(next)
|
||||
}
|
||||
|
||||
function handleSave() {
|
||||
updateMutation.mutate({
|
||||
name,
|
||||
description: description || undefined,
|
||||
permissionSlugs: Array.from(selectedPerms),
|
||||
})
|
||||
}
|
||||
|
||||
if (roleLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-8 w-48" />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!role) {
|
||||
return <p className="text-muted-foreground">Role not found</p>
|
||||
}
|
||||
|
||||
// Group permissions by domain
|
||||
const allPerms = permsData?.data ?? []
|
||||
const domains = new Map<string, typeof allPerms>()
|
||||
for (const p of allPerms) {
|
||||
const list = domains.get(p.domain) ?? []
|
||||
list.push(p)
|
||||
domains.set(p.domain, list)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/roles' })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{role.name}</h1>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span className="font-mono">{role.slug}</span>
|
||||
{role.isSystem && <Badge variant="secondary">System</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Name</Label>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Description</Label>
|
||||
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Permissions</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Select which permissions this role grants. Admin implies Edit and View.
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{Array.from(domains.entries()).map(([domain, perms]) => {
|
||||
const slugs = perms.map((p) => p.slug)
|
||||
const allChecked = slugs.every((s) => selectedPerms.has(s))
|
||||
const someChecked = slugs.some((s) => selectedPerms.has(s))
|
||||
|
||||
return (
|
||||
<div key={domain}>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allChecked}
|
||||
ref={(el) => { if (el) el.indeterminate = someChecked && !allChecked }}
|
||||
onChange={() => toggleDomain(domain, slugs)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span className="text-sm font-semibold capitalize">{domain}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 pl-6">
|
||||
{perms.map((p) => (
|
||||
<label key={p.slug} className="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedPerms.has(p.slug)}
|
||||
onChange={() => togglePermission(p.slug)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span>{p.action}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Separator className="mt-4" />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={handleSave} disabled={updateMutation.isPending}>
|
||||
{updateMutation.isPending ? 'Saving...' : 'Save Changes'}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles' })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
109
packages/admin/src/routes/_authenticated/roles/index.tsx
Normal file
109
packages/admin/src/routes/_authenticated/roles/index.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { roleListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Plus, MoreVertical, Pencil, Trash2, Shield } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/roles/')({
|
||||
component: RolesListPage,
|
||||
})
|
||||
|
||||
function RolesListPage() {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const { data, isLoading } = useQuery(roleListOptions())
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: rbacMutations.deleteRole,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||
toast.success('Role deleted')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const roles = data?.data ?? []
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Roles</h1>
|
||||
<Button onClick={() => navigate({ to: '/roles/new' })}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Role
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
) : roles.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">No roles found</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Slug</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead className="w-12"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{roles.map((role) => (
|
||||
<TableRow key={role.id}>
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
{role.name}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-sm text-muted-foreground">{role.slug}</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">{role.description ?? '-'}</TableCell>
|
||||
<TableCell>
|
||||
{role.isSystem ? <Badge variant="secondary">System</Badge> : <Badge>Custom</Badge>}
|
||||
</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={() => navigate({ to: '/roles/$roleId', params: { roleId: role.id } })}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit Permissions
|
||||
</DropdownMenuItem>
|
||||
{!role.isSystem && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => deleteMutation.mutate(role.id)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
162
packages/admin/src/routes/_authenticated/roles/new.tsx
Normal file
162
packages/admin/src/routes/_authenticated/roles/new.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { permissionListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/roles/new')({
|
||||
component: NewRolePage,
|
||||
})
|
||||
|
||||
function NewRolePage() {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const { data: permsData } = useQuery(permissionListOptions())
|
||||
|
||||
const [name, setName] = useState('')
|
||||
const [slug, setSlug] = useState('')
|
||||
const [description, setDescription] = useState('')
|
||||
const [selectedPerms, setSelectedPerms] = useState<Set<string>>(new Set())
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: rbacMutations.createRole,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||
toast.success('Role created')
|
||||
navigate({ to: '/roles' })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
function togglePermission(permSlug: string) {
|
||||
const next = new Set(selectedPerms)
|
||||
if (next.has(permSlug)) next.delete(permSlug)
|
||||
else next.add(permSlug)
|
||||
setSelectedPerms(next)
|
||||
}
|
||||
|
||||
function toggleDomain(domain: string, allSlugs: string[]) {
|
||||
const allSelected = allSlugs.every((s) => selectedPerms.has(s))
|
||||
const next = new Set(selectedPerms)
|
||||
for (const s of allSlugs) {
|
||||
if (allSelected) next.delete(s)
|
||||
else next.add(s)
|
||||
}
|
||||
setSelectedPerms(next)
|
||||
}
|
||||
|
||||
function handleNameChange(value: string) {
|
||||
setName(value)
|
||||
if (!slug || slug === nameToSlug(name)) {
|
||||
setSlug(nameToSlug(value))
|
||||
}
|
||||
}
|
||||
|
||||
function nameToSlug(n: string) {
|
||||
return n.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '')
|
||||
}
|
||||
|
||||
function handleSubmit() {
|
||||
if (!name || !slug) {
|
||||
toast.error('Name and slug are required')
|
||||
return
|
||||
}
|
||||
mutation.mutate({
|
||||
name,
|
||||
slug,
|
||||
description: description || undefined,
|
||||
permissionSlugs: Array.from(selectedPerms),
|
||||
})
|
||||
}
|
||||
|
||||
const allPerms = permsData?.data ?? []
|
||||
const domains = new Map<string, typeof allPerms>()
|
||||
for (const p of allPerms) {
|
||||
const list = domains.get(p.domain) ?? []
|
||||
list.push(p)
|
||||
domains.set(p.domain, list)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<h1 className="text-2xl font-bold">New Role</h1>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Name *</Label>
|
||||
<Input value={name} onChange={(e) => handleNameChange(e.target.value)} placeholder="e.g. School Sales Rep" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Slug *</Label>
|
||||
<Input value={slug} onChange={(e) => setSlug(e.target.value)} placeholder="auto-generated" className="font-mono" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Description</Label>
|
||||
<Textarea value={description} onChange={(e) => setDescription(e.target.value)} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Permissions</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{Array.from(domains.entries()).map(([domain, perms]) => {
|
||||
const slugs = perms.map((p) => p.slug)
|
||||
const allChecked = slugs.every((s) => selectedPerms.has(s))
|
||||
const someChecked = slugs.some((s) => selectedPerms.has(s))
|
||||
|
||||
return (
|
||||
<div key={domain}>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allChecked}
|
||||
ref={(el) => { if (el) el.indeterminate = someChecked && !allChecked }}
|
||||
onChange={() => toggleDomain(domain, slugs)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span className="text-sm font-semibold capitalize">{domain}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-2 pl-6">
|
||||
{perms.map((p) => (
|
||||
<label key={p.slug} className="flex items-center gap-2 text-sm cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedPerms.has(p.slug)}
|
||||
onChange={() => togglePermission(p.slug)}
|
||||
className="rounded"
|
||||
/>
|
||||
<span>{p.action}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Separator className="mt-4" />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={handleSubmit} disabled={mutation.isPending}>
|
||||
{mutation.isPending ? 'Creating...' : 'Create Role'}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles' })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
195
packages/admin/src/routes/_authenticated/users.tsx
Normal file
195
packages/admin/src/routes/_authenticated/users.tsx
Normal file
@@ -0,0 +1,195 @@
|
||||
import { createFileRoute, useNavigate } 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 { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { MoreVertical, Shield, Plus, X } 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'),
|
||||
})
|
||||
}
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/users')({
|
||||
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))
|
||||
const { data: allRolesData } = useQuery(roleListOptions())
|
||||
const [selectedRoleId, setSelectedRoleId] = useState('')
|
||||
|
||||
const userRoles = userRolesData?.data ?? []
|
||||
const allRoles = allRolesData?.data ?? []
|
||||
const assignedIds = new Set(userRoles.map((r) => r.id))
|
||||
const availableRoles = allRoles.filter((r) => !assignedIds.has(r.id))
|
||||
|
||||
const assignMutation = useMutation({
|
||||
mutationFn: (roleId: string) => rbacMutations.assignRole(user.id, roleId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users', user.id, 'roles'] })
|
||||
setSelectedRoleId('')
|
||||
toast.success('Role assigned')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const removeMutation = useMutation({
|
||||
mutationFn: (roleId: string) => rbacMutations.removeRole(user.id, roleId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users', user.id, 'roles'] })
|
||||
toast.success('Role removed')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Manage Roles — {user.firstName} {user.lastName}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">Assigned Roles</p>
|
||||
{userRoles.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No roles assigned</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{userRoles.map((r) => (
|
||||
<div key={r.id} className="flex items-center justify-between p-2 rounded-md border">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">{r.name}</span>
|
||||
{r.isSystem && <Badge variant="secondary" className="text-xs">System</Badge>}
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" className="h-6 w-6 p-0" onClick={() => removeMutation.mutate(r.id)}>
|
||||
<X className="h-3 w-3 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{availableRoles.length > 0 && (
|
||||
<div className="flex gap-2">
|
||||
<Select value={selectedRoleId} onValueChange={setSelectedRoleId}>
|
||||
<SelectTrigger className="flex-1">
|
||||
<SelectValue placeholder="Select a role to add" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{availableRoles.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={!selectedRoleId || assignMutation.isPending}
|
||||
onClick={() => selectedRoleId && assignMutation.mutate(selectedRoleId)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function UsersPage() {
|
||||
const { data, isLoading } = useQuery(userListOptions())
|
||||
const [managingUser, setManagingUser] = useState<UserRecord | null>(null)
|
||||
|
||||
const allUsers = data?.data ?? []
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="text-2xl font-bold">Users</h1>
|
||||
|
||||
{managingUser && (
|
||||
<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>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user