conflict fixed
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'
|
||||
import { ColumnBarChart, DonutChart, HorizontalBarChart, RadialGauge, SalesTrendChart } from './dashboard-charts'
|
||||
import type { ChartDatum, MonthlySalesPoint } from './dashboard-charts'
|
||||
@@ -40,6 +41,7 @@ interface WidgetMeta {
|
||||
cat: Category
|
||||
title: string
|
||||
size: Size
|
||||
permission: string
|
||||
}
|
||||
|
||||
const CATEGORY_META: Record<Category, { label: string; text: string; bg: string; solid: string }> = {
|
||||
@@ -50,23 +52,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: 'salesTrendChart', cat: 'finance', title: 'Sales Trend (6 months)', size: 'chartWide' },
|
||||
{ id: 'paymentStatusChart', cat: 'finance', title: 'Payment Status', size: 'chart' },
|
||||
{ id: 'poStatusChart', cat: 'sales', title: 'Shop POs by Status', size: 'chart' },
|
||||
{ id: 'loadingSheetsChart', cat: 'ops', title: 'Loading Sheets Split', size: 'chart' },
|
||||
{ id: 'warehouseChart', cat: 'stock', title: 'Warehouse Stock Chart', size: 'chart' },
|
||||
{ id: 'movementTypeChart', cat: 'stock', title: 'Movements by Type', size: 'chart' },
|
||||
{ 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 = [
|
||||
@@ -223,103 +219,135 @@ interface DashboardData {
|
||||
monthlySales: MonthlySalesPoint[]
|
||||
}
|
||||
|
||||
const PO_STATUSES = ['Pending', 'PartiallyFulfilled', 'Fulfilled', 'Cancelled'] as const
|
||||
const PAYMENT_STATUSES = ['Pending', 'PartiallyPaid', 'Paid'] as const
|
||||
const SALES_MONTHS = 6
|
||||
/** Recent-activity charts aggregate this many latest records client-side. */
|
||||
const CHART_SAMPLE_SIZE = 200
|
||||
|
||||
const splitWords = (s: string) => s.replace(/([a-z])([A-Z])/g, '$1 $2')
|
||||
|
||||
function buildMonthlySales(rows: Array<{ createdAt: string; totalAmount: number }>): MonthlySalesPoint[] {
|
||||
const now = new Date()
|
||||
const months: MonthlySalesPoint[] = []
|
||||
for (let i = SALES_MONTHS - 1; i >= 0; i--) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - i, 1)
|
||||
months.push({ month: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`, invoiced: 0 })
|
||||
function emptyDashboardData(): DashboardData {
|
||||
return {
|
||||
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,
|
||||
}
|
||||
for (const r of rows) {
|
||||
const bucket = months.find(m => m.month === r.createdAt.slice(0, 7))
|
||||
if (bucket) bucket.invoiced += r.totalAmount
|
||||
}
|
||||
return months
|
||||
}
|
||||
|
||||
async function loadDashboardData(): Promise<DashboardData> {
|
||||
const [
|
||||
pendingPO, awaitingConfirm, allPO, fulfilledPO,
|
||||
openRidesRes,
|
||||
plannedSheets, confirmedSheets,
|
||||
pendingTasks, partialTasks,
|
||||
lowStock,
|
||||
movements,
|
||||
balances,
|
||||
outstanding,
|
||||
draftInv, printedInv, finalizedInv,
|
||||
poStatusCounts, paymentStatusCounts,
|
||||
recentInvoices, recentMovements,
|
||||
] = 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 }),
|
||||
Promise.all(PO_STATUSES.map(status => shopPos.list({ status, pageSize: 1 }))),
|
||||
Promise.all(PAYMENT_STATUSES.map(paymentStatus => invoices.list({ paymentStatus, pageSize: 1 }))),
|
||||
invoices.list({ pageSize: CHART_SAMPLE_SIZE }),
|
||||
stock.movements({ pageSize: CHART_SAMPLE_SIZE }),
|
||||
])
|
||||
async function loadDashboardData(activeIds: Set<string>): Promise<DashboardData> {
|
||||
const data = emptyDashboardData()
|
||||
const fetches: Promise<void>[] = []
|
||||
|
||||
const movementCounts = new Map<string, number>()
|
||||
for (const m of getPaginatedItems(recentMovements)) {
|
||||
movementCounts.set(m.type, (movementCounts.get(m.type) ?? 0) + 1)
|
||||
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(() => {})
|
||||
)
|
||||
}
|
||||
|
||||
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 })
|
||||
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(() => {})
|
||||
)
|
||||
}
|
||||
const warehouseBalances = Array.from(byWarehouse.values())
|
||||
.sort((a, b) => b.quantity - a.quantity)
|
||||
.slice(0, 5)
|
||||
|
||||
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,
|
||||
poStatusChart: PO_STATUSES.map((s, i) => ({ name: splitWords(s), value: poStatusCounts[i].total })),
|
||||
paymentStatusChart: PAYMENT_STATUSES.map((s, i) => ({ name: splitWords(s), value: paymentStatusCounts[i].total })),
|
||||
movementTypeChart: Array.from(movementCounts, ([type, value]) => ({ name: splitWords(type), value })).sort((a, b) => b.value - a.value),
|
||||
monthlySales: buildMonthlySales(getPaginatedItems(recentInvoices)),
|
||||
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 }) {
|
||||
@@ -484,6 +512,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)
|
||||
@@ -492,6 +521,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())
|
||||
}, [])
|
||||
@@ -508,13 +547,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()
|
||||
@@ -547,11 +586,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(() => {
|
||||
@@ -599,7 +638,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 />
|
||||
|
||||
Reference in New Issue
Block a user