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:
@@ -1,14 +1,82 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, type FormEvent } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useAuth } from '@/contexts/auth-context'
|
||||
import { getApiError } from '@/lib/api'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
export default function LoginPage() {
|
||||
const { login, user, loading } = useAuth()
|
||||
const router = useRouter()
|
||||
const [identifier, setIdentifier] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!loading && user) {
|
||||
router.replace('/')
|
||||
}
|
||||
}, [user, loading, router])
|
||||
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
setError(null)
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await login(identifier, password)
|
||||
} catch (err) {
|
||||
setError(getApiError(err))
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-background">
|
||||
<div className="flex w-full max-w-sm flex-col gap-6 p-6">
|
||||
<form onSubmit={handleSubmit} className="flex w-full max-w-sm flex-col gap-6 p-6">
|
||||
<div className="flex flex-col gap-1 text-center">
|
||||
<h1 className="text-2xl font-semibold text-foreground">Sign in</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Authentication will be wired up once the backend is ready.
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">Distribution ERP</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="identifier">Email</Label>
|
||||
<Input
|
||||
id="identifier"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={identifier}
|
||||
onChange={(e) => setIdentifier(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
)}
|
||||
|
||||
<Button type="submit" disabled={submitting} className="w-full">
|
||||
{submitting ? 'Signing in…' : 'Sign in'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
getApiError,
|
||||
getPaginatedItems,
|
||||
} from '@/lib/api/index'
|
||||
import { useAuth } from '@/contexts/auth-context'
|
||||
import type { LowStockItemResponse, StockMovementResponse } from '@/types/api'
|
||||
|
||||
const STORAGE_KEY = 'distribution-dashboard-widgets-v3'
|
||||
@@ -38,6 +39,7 @@ interface WidgetMeta {
|
||||
cat: Category
|
||||
title: string
|
||||
size: Size
|
||||
permission: string
|
||||
}
|
||||
|
||||
const CATEGORY_META: Record<Category, { label: string; text: string; bg: string; solid: string }> = {
|
||||
@@ -48,17 +50,17 @@ const CATEGORY_META: Record<Category, { label: string; text: string; bg: string;
|
||||
}
|
||||
|
||||
const WIDGET_META: WidgetMeta[] = [
|
||||
{ id: 'pendingPO', cat: 'sales', title: 'Pending Shop POs', size: 'sm' },
|
||||
{ id: 'awaitingConfirm', cat: 'sales', title: 'Awaiting Confirmation', size: 'sm' },
|
||||
{ id: 'fulfillRate', cat: 'sales', title: 'Fulfillment Rate', size: 'md' },
|
||||
{ id: 'openRides', cat: 'ops', title: 'Open Rides', size: 'md' },
|
||||
{ id: 'loadingSheetsByStatus', cat: 'ops', title: 'Loading Sheets by Status', size: 'md' },
|
||||
{ id: 'deliveryTasks', cat: 'ops', title: 'Pending Delivery Tasks', size: 'sm' },
|
||||
{ id: 'lowStock', cat: 'stock', title: 'Low Stock Alerts', size: 'lg' },
|
||||
{ id: 'stockMovements', cat: 'stock', title: 'Recent Stock Movements', size: 'lg' },
|
||||
{ id: 'warehouseBalance', cat: 'stock', title: 'Warehouse Balances', size: 'md' },
|
||||
{ id: 'outstandingPay', cat: 'finance', title: 'Outstanding Payments', size: 'sm' },
|
||||
{ id: 'invoiceStatus', cat: 'finance', title: 'Invoices by Status', size: 'md' },
|
||||
{ id: 'pendingPO', cat: 'sales', title: 'Pending Shop POs', size: 'sm', permission: 'orders.view' },
|
||||
{ id: 'awaitingConfirm', cat: 'sales', title: 'Awaiting Confirmation', size: 'sm', permission: 'orders.view' },
|
||||
{ id: 'fulfillRate', cat: 'sales', title: 'Fulfillment Rate', size: 'md', permission: 'orders.view' },
|
||||
{ id: 'openRides', cat: 'ops', title: 'Open Rides', size: 'md', permission: 'rides.view' },
|
||||
{ id: 'loadingSheetsByStatus',cat: 'ops', title: 'Loading Sheets by Status', size: 'md', permission: 'loading-sheet.view' },
|
||||
{ id: 'deliveryTasks', cat: 'ops', title: 'Pending Delivery Tasks', size: 'sm', permission: 'delivery-task.view' },
|
||||
{ id: 'lowStock', cat: 'stock', title: 'Low Stock Alerts', size: 'lg', permission: 'stock.view' },
|
||||
{ id: 'stockMovements', cat: 'stock', title: 'Recent Stock Movements', size: 'lg', permission: 'stock.view' },
|
||||
{ id: 'warehouseBalance', cat: 'stock', title: 'Warehouse Balances', size: 'md', permission: 'stock.view' },
|
||||
{ id: 'outstandingPay', cat: 'finance', title: 'Outstanding Payments', size: 'sm', permission: 'orders.view' },
|
||||
{ id: 'invoiceStatus', cat: 'finance', title: 'Invoices by Status', size: 'md', permission: 'orders.view' },
|
||||
]
|
||||
|
||||
const DEFAULT_ACTIVE = [
|
||||
@@ -200,68 +202,137 @@ interface DashboardData {
|
||||
finalizedInvoiceCount: number
|
||||
}
|
||||
|
||||
async function loadDashboardData(): Promise<DashboardData> {
|
||||
const [
|
||||
pendingPO, awaitingConfirm, allPO, fulfilledPO,
|
||||
openRidesRes,
|
||||
plannedSheets, confirmedSheets,
|
||||
pendingTasks, partialTasks,
|
||||
lowStock,
|
||||
movements,
|
||||
balances,
|
||||
outstanding,
|
||||
draftInv, printedInv, finalizedInv,
|
||||
] = await Promise.all([
|
||||
shopPos.list({ status: 'Pending', pageSize: 1 }),
|
||||
shopPos.list({ confirmed: true, status: 'Pending', pageSize: 1 }),
|
||||
shopPos.list({ pageSize: 1 }),
|
||||
shopPos.list({ status: 'Fulfilled', pageSize: 1 }),
|
||||
rides.list({ status: 'Open', pageSize: 5 }),
|
||||
loadingSheets.list({ status: 'Planned', pageSize: 1 }),
|
||||
loadingSheets.list({ status: 'Confirmed', pageSize: 1 }),
|
||||
deliveryTasks.list({ status: 'Pending', pageSize: 1 }),
|
||||
deliveryTasks.list({ status: 'PartiallyDelivered', pageSize: 1 }),
|
||||
stock.lowStock(),
|
||||
stock.movements({ pageSize: 5 }),
|
||||
stock.balances({ locationType: 'Warehouse', pageSize: 300 }),
|
||||
invoices.outstandingSummary(),
|
||||
invoices.list({ status: 'Draft', pageSize: 1 }),
|
||||
invoices.list({ status: 'Printed', pageSize: 1 }),
|
||||
invoices.list({ status: 'Finalized', pageSize: 1 }),
|
||||
])
|
||||
|
||||
const balanceRows = getPaginatedItems(balances)
|
||||
const byWarehouse = new Map<string, WarehouseBalanceRow>()
|
||||
for (const b of balanceRows) {
|
||||
const existing = byWarehouse.get(b.locationId)
|
||||
if (existing) existing.quantity += b.quantity
|
||||
else byWarehouse.set(b.locationId, { locationId: b.locationId, name: b.locationName, quantity: b.quantity })
|
||||
}
|
||||
const warehouseBalances = Array.from(byWarehouse.values())
|
||||
.sort((a, b) => b.quantity - a.quantity)
|
||||
.slice(0, 5)
|
||||
|
||||
function emptyDashboardData(): DashboardData {
|
||||
return {
|
||||
pendingPOCount: pendingPO.total,
|
||||
awaitingConfirmCount: awaitingConfirm.total,
|
||||
totalPOCount: allPO.total,
|
||||
fulfilledPOCount: fulfilledPO.total,
|
||||
openRides: getPaginatedItems(openRidesRes).map(r => ({ id: r.id, vehicleNumberPlate: r.vehicleNumberPlate, driverFullName: r.driverFullName })),
|
||||
plannedSheetsCount: plannedSheets.total,
|
||||
confirmedSheetsCount: confirmedSheets.total,
|
||||
pendingTasksCount: pendingTasks.total,
|
||||
partialTasksCount: partialTasks.total,
|
||||
lowStock: getPaginatedItems(lowStock).slice(0, 5),
|
||||
movements: getPaginatedItems(movements),
|
||||
warehouseBalances,
|
||||
outstandingAmount: outstanding.outstandingAmount,
|
||||
outstandingInvoiceCount: outstanding.invoiceCount,
|
||||
draftInvoiceCount: draftInv.total,
|
||||
printedInvoiceCount: printedInv.total,
|
||||
finalizedInvoiceCount: finalizedInv.total,
|
||||
pendingPOCount: 0, awaitingConfirmCount: 0, totalPOCount: 0, fulfilledPOCount: 0,
|
||||
openRides: [],
|
||||
plannedSheetsCount: 0, confirmedSheetsCount: 0,
|
||||
pendingTasksCount: 0, partialTasksCount: 0,
|
||||
lowStock: [], movements: [], warehouseBalances: [],
|
||||
outstandingAmount: 0, outstandingInvoiceCount: 0,
|
||||
draftInvoiceCount: 0, printedInvoiceCount: 0, finalizedInvoiceCount: 0,
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDashboardData(activeIds: Set<string>): Promise<DashboardData> {
|
||||
const data = emptyDashboardData()
|
||||
const fetches: Promise<void>[] = []
|
||||
|
||||
if (activeIds.has('pendingPO') || activeIds.has('awaitingConfirm') || activeIds.has('fulfillRate')) {
|
||||
fetches.push(
|
||||
Promise.all([
|
||||
shopPos.list({ status: 'Pending', pageSize: 1 }),
|
||||
shopPos.list({ confirmed: true, status: 'Pending', pageSize: 1 }),
|
||||
shopPos.list({ pageSize: 1 }),
|
||||
shopPos.list({ status: 'Fulfilled', pageSize: 1 }),
|
||||
]).then(([pending, awaiting, all, fulfilled]) => {
|
||||
data.pendingPOCount = pending.total
|
||||
data.awaitingConfirmCount = awaiting.total
|
||||
data.totalPOCount = all.total
|
||||
data.fulfilledPOCount = fulfilled.total
|
||||
}).catch(() => {})
|
||||
)
|
||||
}
|
||||
|
||||
if (activeIds.has('openRides')) {
|
||||
fetches.push(
|
||||
rides.list({ status: 'Open', pageSize: 5 })
|
||||
.then(res => {
|
||||
data.openRides = getPaginatedItems(res).map(r => ({
|
||||
id: r.id, vehicleNumberPlate: r.vehicleNumberPlate, driverFullName: r.driverFullName,
|
||||
}))
|
||||
})
|
||||
.catch(() => {})
|
||||
)
|
||||
}
|
||||
|
||||
if (activeIds.has('loadingSheetsByStatus')) {
|
||||
fetches.push(
|
||||
Promise.all([
|
||||
loadingSheets.list({ status: 'Planned', pageSize: 1 }),
|
||||
loadingSheets.list({ status: 'Confirmed', pageSize: 1 }),
|
||||
]).then(([planned, confirmed]) => {
|
||||
data.plannedSheetsCount = planned.total
|
||||
data.confirmedSheetsCount = confirmed.total
|
||||
}).catch(() => {})
|
||||
)
|
||||
}
|
||||
|
||||
if (activeIds.has('deliveryTasks')) {
|
||||
fetches.push(
|
||||
Promise.all([
|
||||
deliveryTasks.list({ status: 'Pending', pageSize: 1 }),
|
||||
deliveryTasks.list({ status: 'PartiallyDelivered', pageSize: 1 }),
|
||||
]).then(([pending, partial]) => {
|
||||
data.pendingTasksCount = pending.total
|
||||
data.partialTasksCount = partial.total
|
||||
}).catch(() => {})
|
||||
)
|
||||
}
|
||||
|
||||
if (activeIds.has('lowStock')) {
|
||||
fetches.push(
|
||||
stock.lowStock()
|
||||
.then(res => { data.lowStock = getPaginatedItems(res).slice(0, 5) })
|
||||
.catch(() => {})
|
||||
)
|
||||
}
|
||||
|
||||
if (activeIds.has('stockMovements')) {
|
||||
fetches.push(
|
||||
stock.movements({ pageSize: 5 })
|
||||
.then(res => { data.movements = getPaginatedItems(res) })
|
||||
.catch(() => {})
|
||||
)
|
||||
}
|
||||
|
||||
if (activeIds.has('warehouseBalance')) {
|
||||
fetches.push(
|
||||
stock.balances({ locationType: 'Warehouse', pageSize: 300 })
|
||||
.then(res => {
|
||||
const byWarehouse = new Map<string, WarehouseBalanceRow>()
|
||||
for (const b of getPaginatedItems(res)) {
|
||||
const existing = byWarehouse.get(b.locationId)
|
||||
if (existing) existing.quantity += b.quantity
|
||||
else byWarehouse.set(b.locationId, { locationId: b.locationId, name: b.locationName, quantity: b.quantity })
|
||||
}
|
||||
data.warehouseBalances = Array.from(byWarehouse.values())
|
||||
.sort((a, b) => b.quantity - a.quantity)
|
||||
.slice(0, 5)
|
||||
})
|
||||
.catch(() => {})
|
||||
)
|
||||
}
|
||||
|
||||
if (activeIds.has('outstandingPay')) {
|
||||
fetches.push(
|
||||
invoices.outstandingSummary()
|
||||
.then(res => {
|
||||
data.outstandingAmount = res.outstandingAmount
|
||||
data.outstandingInvoiceCount = res.invoiceCount
|
||||
})
|
||||
.catch(() => {})
|
||||
)
|
||||
}
|
||||
|
||||
if (activeIds.has('invoiceStatus')) {
|
||||
fetches.push(
|
||||
Promise.all([
|
||||
invoices.list({ status: 'Draft', pageSize: 1 }),
|
||||
invoices.list({ status: 'Printed', pageSize: 1 }),
|
||||
invoices.list({ status: 'Finalized', pageSize: 1 }),
|
||||
]).then(([draft, printed, finalized]) => {
|
||||
data.draftInvoiceCount = draft.total
|
||||
data.printedInvoiceCount = printed.total
|
||||
data.finalizedInvoiceCount = finalized.total
|
||||
}).catch(() => {})
|
||||
)
|
||||
}
|
||||
|
||||
await Promise.all(fetches)
|
||||
return data
|
||||
}
|
||||
|
||||
function CategoryPill({ cat }: { cat: Category }) {
|
||||
const meta = CATEGORY_META[cat]
|
||||
return (
|
||||
@@ -462,6 +533,7 @@ function mergeLayoutsChange(
|
||||
}
|
||||
|
||||
export function DashboardClient() {
|
||||
const { hasPermission } = useAuth()
|
||||
const [data, setData] = useState<DashboardData | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [state, setState] = useState<DashboardLayoutState>(defaultLayoutState)
|
||||
@@ -470,6 +542,16 @@ export function DashboardClient() {
|
||||
const [category, setCategory] = useState<'all' | Category>('all')
|
||||
const { width, containerRef, mounted } = useContainerWidth({ initialWidth: 1200 })
|
||||
|
||||
const allowedIds = useMemo(
|
||||
() => new Set(WIDGET_META.filter(w => hasPermission(w.permission)).map(w => w.id)),
|
||||
[hasPermission],
|
||||
)
|
||||
|
||||
const permittedActiveIds = useMemo(
|
||||
() => state.activeIds.filter(id => allowedIds.has(id)),
|
||||
[state.activeIds, allowedIds],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
setState(loadStoredLayoutState())
|
||||
}, [])
|
||||
@@ -486,13 +568,13 @@ export function DashboardClient() {
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
setData(await loadDashboardData())
|
||||
setData(await loadDashboardData(new Set(permittedActiveIds)))
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to load dashboard', description: getApiError(err), type: 'error' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
}, [permittedActiveIds])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
@@ -525,11 +607,11 @@ export function DashboardClient() {
|
||||
}
|
||||
|
||||
const visibleWidgets = useMemo(
|
||||
() => state.activeIds
|
||||
() => permittedActiveIds
|
||||
.map(id => WIDGET_META.find(w => w.id === id))
|
||||
.filter((w): w is WidgetMeta => Boolean(w))
|
||||
.filter(w => category === 'all' || w.cat === category),
|
||||
[state.activeIds, category],
|
||||
[permittedActiveIds, category],
|
||||
)
|
||||
|
||||
const visibleLayouts = useMemo(() => {
|
||||
@@ -577,7 +659,7 @@ export function DashboardClient() {
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
{WIDGET_META.map(w => {
|
||||
{WIDGET_META.filter(w => allowedIds.has(w.id)).map(w => {
|
||||
const checked = state.activeIds.includes(w.id)
|
||||
return (
|
||||
<label
|
||||
|
||||
@@ -120,7 +120,7 @@ export function GrnTaxCard() {
|
||||
setSettings(s => ({ ...s, [field]: value }))
|
||||
setPending(p => ({ ...p, [configKey]: true }))
|
||||
try {
|
||||
await sysConfig.set(configKey, String(value), user.id)
|
||||
await sysConfig.set(configKey, String(value), user?.userId)
|
||||
} catch (err) {
|
||||
setSettings(s => ({ ...s, [field]: previous }))
|
||||
toast.add({ title: 'Failed to update configuration', description: getApiError(err), type: 'error' })
|
||||
|
||||
+2
-2
@@ -92,7 +92,7 @@ export function ProductCapabilitiesCard() {
|
||||
setForm(f => ({ ...f, [formKey]: value }))
|
||||
setPendingKeys(p => ({ ...p, [configKey]: true }))
|
||||
try {
|
||||
await sysConfig.set(configKey, String(value), user.id)
|
||||
await sysConfig.set(configKey, String(value), user?.userId)
|
||||
} catch (err) {
|
||||
setForm(f => ({ ...f, [formKey]: previous }))
|
||||
toast.add({ title: 'Failed to update configuration', description: getApiError(err), type: 'error' })
|
||||
@@ -107,7 +107,7 @@ export function ProductCapabilitiesCard() {
|
||||
if (value === previous) return
|
||||
setPendingKeys(p => ({ ...p, [ITEM_TRACKING_KEYS.defaultWarrantyPeriodDays]: true }))
|
||||
try {
|
||||
await sysConfig.set(ITEM_TRACKING_KEYS.defaultWarrantyPeriodDays, String(value), user.id)
|
||||
await sysConfig.set(ITEM_TRACKING_KEYS.defaultWarrantyPeriodDays, String(value), user?.userId)
|
||||
} catch (err) {
|
||||
setForm(f => ({ ...f, defaultWarrantyPeriodDays: previous }))
|
||||
toast.add({ title: 'Failed to update configuration', description: getApiError(err), type: 'error' })
|
||||
|
||||
@@ -50,7 +50,9 @@ export function RegionSheet({ open, onClose, region, readOnly = false, onSuccess
|
||||
.then((res) => {
|
||||
if (!form.getValues('code')) form.setValue('code', res.code)
|
||||
})
|
||||
.catch(() => {})
|
||||
.catch(() => {
|
||||
toast.add({ title: 'Could not suggest a code — enter one manually', type: 'warning' })
|
||||
})
|
||||
}
|
||||
}
|
||||
}, [open, region])
|
||||
|
||||
@@ -39,7 +39,11 @@ export default function NewPriceListPage() {
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
regionsApi.list({ pageSize: 100 }).then((res) => setRegionsList(getPaginatedItems(res))).catch(() => {})
|
||||
regionsApi.list({ pageSize: 100 })
|
||||
.then((res) => setRegionsList(getPaginatedItems(res)))
|
||||
.catch(() => {
|
||||
toast.add({ title: 'Failed to load regions', type: 'error' })
|
||||
})
|
||||
}, [])
|
||||
|
||||
async function onSubmit(values: FormValues) {
|
||||
|
||||
@@ -86,7 +86,11 @@ export function SchemeSheet({ open, onClose, scheme, onSuccess }: SchemeSheetPro
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
regionsApi.list({ pageSize: 100 }).then((res) => setRegionsList(getPaginatedItems(res))).catch(() => {})
|
||||
regionsApi.list({ pageSize: 100 })
|
||||
.then((res) => setRegionsList(getPaginatedItems(res)))
|
||||
.catch(() => {
|
||||
toast.add({ title: 'Failed to load regions', type: 'error' })
|
||||
})
|
||||
}
|
||||
}, [open])
|
||||
|
||||
|
||||
@@ -1,110 +1,97 @@
|
||||
'use client'
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect } 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 {
|
||||
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { toast } from '@/components/ui/toast'
|
||||
import { users as usersApi, roles as rolesApi, getApiError } from '@/lib/api/index'
|
||||
import { users as usersApi, getApiError } from '@/lib/api/index'
|
||||
import type { UserResponse, RoleResponse } from '@/types/api'
|
||||
|
||||
const createSchema = z.object({
|
||||
fullName: z.string().min(1, 'Full name is required'),
|
||||
username: z.string().min(1, 'Username is required'),
|
||||
roleId: z.string().min(1, 'Role is required'),
|
||||
username: z.string().email('Must be a valid email'),
|
||||
password: z.string().min(6, 'Password must be at least 6 characters'),
|
||||
isActive: z.boolean(),
|
||||
fullName: z.string().min(1, 'Full name is required'),
|
||||
roleId: z.string().min(1, 'Role is required'),
|
||||
reportsToUserId: z.string().optional(),
|
||||
})
|
||||
|
||||
const editSchema = z.object({
|
||||
fullName: z.string().min(1, 'Full name is required'),
|
||||
username: z.string().min(1, 'Username is required'),
|
||||
roleId: z.string().min(1, 'Role is required'),
|
||||
isActive: z.boolean(),
|
||||
})
|
||||
|
||||
type CreateFormValues = z.infer<typeof createSchema>
|
||||
type EditFormValues = z.infer<typeof editSchema>
|
||||
type CreateValues = z.infer<typeof createSchema>
|
||||
type EditValues = z.infer<typeof editSchema>
|
||||
|
||||
interface UserSheetProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
user: UserResponse | null
|
||||
roles: RoleResponse[]
|
||||
users: UserResponse[]
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export function UserSheet({ open, onClose, user, onSuccess }: UserSheetProps) {
|
||||
export function UserSheet({ open, onClose, user, roles, users, onSuccess }: UserSheetProps) {
|
||||
const isEdit = !!user
|
||||
const [roles, setRoles] = useState<RoleResponse[]>([])
|
||||
|
||||
const createForm = useForm<CreateFormValues>({
|
||||
const createForm = useForm<CreateValues>({
|
||||
resolver: zodResolver(createSchema),
|
||||
defaultValues: { fullName: '', username: '', roleId: '', password: '', isActive: true },
|
||||
defaultValues: { username: '', password: '', fullName: '', roleId: '', reportsToUserId: '' },
|
||||
})
|
||||
|
||||
const editForm = useForm<EditFormValues>({
|
||||
const editForm = useForm<EditValues>({
|
||||
resolver: zodResolver(editSchema),
|
||||
defaultValues: { fullName: '', username: '', roleId: '', isActive: true },
|
||||
defaultValues: { fullName: '', roleId: '' },
|
||||
})
|
||||
|
||||
const form = isEdit ? editForm : createForm
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
rolesApi.list().then(setRoles).catch((err) =>
|
||||
toast.add({ title: 'Failed to load roles', description: getApiError(err), type: 'error' })
|
||||
)
|
||||
|
||||
if (isEdit && user) {
|
||||
editForm.reset({
|
||||
fullName: user.fullName,
|
||||
username: user.username,
|
||||
roleId: user.roleId,
|
||||
isActive: user.isActive,
|
||||
})
|
||||
if (user) {
|
||||
editForm.reset({ fullName: user.fullName, roleId: user.roleId })
|
||||
} else {
|
||||
createForm.reset({ fullName: '', username: '', roleId: '', password: '', isActive: true })
|
||||
createForm.reset({ username: '', password: '', fullName: '', roleId: '', reportsToUserId: '' })
|
||||
}
|
||||
}
|
||||
}, [open, user])
|
||||
|
||||
async function onSubmitCreate(values: CreateFormValues) {
|
||||
async function onCreateSubmit(values: CreateValues) {
|
||||
try {
|
||||
await usersApi.create(values)
|
||||
await usersApi.create({
|
||||
username: values.username,
|
||||
password: values.password,
|
||||
fullName: values.fullName,
|
||||
roleId: values.roleId,
|
||||
reportsToUserId: values.reportsToUserId || null,
|
||||
})
|
||||
toast.add({ title: 'User created', type: 'success' })
|
||||
onSuccess()
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to save', description: getApiError(err), type: 'error' })
|
||||
toast.add({ title: 'Failed to create user', description: getApiError(err), type: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
async function onSubmitEdit(values: EditFormValues) {
|
||||
async function onEditSubmit(values: EditValues) {
|
||||
try {
|
||||
await usersApi.update(user!.id, values)
|
||||
await usersApi.update(user!.id, { fullName: values.fullName })
|
||||
if (values.roleId !== user!.roleId) {
|
||||
await usersApi.assignRole(user!.id, values.roleId)
|
||||
}
|
||||
toast.add({ title: 'User updated', type: 'success' })
|
||||
onSuccess()
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to save', description: getApiError(err), type: 'error' })
|
||||
toast.add({ title: 'Failed to update user', description: getApiError(err), type: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,12 +101,12 @@ export function UserSheet({ open, onClose, user, onSuccess }: UserSheetProps) {
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEdit ? 'Edit User' : 'Add User'}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{isEdit ? 'Update the user details below.' : 'Create a new staff account.'}
|
||||
{isEdit ? 'Update user details and role.' : 'Create a new staff account.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isEdit ? (
|
||||
<form onSubmit={editForm.handleSubmit(onSubmitEdit)} className="flex flex-col gap-6">
|
||||
<form onSubmit={editForm.handleSubmit(onEditSubmit)} className="flex flex-col gap-6">
|
||||
<FieldGroup>
|
||||
<FormField
|
||||
control={editForm.control}
|
||||
@@ -134,31 +121,11 @@ export function UserSheet({ open, onClose, user, onSuccess }: UserSheetProps) {
|
||||
value={field.value as string}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="e.g. John Smith"
|
||||
placeholder="e.g. Nimal Perera"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={editForm.control}
|
||||
name="username"
|
||||
label="Username"
|
||||
required
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
id="username"
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
value={field.value as string}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="e.g. john.smith"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={editForm.control}
|
||||
name="roleId"
|
||||
@@ -167,49 +134,46 @@ export function UserSheet({ open, onClose, user, onSuccess }: UserSheetProps) {
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a role" />
|
||||
<SelectValue placeholder="Select role" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{roles.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>
|
||||
{r.name}
|
||||
</SelectItem>
|
||||
<SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={editForm.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>
|
||||
)}
|
||||
/>
|
||||
</FieldGroup>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
|
||||
<Button type="submit" disabled={editForm.formState.isSubmitting}>
|
||||
{editForm.formState.isSubmitting ? 'Saving…' : 'Save Changes'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
) : (
|
||||
<form onSubmit={createForm.handleSubmit(onSubmitCreate)} className="flex flex-col gap-6">
|
||||
<form onSubmit={createForm.handleSubmit(onCreateSubmit)} className="flex flex-col gap-6">
|
||||
<FieldGroup>
|
||||
<FormField
|
||||
control={createForm.control}
|
||||
name="username"
|
||||
label="Email"
|
||||
required
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
id="username"
|
||||
type="email"
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
value={field.value as string}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="e.g. nimal.perera@company.com"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={createForm.control}
|
||||
name="fullName"
|
||||
@@ -223,52 +187,11 @@ export function UserSheet({ open, onClose, user, onSuccess }: UserSheetProps) {
|
||||
value={field.value as string}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="e.g. John Smith"
|
||||
placeholder="e.g. Nimal Perera"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={createForm.control}
|
||||
name="username"
|
||||
label="Username"
|
||||
required
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
id="username"
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
value={field.value as string}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="e.g. john.smith"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={createForm.control}
|
||||
name="roleId"
|
||||
label="Role"
|
||||
required
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a role" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{roles.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>
|
||||
{r.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={createForm.control}
|
||||
name="password"
|
||||
@@ -277,42 +200,57 @@ export function UserSheet({ open, onClose, user, onSuccess }: UserSheetProps) {
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
type="password"
|
||||
value={field.value as string}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="Min. 6 characters"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={createForm.control}
|
||||
name="isActive"
|
||||
name="roleId"
|
||||
label="Role"
|
||||
required
|
||||
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 role" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{roles.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={createForm.control}
|
||||
name="reportsToUserId"
|
||||
label="Reports To"
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="None" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="">None</SelectItem>
|
||||
{users.map((u) => (
|
||||
<SelectItem key={u.id} value={u.id}>{u.fullName}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
</FieldGroup>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
|
||||
<Button type="submit" disabled={createForm.formState.isSubmitting}>
|
||||
{createForm.formState.isSubmitting ? 'Saving…' : 'Create User'}
|
||||
{createForm.formState.isSubmitting ? 'Creating…' : 'Create User'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
'use client'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import type { UserResponse } from '@/types/api'
|
||||
|
||||
const fmtDate = (v: string) =>
|
||||
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
|
||||
|
||||
function Row({ label, value }: { label: string; value: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between py-2 text-sm border-b last:border-0">
|
||||
<span className="text-muted-foreground">{label}</span>
|
||||
<span className="font-medium text-right">{value}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface UserViewSheetProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
user: UserResponse | null
|
||||
}
|
||||
|
||||
export function UserViewSheet({ open, onClose, user }: UserViewSheetProps) {
|
||||
if (!user) return null
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
|
||||
<DialogContent className="overflow-y-auto sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>User Details</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col">
|
||||
<Row label="Username" value={user.username} />
|
||||
<Row label="Full Name" value={user.fullName} />
|
||||
<Row label="Role" value={user.roleName} />
|
||||
<Row label="Status" value={
|
||||
<Badge variant={user.isActive ? 'default' : 'secondary'}>
|
||||
{user.isActive ? 'Active' : 'Inactive'}
|
||||
</Badge>
|
||||
} />
|
||||
<Row label="Created" value={fmtDate(user.createdAt)} />
|
||||
{user.updatedAt && <Row label="Updated" value={fmtDate(user.updatedAt)} />}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
'use client'
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||
import { HugeiconsIcon } from '@hugeicons/react'
|
||||
@@ -8,28 +8,37 @@ import { DataTable } from '@/components/shared/data-table'
|
||||
import type { TableConfig } from '@/components/shared/data-table'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { toast } from '@/components/ui/toast'
|
||||
import { users as usersApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||
import type { UserResponse } from '@/types/api'
|
||||
import { users as usersApi, roles as rolesApi, getApiError } from '@/lib/api/index'
|
||||
import type { UserResponse, RoleResponse } from '@/types/api'
|
||||
|
||||
import { UserSheet } from './user-sheet'
|
||||
import { UserViewSheet } from './user-view-sheet'
|
||||
|
||||
export function UsersClient() {
|
||||
const [data, setData] = useState<UserResponse[]>([])
|
||||
const [rolesList, setRolesList] = useState<RoleResponse[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(20)
|
||||
|
||||
const [sheetOpen, setSheetOpen] = useState(false)
|
||||
const [editing, setEditing] = useState<UserResponse | null>(null)
|
||||
const [viewOpen, setViewOpen] = useState(false)
|
||||
const [viewing, setViewing] = useState<UserResponse | null>(null)
|
||||
const [confirmTarget, setConfirmTarget] = useState<UserResponse | null>(null)
|
||||
const [deactivating, setDeactivating] = useState(false)
|
||||
|
||||
const fetchData = useCallback(async (p: number, ps: number) => {
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await usersApi.list({ page: p, pageSize: ps })
|
||||
setData(getPaginatedItems(res))
|
||||
setTotal(res.total)
|
||||
const [items, roles] = await Promise.all([usersApi.list(), rolesApi.list()])
|
||||
setData(items)
|
||||
setTotal(items.length)
|
||||
setRolesList(roles)
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to load users', description: getApiError(err), type: 'error' })
|
||||
} finally {
|
||||
@@ -37,54 +46,48 @@ export function UsersClient() {
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData(page, pageSize)
|
||||
}, [fetchData, page, pageSize])
|
||||
useEffect(() => { fetchData() }, [fetchData])
|
||||
|
||||
function openCreate() {
|
||||
setEditing(null)
|
||||
setSheetOpen(true)
|
||||
}
|
||||
function openCreate() { setEditing(null); setSheetOpen(true) }
|
||||
function openEdit(user: UserResponse) { setEditing(user); setSheetOpen(true) }
|
||||
function openView(user: UserResponse) { setViewing(user); setViewOpen(true) }
|
||||
|
||||
function openEdit(user: UserResponse) {
|
||||
setEditing(user)
|
||||
setSheetOpen(true)
|
||||
}
|
||||
|
||||
async function toggleActive(user: UserResponse) {
|
||||
async function confirmDeactivate() {
|
||||
if (!confirmTarget) return
|
||||
setDeactivating(true)
|
||||
try {
|
||||
await usersApi.update(user.id, { isActive: !user.isActive })
|
||||
toast.add({
|
||||
title: user.isActive ? 'User deactivated' : 'User activated',
|
||||
type: 'success',
|
||||
})
|
||||
fetchData(page, pageSize)
|
||||
await usersApi.deactivate(confirmTarget.id)
|
||||
toast.add({ title: 'User deactivated', type: 'success' })
|
||||
setConfirmTarget(null)
|
||||
fetchData()
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to update user', description: getApiError(err), type: 'error' })
|
||||
toast.add({ title: 'Failed to deactivate user', description: getApiError(err), type: 'error' })
|
||||
} finally {
|
||||
setDeactivating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const tableConfig = useMemo<TableConfig<UserResponse>>(() => ({
|
||||
rowKey: 'id',
|
||||
serverSide: true,
|
||||
stickyHeader: true,
|
||||
emptyMessage: 'No users yet. Add one to get started.',
|
||||
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
|
||||
columns: [
|
||||
{
|
||||
key: 'fullName',
|
||||
title: 'Name',
|
||||
fields: ['fullName', 'username'],
|
||||
minWidth: 200,
|
||||
cellRender: (row) => (
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-medium">{row.fullName}</span>
|
||||
<span className="text-xs text-muted-foreground">{row.username}</span>
|
||||
</div>
|
||||
),
|
||||
key: 'username',
|
||||
title: 'Username',
|
||||
fields: [{ key: 'username', primary: true }],
|
||||
sortable: true,
|
||||
minWidth: 160,
|
||||
},
|
||||
{
|
||||
key: 'roleName',
|
||||
key: 'fullName',
|
||||
title: 'Full Name',
|
||||
fields: [{ key: 'fullName' }],
|
||||
minWidth: 180,
|
||||
},
|
||||
{
|
||||
key: 'role',
|
||||
title: 'Role',
|
||||
fields: [{ key: 'roleName' }],
|
||||
minWidth: 140,
|
||||
@@ -93,45 +96,35 @@ export function UsersClient() {
|
||||
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 user',
|
||||
onClick: openEdit,
|
||||
},
|
||||
{
|
||||
action: 'deactivate',
|
||||
label: 'Deactivate user',
|
||||
onClick: toggleActive,
|
||||
visible: (target) => target.isActive,
|
||||
},
|
||||
{
|
||||
action: 'activate',
|
||||
label: 'Activate user',
|
||||
onClick: toggleActive,
|
||||
visible: (target) => !target.isActive,
|
||||
},
|
||||
{ action: 'view', label: 'View user', onClick: openView },
|
||||
{ action: 'edit', label: 'Edit user', onClick: openEdit },
|
||||
{ action: 'cancel', label: 'Deactivate user', onClick: (u) => setConfirmTarget(u), visible: (t) => t.isActive },
|
||||
],
|
||||
},
|
||||
}), [pageSize, openEdit, toggleActive])
|
||||
}), [pageSize])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-foreground">Users</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
Staff accounts and their role assignments
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">Staff accounts and their role assignments</p>
|
||||
</div>
|
||||
<Button onClick={openCreate}>
|
||||
<HugeiconsIcon icon={Add01Icon} size={16} />
|
||||
@@ -144,18 +137,43 @@ export function UsersClient() {
|
||||
data={data}
|
||||
loading={loading}
|
||||
totalCount={total}
|
||||
onServerSideChange={({ page: p }) => {
|
||||
setPage(p.page)
|
||||
setPageSize(p.pageSize)
|
||||
}}
|
||||
onServerSideChange={({ page: p }) => setPageSize(p.pageSize)}
|
||||
/>
|
||||
|
||||
<UserSheet
|
||||
open={sheetOpen}
|
||||
onClose={() => setSheetOpen(false)}
|
||||
user={editing}
|
||||
onSuccess={() => fetchData(page, pageSize)}
|
||||
roles={rolesList}
|
||||
users={data}
|
||||
onSuccess={() => fetchData()}
|
||||
/>
|
||||
|
||||
<UserViewSheet
|
||||
open={viewOpen}
|
||||
onClose={() => setViewOpen(false)}
|
||||
user={viewing}
|
||||
/>
|
||||
|
||||
<Dialog open={!!confirmTarget} onOpenChange={(v) => !v && setConfirmTarget(null)}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Deactivate user?</DialogTitle>
|
||||
<DialogDescription>
|
||||
<span className="font-medium text-foreground">{confirmTarget?.fullName}</span>
|
||||
{' '}({confirmTarget?.username}) will lose access immediately. This cannot be undone from here.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setConfirmTarget(null)} disabled={deactivating}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={confirmDeactivate} disabled={deactivating}>
|
||||
{deactivating ? 'Deactivating…' : 'Deactivate'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { UsersClient } from './_components/users-client'
|
||||
import { UsersClient } from './_components/users-client'
|
||||
|
||||
export default function UsersPage() {
|
||||
return <UsersClient />
|
||||
|
||||
@@ -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 />
|
||||
|
||||
@@ -25,32 +25,26 @@ import {
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip'
|
||||
import { useAuth, type Role } from '@/contexts/auth-context'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useAuth } from '@/contexts/auth-context'
|
||||
import { DASHBOARD_ITEM, CONFIGURATION_ITEM, NAV_GROUPS, type NavGroup, type NavItem } from '@/config/nav'
|
||||
|
||||
function canSee(item: NavItem, permissions: string[]): boolean {
|
||||
function canSee(item: NavItem, permissions: Set<string>): boolean {
|
||||
if (!item.permission) return true
|
||||
return permissions.includes('*') || permissions.includes(item.permission)
|
||||
return permissions.has(item.permission)
|
||||
}
|
||||
|
||||
function isGroupVisible(group: NavGroup, permissions: string[]): boolean {
|
||||
function isGroupVisible(group: NavGroup, permissions: Set<string>): boolean {
|
||||
return group.items.some((item) => canSee(item, permissions))
|
||||
}
|
||||
|
||||
export function AppSidebar() {
|
||||
const { user, setRole, permissions } = useAuth()
|
||||
const { user, permissions, logout } = useAuth()
|
||||
const pathname = usePathname()
|
||||
|
||||
const dashboardActive = pathname === DASHBOARD_ITEM.href
|
||||
@@ -137,7 +131,6 @@ export function AppSidebar() {
|
||||
>
|
||||
<SidebarGroup className="py-0">
|
||||
<SidebarMenu>
|
||||
{/* Group trigger — looks like a regular nav button */}
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
render={<CollapsibleTrigger />}
|
||||
@@ -154,7 +147,6 @@ export function AppSidebar() {
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
|
||||
{/* Sub-items with indent line */}
|
||||
<CollapsibleContent>
|
||||
<SidebarMenuSub>
|
||||
{visibleItems.map((item) => {
|
||||
@@ -186,20 +178,22 @@ export function AppSidebar() {
|
||||
})}
|
||||
|
||||
{/* Configuration — standalone, no sub-nav */}
|
||||
<SidebarGroup className="py-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
render={<Link href={CONFIGURATION_ITEM.href} />}
|
||||
isActive={configurationActive}
|
||||
tooltip={CONFIGURATION_ITEM.title}
|
||||
>
|
||||
<HugeiconsIcon icon={CONFIGURATION_ITEM.icon} size={18} />
|
||||
<span>{CONFIGURATION_ITEM.title}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
{canSee(CONFIGURATION_ITEM, permissions) && (
|
||||
<SidebarGroup className="py-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
render={<Link href={CONFIGURATION_ITEM.href} />}
|
||||
isActive={configurationActive}
|
||||
tooltip={CONFIGURATION_ITEM.title}
|
||||
>
|
||||
<HugeiconsIcon icon={CONFIGURATION_ITEM.icon} size={18} />
|
||||
<span>{CONFIGURATION_ITEM.title}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
)}
|
||||
</SidebarContent>
|
||||
|
||||
<SidebarFooter>
|
||||
@@ -209,18 +203,16 @@ export function AppSidebar() {
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 flex-col group-data-[collapsible=icon]:hidden">
|
||||
<span className="truncate text-sm font-medium text-sidebar-foreground">
|
||||
{user.fullName}
|
||||
{user?.username ?? '—'}
|
||||
</span>
|
||||
<Select value={user.role} onValueChange={(v) => setRole(v as Role)}>
|
||||
<SelectTrigger className="h-5 border-0 p-0 text-xs text-muted-foreground shadow-none focus:ring-0">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
<SelectItem value="warehouse">Warehouse</SelectItem>
|
||||
<SelectItem value="sales">Sales</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={logout}
|
||||
className="h-auto justify-start p-0 text-xs text-muted-foreground hover:text-foreground hover:bg-transparent"
|
||||
>
|
||||
Sign out
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</SidebarFooter>
|
||||
|
||||
@@ -16,7 +16,7 @@ export function BottomNav() {
|
||||
|
||||
const visibleItems: NavItem[] = BOTTOM_NAV_CANDIDATES.filter((item) => {
|
||||
if (!item.permission) return true
|
||||
return permissions.includes('*') || permissions.includes(item.permission)
|
||||
return permissions.has(item.permission)
|
||||
}).slice(0, MAX_TABS)
|
||||
|
||||
return (
|
||||
|
||||
@@ -55,6 +55,7 @@ export const CONFIGURATION_ITEM: NavItem = {
|
||||
title: 'Configuration',
|
||||
href: '/configuration',
|
||||
icon: Settings01Icon,
|
||||
permission: 'sys-config.view',
|
||||
}
|
||||
|
||||
export const NAV_GROUPS: NavGroup[] = [
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
export interface PermissionCategory {
|
||||
id: string
|
||||
label: string
|
||||
codes: string[]
|
||||
}
|
||||
|
||||
export const PERMISSION_CATEGORIES: PermissionCategory[] = [
|
||||
{
|
||||
id: 'sales',
|
||||
label: 'Sales & Orders',
|
||||
codes: [
|
||||
'orders.view',
|
||||
'stores.view',
|
||||
'store.view',
|
||||
'store.manage',
|
||||
'sales_visits.checkin',
|
||||
'return.view',
|
||||
'return.manage',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'operations',
|
||||
label: 'Operations',
|
||||
codes: [
|
||||
'rides.view',
|
||||
'loading.view',
|
||||
'loading-sheet.view',
|
||||
'loading-sheet.manage',
|
||||
'delivery-task.view',
|
||||
'delivery-task.manage',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'stock',
|
||||
label: 'Stock & Inventory',
|
||||
codes: [
|
||||
'warehouses.view',
|
||||
'stock.view',
|
||||
'stock.manage',
|
||||
'items.view',
|
||||
'categories.view',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'procurement',
|
||||
label: 'Procurement',
|
||||
codes: [
|
||||
'purchase_orders.view',
|
||||
'purchase-order.view',
|
||||
'purchase-order.manage',
|
||||
'purchase-return.manage',
|
||||
'grn.view',
|
||||
'grn.manage',
|
||||
'suppliers.view',
|
||||
'supplier-claim.view',
|
||||
'supplier-claim.manage',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'pricing',
|
||||
label: 'Pricing',
|
||||
codes: [
|
||||
'pricelists.view',
|
||||
'price-list.view',
|
||||
'price-list.manage',
|
||||
'schemes.view',
|
||||
'scheme.view',
|
||||
'scheme.manage',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'claims',
|
||||
label: 'Claims',
|
||||
codes: [
|
||||
'claim.view',
|
||||
'claim.manage',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'network',
|
||||
label: 'Network & Routes',
|
||||
codes: [
|
||||
'regions.view',
|
||||
'region.view',
|
||||
'region.manage',
|
||||
'routes.view',
|
||||
'route.view',
|
||||
'route.manage',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'fleet',
|
||||
label: 'Fleet & Drivers',
|
||||
codes: [
|
||||
'vehicles.view',
|
||||
'driver_profiles.view',
|
||||
'driver.view',
|
||||
'driver.manage',
|
||||
'compliance.manage',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'users',
|
||||
label: 'User Management',
|
||||
codes: [
|
||||
'users.view',
|
||||
'roles.view',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'system',
|
||||
label: 'System',
|
||||
codes: [
|
||||
'sys-config.view',
|
||||
'sys-config.manage',
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export const ALL_PERMISSION_CODES = new Set(
|
||||
PERMISSION_CATEGORIES.flatMap((c) => c.codes),
|
||||
)
|
||||
|
||||
export function getCategoryForCode(code: string): PermissionCategory | undefined {
|
||||
return PERMISSION_CATEGORIES.find((c) => c.codes.includes(code))
|
||||
}
|
||||
@@ -1,101 +1,109 @@
|
||||
'use client'
|
||||
|
||||
import { createContext, useContext, useState, type ReactNode } from 'react'
|
||||
import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { api, registerUnauthorizedHandler } from '@/lib/api'
|
||||
|
||||
export type Role = 'admin' | 'warehouse' | 'sales'
|
||||
|
||||
export interface MockUser {
|
||||
id: string
|
||||
fullName: string
|
||||
export interface User {
|
||||
userId: string
|
||||
username: string
|
||||
roleId: string
|
||||
role: Role
|
||||
roleCode: string
|
||||
roleLevel: number
|
||||
}
|
||||
|
||||
interface AuthContextValue {
|
||||
user: MockUser
|
||||
permissions: string[]
|
||||
setRole: (role: Role) => void
|
||||
user: User | null
|
||||
permissions: Set<string>
|
||||
loading: boolean
|
||||
login: (identifier: string, password: string) => Promise<void>
|
||||
logout: () => Promise<void>
|
||||
hasPermission: (code: string) => boolean
|
||||
}
|
||||
|
||||
// Mock permissions per role — replace with real API call once auth is implemented
|
||||
const MOCK_PERMISSIONS: Record<Role, string[]> = {
|
||||
admin: ['*'],
|
||||
warehouse: [
|
||||
'items.view',
|
||||
'categories.view',
|
||||
'regions.view',
|
||||
'routes.view',
|
||||
'vehicles.view',
|
||||
'warehouses.view',
|
||||
'loading.view',
|
||||
'loading.dispatch',
|
||||
'loading.receive',
|
||||
'loading.resolve',
|
||||
'rides.view',
|
||||
'rides.manage',
|
||||
'rides.cancel.request',
|
||||
'driver_profiles.view',
|
||||
'compliance.manage',
|
||||
],
|
||||
sales: [
|
||||
'stores.view',
|
||||
'stores.create',
|
||||
'stores.update',
|
||||
'orders.view',
|
||||
'orders.create',
|
||||
'orders.update',
|
||||
'items.view',
|
||||
'categories.view',
|
||||
'regions.view',
|
||||
'routes.view',
|
||||
'rides.view',
|
||||
'driver_profiles.view',
|
||||
'sales_visits.checkin',
|
||||
],
|
||||
const PERMISSIONS_KEY = 'app:permissions'
|
||||
|
||||
function savePermissions(perms: string[]): void {
|
||||
try {
|
||||
localStorage.setItem(PERMISSIONS_KEY, JSON.stringify(perms))
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const MOCK_USERS: Record<Role, MockUser> = {
|
||||
admin: {
|
||||
id: '00000000-0000-0000-0000-000000000001',
|
||||
fullName: 'Admin User',
|
||||
username: 'admin',
|
||||
roleId: '00000000-0000-0000-0000-000000000010',
|
||||
role: 'admin',
|
||||
},
|
||||
warehouse: {
|
||||
id: '00000000-0000-0000-0000-000000000002',
|
||||
fullName: 'Warehouse Staff',
|
||||
username: 'warehouse',
|
||||
roleId: '00000000-0000-0000-0000-000000000011',
|
||||
role: 'warehouse',
|
||||
},
|
||||
sales: {
|
||||
id: '00000000-0000-0000-0000-000000000003',
|
||||
fullName: 'Sales Rep',
|
||||
username: 'sales',
|
||||
roleId: '00000000-0000-0000-0000-000000000012',
|
||||
role: 'sales',
|
||||
},
|
||||
function readPermissions(): Set<string> {
|
||||
try {
|
||||
const raw = localStorage.getItem(PERMISSIONS_KEY)
|
||||
if (raw) return new Set(JSON.parse(raw) as string[])
|
||||
} catch {}
|
||||
return new Set()
|
||||
}
|
||||
|
||||
function clearPermissions(): void {
|
||||
try {
|
||||
localStorage.removeItem(PERMISSIONS_KEY)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null)
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [role, setRoleState] = useState<Role>('admin')
|
||||
const router = useRouter()
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [permissions, setPermissions] = useState<Set<string>>(new Set())
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
function setRole(newRole: Role) {
|
||||
setRoleState(newRole)
|
||||
const loadSession = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const { data } = await api.get<User>('/auth/me')
|
||||
setUser(data)
|
||||
setPermissions(readPermissions())
|
||||
} catch {
|
||||
setUser(null)
|
||||
setPermissions(new Set())
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
loadSession()
|
||||
}, [loadSession])
|
||||
|
||||
useEffect(() => {
|
||||
return registerUnauthorizedHandler(() => {
|
||||
clearPermissions()
|
||||
setUser(null)
|
||||
setPermissions(new Set())
|
||||
router.push('/login')
|
||||
})
|
||||
}, [router])
|
||||
|
||||
async function login(identifier: string, password: string) {
|
||||
const { data: loginData } = await api.post<{ profile: User }>('/auth/login', { identifier, password, deviceName: 'Web' })
|
||||
setUser(loginData.profile)
|
||||
const { data: permData } = await api.get<{ permissions: string[] }>('/authorization/my-permissions')
|
||||
savePermissions(permData.permissions)
|
||||
setPermissions(new Set(permData.permissions))
|
||||
router.push('/')
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await api.post('/auth/logout')
|
||||
} finally {
|
||||
clearPermissions()
|
||||
setUser(null)
|
||||
setPermissions(new Set())
|
||||
router.push('/login')
|
||||
}
|
||||
}
|
||||
|
||||
function hasPermission(code: string): boolean {
|
||||
return permissions.has(code)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user: MOCK_USERS[role],
|
||||
permissions: MOCK_PERMISSIONS[role],
|
||||
setRole,
|
||||
}}
|
||||
>
|
||||
<AuthContext.Provider value={{ user, permissions, loading, login, logout, hasPermission }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
|
||||
@@ -4,17 +4,15 @@ import { useAuth } from '@/contexts/auth-context'
|
||||
|
||||
export function usePermission(permission: string): boolean {
|
||||
const { permissions } = useAuth()
|
||||
return permissions.includes('*') || permissions.includes(permission)
|
||||
return permissions.has(permission)
|
||||
}
|
||||
|
||||
export function usePermissions(codes: string[]): boolean[] {
|
||||
const { permissions } = useAuth()
|
||||
const isAdmin = permissions.includes('*')
|
||||
return codes.map((code) => isAdmin || permissions.includes(code))
|
||||
return codes.map((code) => permissions.has(code))
|
||||
}
|
||||
|
||||
export function useHasAnyPermission(codes: string[]): boolean {
|
||||
const { permissions } = useAuth()
|
||||
if (permissions.includes('*')) return true
|
||||
return codes.some((code) => permissions.includes(code))
|
||||
return codes.some((code) => permissions.has(code))
|
||||
}
|
||||
|
||||
+11
-14
@@ -3,32 +3,29 @@ import axios, { type AxiosError } from 'axios'
|
||||
export const api = axios.create({
|
||||
baseURL: process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:5089/api',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
withCredentials: true,
|
||||
})
|
||||
|
||||
// Inject auth token on every request
|
||||
api.interceptors.request.use((config) => {
|
||||
// TODO: replace with real token from cookie once auth is implemented
|
||||
const token = typeof window !== 'undefined'
|
||||
? document.cookie.split('; ').find(r => r.startsWith('access-token='))?.split('=')[1]
|
||||
: null
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
return config
|
||||
})
|
||||
type UnauthorizedHandler = () => void
|
||||
let unauthorizedHandler: UnauthorizedHandler | null = null
|
||||
|
||||
export function registerUnauthorizedHandler(fn: UnauthorizedHandler): () => void {
|
||||
unauthorizedHandler = fn
|
||||
return () => { unauthorizedHandler = null }
|
||||
}
|
||||
|
||||
// Normalize error responses
|
||||
api.interceptors.response.use(
|
||||
(res) => res,
|
||||
(error: AxiosError<{ error: string }>) => {
|
||||
const status = error.response?.status
|
||||
if (status === 401) {
|
||||
if (typeof window !== 'undefined') window.location.href = '/login'
|
||||
return new Promise(() => {}) // redirect in progress — never resolve so no error toast fires
|
||||
if (status === 401 && typeof window !== 'undefined' && window.location.pathname !== '/login') {
|
||||
unauthorizedHandler?.()
|
||||
return new Promise(() => {})
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// Helper to extract error message from API response
|
||||
export function getApiError(error: unknown): string {
|
||||
if (axios.isAxiosError(error)) {
|
||||
return error.response?.data?.error ?? error.message
|
||||
|
||||
@@ -1,41 +1,38 @@
|
||||
import { api } from '@/lib/api'
|
||||
import type {
|
||||
PaginatedResponse,
|
||||
UserResponse,
|
||||
RoleResponse,
|
||||
PermissionResponse,
|
||||
} from '@/types/api'
|
||||
|
||||
import type { PageParams } from './master'
|
||||
import type { UserResponse, RoleResponse, PermissionResponse } from '@/types/api'
|
||||
|
||||
// ─── Users ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface UserBody {
|
||||
export interface CreateUserBody {
|
||||
username: string
|
||||
password: string
|
||||
fullName: string
|
||||
roleId: string
|
||||
reportsToUserId?: string | null
|
||||
password?: string
|
||||
isActive?: boolean
|
||||
}
|
||||
|
||||
export interface UserListParams extends PageParams {
|
||||
roleId?: string
|
||||
search?: string
|
||||
export interface UpdateUserBody {
|
||||
fullName: string
|
||||
}
|
||||
|
||||
export const users = {
|
||||
list: (params?: UserListParams) =>
|
||||
api.get<PaginatedResponse<UserResponse>>('/users', { params }).then(r => r.data),
|
||||
list: () =>
|
||||
api.get<UserResponse[]>('/users').then(r => r.data),
|
||||
|
||||
get: (id: string) =>
|
||||
api.get<UserResponse>(`/users/${id}`).then(r => r.data),
|
||||
|
||||
create: (body: UserBody) =>
|
||||
create: (body: CreateUserBody) =>
|
||||
api.post<UserResponse>('/users', body).then(r => r.data),
|
||||
|
||||
update: (id: string, body: Partial<UserBody>) =>
|
||||
update: (id: string, body: UpdateUserBody) =>
|
||||
api.put<UserResponse>(`/users/${id}`, body).then(r => r.data),
|
||||
|
||||
assignRole: (id: string, roleId: string) =>
|
||||
api.put<UserResponse>(`/users/${id}/role`, { roleId }).then(r => r.data),
|
||||
|
||||
deactivate: (id: string) =>
|
||||
api.delete(`/users/${id}`),
|
||||
}
|
||||
|
||||
// ─── Roles ────────────────────────────────────────────────────────────────────
|
||||
@@ -43,11 +40,6 @@ export const users = {
|
||||
export interface RoleBody {
|
||||
name: string
|
||||
level: number
|
||||
isActive?: boolean
|
||||
}
|
||||
|
||||
export interface RoleWithPermissions extends RoleResponse {
|
||||
permissions: PermissionResponse[]
|
||||
}
|
||||
|
||||
export const roles = {
|
||||
@@ -55,16 +47,22 @@ export const roles = {
|
||||
api.get<RoleResponse[]>('/roles').then(r => r.data),
|
||||
|
||||
get: (id: string) =>
|
||||
api.get<RoleWithPermissions>(`/roles/${id}`).then(r => r.data),
|
||||
api.get<RoleResponse>(`/roles/${id}`).then(r => r.data),
|
||||
|
||||
getPermissions: (id: string) =>
|
||||
api.get<PermissionResponse[]>(`/roles/${id}/permissions`).then(r => r.data),
|
||||
|
||||
create: (body: RoleBody) =>
|
||||
api.post<RoleResponse>('/roles', body).then(r => r.data),
|
||||
|
||||
update: (id: string, body: Partial<RoleBody>) =>
|
||||
update: (id: string, body: RoleBody) =>
|
||||
api.put<RoleResponse>(`/roles/${id}`, body).then(r => r.data),
|
||||
|
||||
assignPermissions: (id: string, permissionIds: string[]) =>
|
||||
api.put(`/roles/${id}/permissions`, { permissionIds }).then(r => r.data),
|
||||
|
||||
deactivate: (id: string) =>
|
||||
api.delete(`/roles/${id}`),
|
||||
}
|
||||
|
||||
// ─── Permissions ──────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { NextRequest } from 'next/server'
|
||||
|
||||
const PUBLIC_PATHS = ['/login', '/register']
|
||||
|
||||
export function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl
|
||||
|
||||
if (PUBLIC_PATHS.some((p) => pathname.startsWith(p))) {
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
const token = request.cookies.get('access-token')
|
||||
if (!token) {
|
||||
return NextResponse.redirect(new URL('/login', request.url))
|
||||
}
|
||||
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
|
||||
}
|
||||
Reference in New Issue
Block a user