Add brand viewing

This commit is contained in:
2026-09-08 11:45:54 +05:30
parent 7e9110b707
commit ef0486829c
3 changed files with 102 additions and 14 deletions
@@ -0,0 +1,48 @@
'use client'
import { Badge } from '@/components/ui/badge'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import type { BrandResponse } from '@/types/api'
const fmtDate = (v: string) =>
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
interface BrandViewSheetProps {
open: boolean
onClose: () => void
brand: BrandResponse | null
}
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>
)
}
export function BrandViewSheet({ open, onClose, brand }: BrandViewSheetProps) {
if (!brand) return null
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>Brand Details</DialogTitle>
</DialogHeader>
<div className="flex flex-col">
<Row label="Name" value={brand.name} />
<Row label="Status" value={<Badge variant={brand.isActive ? 'default' : 'secondary'}>{brand.isActive ? 'Active' : 'Inactive'}</Badge>} />
<Row label="Created At" value={fmtDate(brand.createdAt)} />
</div>
</DialogContent>
</Dialog>
)
}
@@ -9,27 +9,29 @@ import type { TableConfig } from '@/components/shared/data-table'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { toast } from '@/components/ui/toast' import { toast } from '@/components/ui/toast'
import { brands as brandsApi, getApiError, getPaginatedItems } from '@/lib/api/index' import { brands as brandsApi, getApiError } from '@/lib/api/index'
import type { BrandResponse } from '@/types/api' import type { BrandResponse } from '@/types/api'
import { BrandSheet } from './brand-sheet' import { BrandSheet } from './brand-sheet'
import { BrandViewSheet } from './brand-view-sheet'
export function BrandsClient() { export function BrandsClient() {
const [data, setData] = useState<BrandResponse[]>([]) const [data, setData] = useState<BrandResponse[]>([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [total, setTotal] = useState(0) const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20) const [pageSize, setPageSize] = useState(20)
const [sheetOpen, setSheetOpen] = useState(false) const [sheetOpen, setSheetOpen] = useState(false)
const [editing, setEditing] = useState<BrandResponse | null>(null) const [editing, setEditing] = useState<BrandResponse | null>(null)
const [viewOpen, setViewOpen] = useState(false)
const [viewing, setViewing] = useState<BrandResponse | null>(null)
const fetchData = useCallback(async (p: number, ps: number) => { const fetchData = useCallback(async () => {
setLoading(true) setLoading(true)
try { try {
const res = await brandsApi.list({ page: p, pageSize: ps }) const items = await brandsApi.list()
setData(getPaginatedItems(res)) setData(items)
setTotal(res.total) setTotal(items.length)
} catch (err) { } catch (err) {
toast.add({ title: 'Failed to load brands', description: getApiError(err), type: 'error' }) toast.add({ title: 'Failed to load brands', description: getApiError(err), type: 'error' })
} finally { } finally {
@@ -38,8 +40,8 @@ export function BrandsClient() {
}, []) }, [])
useEffect(() => { useEffect(() => {
fetchData(page, pageSize) fetchData()
}, [fetchData, page, pageSize]) }, [fetchData])
function openCreate() { function openCreate() {
setEditing(null) setEditing(null)
@@ -51,9 +53,23 @@ export function BrandsClient() {
setSheetOpen(true) setSheetOpen(true)
} }
function openView(brand: BrandResponse) {
setViewing(brand)
setViewOpen(true)
}
async function handleDelete(brand: BrandResponse) {
try {
await brandsApi.remove(brand.id)
toast.add({ title: 'Brand deactivated', type: 'success' })
fetchData()
} catch (err) {
toast.add({ title: 'Failed to deactivate brand', description: getApiError(err), type: 'error' })
}
}
const tableConfig = useMemo<TableConfig<BrandResponse>>(() => ({ const tableConfig = useMemo<TableConfig<BrandResponse>>(() => ({
rowKey: 'id', rowKey: 'id',
serverSide: true,
stickyHeader: true, stickyHeader: true,
emptyMessage: 'No brands yet. Add one to get started.', emptyMessage: 'No brands yet. Add one to get started.',
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] }, pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
@@ -90,14 +106,25 @@ export function BrandsClient() {
], ],
rowActions: { rowActions: {
actions: () => [ actions: () => [
{
action: 'view',
label: 'View brand',
onClick: openView,
},
{ {
action: 'edit', action: 'edit',
label: 'Edit brand', label: 'Edit brand',
onClick: openEdit, onClick: openEdit,
}, },
{
action: 'cancel',
label: 'Delete brand',
onClick: handleDelete,
visible: (target) => target.isActive,
},
], ],
}, },
}), [pageSize, openEdit]) }), [pageSize])
return ( return (
<> <>
@@ -120,7 +147,6 @@ export function BrandsClient() {
loading={loading} loading={loading}
totalCount={total} totalCount={total}
onServerSideChange={({ page: p }) => { onServerSideChange={({ page: p }) => {
setPage(p.page)
setPageSize(p.pageSize) setPageSize(p.pageSize)
}} }}
/> />
@@ -129,7 +155,13 @@ export function BrandsClient() {
open={sheetOpen} open={sheetOpen}
onClose={() => setSheetOpen(false)} onClose={() => setSheetOpen(false)}
brand={editing} brand={editing}
onSuccess={() => fetchData(page, pageSize)} onSuccess={() => fetchData()}
/>
<BrandViewSheet
open={viewOpen}
onClose={() => setViewOpen(false)}
brand={viewing}
/> />
</> </>
) )
+10 -2
View File
@@ -74,6 +74,9 @@ export const categories = {
update: (id: string, body: Partial<CategoryBody>) => update: (id: string, body: Partial<CategoryBody>) =>
api.put<CategoryResponse>(`/categories/${id}`, body).then(r => r.data), api.put<CategoryResponse>(`/categories/${id}`, body).then(r => r.data),
remove: (id: string) =>
api.delete(`/categories/${id}`),
createSubCategory: (categoryId: string, body: SubCategoryBody) => createSubCategory: (categoryId: string, body: SubCategoryBody) =>
api.post(`/categories/${categoryId}/subcategories`, body).then(r => r.data), api.post(`/categories/${categoryId}/subcategories`, body).then(r => r.data),
@@ -91,9 +94,11 @@ export interface BrandBody {
isActive?: boolean isActive?: boolean
} }
// GET /brands takes no query params and returns a plain array — no server-side
// filtering/pagination exists on the backend.
export const brands = { export const brands = {
list: (params?: PageParams) => list: () =>
api.get<PaginatedResponse<BrandResponse>>('/brands', { params }).then(r => r.data), api.get<BrandResponse[]>('/brands').then(r => r.data),
get: (id: string) => get: (id: string) =>
api.get<BrandResponse>(`/brands/${id}`).then(r => r.data), api.get<BrandResponse>(`/brands/${id}`).then(r => r.data),
@@ -103,6 +108,9 @@ export const brands = {
update: (id: string, body: Partial<BrandBody>) => update: (id: string, body: Partial<BrandBody>) =>
api.put<BrandResponse>(`/brands/${id}`, body).then(r => r.data), api.put<BrandResponse>(`/brands/${id}`, body).then(r => r.data),
remove: (id: string) =>
api.delete(`/brands/${id}`),
} }
// ─── UOMs ───────────────────────────────────────────────────────────────────── // ─── UOMs ─────────────────────────────────────────────────────────────────────