feat: add user and role view sheets with detailed information display

- Created UserViewSheet component to display user details including username, full name, role, status, and timestamps.
- Created RoleViewSheet component to display role details including name, level, status, creation date, and associated permissions.
- Introduced permissions configuration in a new permissions.ts file, defining categories and permission codes for better management.
- Implemented middleware for authentication, ensuring access control for protected routes.
This commit is contained in:
Kalana B. Thilakarathna
2026-10-18 23:11:01 +05:30
parent 558afc6f9d
commit 0052725b88
86 changed files with 41117 additions and 939 deletions
@@ -1,28 +1,36 @@
'use client'
'use client'
import { useEffect } from 'react'
import { useEffect, useState } from 'react'
import { useForm, zodResolver, z } from '@/lib/form'
import { FormField } from '@/components/shared/form-field'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
} from '@/components/ui/dialog'
import { FieldGroup } from '@/components/ui/field'
import { toast } from '@/components/ui/toast'
import { roles as rolesApi, getApiError } from '@/lib/api/index'
import type { RoleResponse } from '@/types/api'
import { roles as rolesApi, permissions as permissionsApi, getApiError } from '@/lib/api/index'
import type { RoleResponse, PermissionResponse } from '@/types/api'
import { PERMISSION_CATEGORIES } from '@/config/permissions'
const ROLE_LEVELS: { value: number; label: string; description: string }[] = [
{ value: 10, label: 'Level 10 — Field Agent', description: 'Front-line sales rep; can place orders and check in to visits' },
{ value: 20, label: 'Level 20 — Supervisor', description: 'Oversees agents; can approve variances and update store credit limits' },
{ value: 30, label: 'Level 30 — Area Manager', description: 'Manages a group of supervisors within an area' },
{ value: 40, label: 'Level 40 — Area Supervisor', description: 'Senior oversight across multiple areas' },
{ value: 50, label: 'Level 50 — Regional Manager', description: 'Controls region targets, budgets and route assignments' },
{ value: 60, label: 'Level 60 — Regional Agency', description: 'Agency-level access across any region; broader scope than Regional Manager' },
{ value: 100, label: 'Level 100 — Super Admin', description: 'Full system access; all permissions granted' },
]
const schema = z.object({
name: z.string().min(1, 'Name is required'),
level: z.number().int().min(1, 'Level must be at least 1'),
isActive: z.boolean(),
level: z.string().min(1, 'Level is required'),
})
type FormValues = z.infer<typeof schema>
@@ -37,44 +45,64 @@ interface RoleSheetProps {
export function RoleSheet({ open, onClose, role, onSuccess }: RoleSheetProps) {
const isEdit = !!role
const [allPermissions, setAllPermissions] = useState<PermissionResponse[]>([])
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: { name: '', level: 1, isActive: true },
defaultValues: { name: '', level: '' },
})
useEffect(() => {
if (open) {
form.reset(
role
? { name: role.name, level: role.level, isActive: role.isActive }
: { name: '', level: 1, isActive: true }
)
if (!open) return
permissionsApi.list().then(setAllPermissions).catch(() => {})
if (role) {
form.reset({ name: role.name, level: String(role.level) })
rolesApi.getPermissions(role.id)
.then((perms) => setSelectedIds(new Set(perms.map((p) => p.permissionId))))
.catch(() => {})
} else {
form.reset({ name: '', level: '' })
setSelectedIds(new Set())
}
}, [open, role])
function togglePermission(id: string) {
setSelectedIds((prev) => {
const next = new Set(prev)
next.has(id) ? next.delete(id) : next.add(id)
return next
})
}
async function onSubmit(values: FormValues) {
const body = { name: values.name, level: parseInt(values.level, 10) }
try {
let roleId: string
if (isEdit) {
await rolesApi.update(role!.id, values)
await rolesApi.update(role!.id, body)
roleId = role!.id
toast.add({ title: 'Role updated', type: 'success' })
} else {
await rolesApi.create(values)
const created = await rolesApi.create(body)
roleId = created.id
toast.add({ title: 'Role created', type: 'success' })
}
await rolesApi.assignPermissions(roleId, Array.from(selectedIds))
onSuccess()
onClose()
} catch (err) {
toast.add({ title: 'Failed to save', description: getApiError(err), type: 'error' })
toast.add({ title: 'Failed to save role', description: getApiError(err), type: 'error' })
}
}
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-lg">
<DialogContent className="overflow-y-auto sm:max-w-3xl">
<DialogHeader>
<DialogTitle>{isEdit ? 'Edit Role' : 'Add Role'}</DialogTitle>
<DialogDescription>
{isEdit ? 'Update the role details below.' : 'Add a new role to the system.'}
{isEdit ? 'Update role details and permissions.' : 'Create a new role and assign permissions.'}
</DialogDescription>
</DialogHeader>
@@ -93,54 +121,91 @@ export function RoleSheet({ open, onClose, role, onSuccess }: RoleSheetProps) {
value={field.value as string}
onChange={field.onChange}
onBlur={field.onBlur}
placeholder="e.g. Sales Manager"
placeholder="e.g. Sales Rep"
aria-invalid={invalid}
/>
)}
/>
<FormField
control={form.control}
name="level"
label="Level"
required
render={({ field, invalid }) => (
<Input
id="level"
name={field.name}
ref={field.ref}
type="number"
value={String(field.value as number)}
onChange={(e) => field.onChange(parseInt(e.target.value) || 1)}
onBlur={field.onBlur}
placeholder="e.g. 1"
aria-invalid={invalid}
/>
)}
/>
<FormField
control={form.control}
name="isActive"
render={({ field }) => (
<div className="flex items-center gap-2">
<Checkbox
id="isActive"
checked={field.value as boolean}
onCheckedChange={field.onChange}
/>
<label htmlFor="isActive" className="text-sm font-medium cursor-pointer">
Active
</label>
</div>
<Select value={field.value as string} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select level" />
</SelectTrigger>
<SelectContent>
{ROLE_LEVELS.map((l) => (
<SelectItem key={l.value} value={String(l.value)}>
<div className="flex flex-col">
<span className="font-medium">{l.label}</span>
<span className="text-xs text-muted-foreground">{l.description}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</FieldGroup>
{allPermissions.length > 0 && (
<div className="flex flex-col gap-2">
<p className="text-sm font-medium">Permissions</p>
<div className="border rounded-md max-h-[28rem] overflow-y-auto p-3">
<div className="grid grid-cols-2 gap-3">
{PERMISSION_CATEGORIES.map((cat) => {
const catPerms = allPermissions.filter((p) => cat.codes.includes(p.code))
if (catPerms.length === 0) return null
const allChecked = catPerms.every((p) => selectedIds.has(p.permissionId))
const someChecked = catPerms.some((p) => selectedIds.has(p.permissionId))
return (
<div key={cat.id} className="rounded-md border bg-muted/30 p-3 flex flex-col gap-2">
<div className="flex items-center gap-2">
<Checkbox
id={`cat-${cat.id}`}
checked={allChecked}
data-state={someChecked && !allChecked ? 'indeterminate' : undefined}
onCheckedChange={(checked) => {
setSelectedIds((prev) => {
const next = new Set(prev)
catPerms.forEach((p) => checked ? next.add(p.permissionId) : next.delete(p.permissionId))
return next
})
}}
/>
<label htmlFor={`cat-${cat.id}`} className="text-xs font-semibold uppercase tracking-wide text-muted-foreground cursor-pointer select-none">
{cat.label}
</label>
</div>
<div className="flex flex-col gap-1.5 pl-6">
{catPerms.map((p) => (
<div key={p.permissionId} className="flex items-start gap-2">
<Checkbox
id={p.permissionId}
checked={selectedIds.has(p.permissionId)}
onCheckedChange={() => togglePermission(p.permissionId)}
className="mt-0.5"
/>
<label htmlFor={p.permissionId} className="text-sm cursor-pointer flex flex-col">
<span className="font-medium">{p.code}</span>
{p.description && <span className="text-muted-foreground text-xs">{p.description}</span>}
</label>
</div>
))}
</div>
</div>
)
})}
</div>
</div>
</div>
)}
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Saving…' : isEdit ? 'Save Changes' : 'Create Role'}
</Button>
@@ -0,0 +1,77 @@
'use client'
import { useEffect, useState } from 'react'
import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { toast } from '@/components/ui/toast'
import { roles as rolesApi, getApiError } from '@/lib/api/index'
import type { RoleResponse, PermissionResponse } from '@/types/api'
const fmtDate = (v: string) =>
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
interface RoleViewSheetProps {
open: boolean
onClose: () => void
role: RoleResponse | null
}
function Row({ label, value }: { label: string; value: React.ReactNode }) {
return (
<div className="flex items-center justify-between border-b py-2 text-sm last:border-0">
<span className="text-muted-foreground">{label}</span>
<span className="font-medium text-right">{value}</span>
</div>
)
}
export function RoleViewSheet({ open, onClose, role }: RoleViewSheetProps) {
const [permissions, setPermissions] = useState<PermissionResponse[]>([])
const [loading, setLoading] = useState(false)
useEffect(() => {
if (!open || !role) return
setLoading(true)
rolesApi.getPermissions(role.id)
.then(setPermissions)
.catch((err) => toast.add({ title: 'Failed to load permissions', description: getApiError(err), type: 'error' }))
.finally(() => setLoading(false))
}, [open, role])
if (!role) return null
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>Role Details</DialogTitle>
</DialogHeader>
<div className="flex flex-col">
<Row label="Name" value={role.name} />
<Row label="Level" value={role.level} />
<Row label="Status" value={<Badge variant={role.isActive ? 'default' : 'secondary'}>{role.isActive ? 'Active' : 'Inactive'}</Badge>} />
<Row label="Created At" value={fmtDate(role.createdAt)} />
</div>
<div className="mt-2 flex flex-col gap-2">
<p className="text-sm font-medium">Permissions</p>
{loading ? (
<p className="text-sm text-muted-foreground">Loading…</p>
) : permissions.length === 0 ? (
<p className="text-sm text-muted-foreground">No permissions assigned to this role.</p>
) : (
<div className="max-h-64 overflow-y-auto rounded-md border p-3 flex flex-col gap-2">
{permissions.map((p) => (
<div key={p.permissionId} className="flex flex-col">
<span className="text-sm font-medium">{p.code}</span>
{p.description && <span className="text-xs text-muted-foreground">{p.description}</span>}
</div>
))}
</div>
)}
</div>
</DialogContent>
</Dialog>
)
}
@@ -1,4 +1,4 @@
'use client'
'use client'
import { useState, useEffect, useCallback, useMemo } from 'react'
import { HugeiconsIcon } from '@hugeicons/react'
@@ -13,21 +13,25 @@ import { roles as rolesApi, getApiError } from '@/lib/api/index'
import type { RoleResponse } from '@/types/api'
import { RoleSheet } from './role-sheet'
import { RoleViewSheet } from './role-view-sheet'
export function RolesClient() {
const [data, setData] = useState<RoleResponse[]>([])
const [loading, setLoading] = useState(true)
const [total, setTotal] = useState(0)
const [pageSize, setPageSize] = useState(20)
const [sheetOpen, setSheetOpen] = useState(false)
const [editing, setEditing] = useState<RoleResponse | null>(null)
const [viewOpen, setViewOpen] = useState(false)
const [viewing, setViewing] = useState<RoleResponse | null>(null)
const fetchData = useCallback(async () => {
setLoading(true)
try {
const res = await rolesApi.list()
setData(res)
setTotal(res.length)
const items = await rolesApi.list()
setData(items)
setTotal(items.length)
} catch (err) {
toast.add({ title: 'Failed to load roles', description: getApiError(err), type: 'error' })
} finally {
@@ -35,30 +39,19 @@ export function RolesClient() {
}
}, [])
useEffect(() => {
fetchData()
}, [fetchData])
useEffect(() => { fetchData() }, [fetchData])
function openCreate() {
setEditing(null)
setSheetOpen(true)
}
function openCreate() { setEditing(null); setSheetOpen(true) }
function openEdit(role: RoleResponse) { setEditing(role); setSheetOpen(true) }
function openView(role: RoleResponse) { setViewing(role); setViewOpen(true) }
function openEdit(role: RoleResponse) {
setEditing(role)
setSheetOpen(true)
}
async function toggleActive(role: RoleResponse) {
async function handleDeactivate(role: RoleResponse) {
try {
await rolesApi.update(role.id, { isActive: !role.isActive })
toast.add({
title: role.isActive ? 'Role deactivated' : 'Role activated',
type: 'success',
})
await rolesApi.deactivate(role.id)
toast.add({ title: 'Role deactivated', type: 'success' })
fetchData()
} catch (err) {
toast.add({ title: 'Failed to update role', description: getApiError(err), type: 'error' })
toast.add({ title: 'Failed to deactivate role', description: getApiError(err), type: 'error' })
}
}
@@ -66,64 +59,54 @@ export function RolesClient() {
rowKey: 'id',
stickyHeader: true,
emptyMessage: 'No roles yet. Add one to get started.',
pagination: { enabled: true, pageSize: 20, pageSizeOptions: [10, 20, 50] },
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
columns: [
{
key: 'name',
title: 'Role',
title: 'Role Name',
fields: [{ key: 'name', primary: true }],
sortable: true,
minWidth: 200,
minWidth: 180,
},
{
key: 'level',
title: 'Level',
fields: [{ key: 'level', transform: (v) => `Level ${v}` }],
fields: [{ key: 'level' }],
width: 100,
},
{
key: 'status',
title: 'Status',
fields: ['isActive'],
width: 120,
width: 100,
cellRender: (row) => (
<Badge variant={row.isActive ? 'default' : 'secondary'}>
{row.isActive ? 'Active' : 'Inactive'}
</Badge>
),
},
{
key: 'createdAt',
title: 'Created',
fields: [{ key: 'createdAt', transform: (v) => new Date(v as string).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }) }],
width: 140,
},
],
rowActions: {
actions: () => [
{
action: 'edit',
label: 'Edit role',
onClick: openEdit,
},
{
action: 'deactivate',
label: 'Deactivate role',
onClick: toggleActive,
visible: (target) => target.isActive,
},
{
action: 'activate',
label: 'Activate role',
onClick: toggleActive,
visible: (target) => !target.isActive,
},
{ action: 'view', label: 'View role & permissions', onClick: openView },
{ action: 'edit', label: 'Edit role', onClick: openEdit },
{ action: 'cancel', label: 'Deactivate role', onClick: handleDeactivate, visible: (t) => t.isActive },
],
},
}), [openEdit, toggleActive])
}), [pageSize])
return (
<>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-semibold text-foreground">Roles</h1>
<p className="text-sm text-muted-foreground mt-0.5">
Permission sets that control what each role can see and do
</p>
<p className="text-sm text-muted-foreground mt-0.5">Permission sets that control what each role can see and do</p>
</div>
<Button onClick={openCreate}>
<HugeiconsIcon icon={Add01Icon} size={16} />
@@ -136,6 +119,7 @@ export function RolesClient() {
data={data}
loading={loading}
totalCount={total}
onServerSideChange={({ page: p }) => setPageSize(p.pageSize)}
/>
<RoleSheet
@@ -144,6 +128,12 @@ export function RolesClient() {
role={editing}
onSuccess={() => fetchData()}
/>
<RoleViewSheet
open={viewOpen}
onClose={() => setViewOpen(false)}
role={viewing}
/>
</>
)
}
@@ -1,4 +1,4 @@
import { RolesClient } from './_components/roles-client'
import { RolesClient } from './_components/roles-client'
export default function RolesPage() {
return <RolesClient />