Add product reports
This commit is contained in:
+213
@@ -0,0 +1,213 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||
|
||||
import { DataTable } from '@/components/shared/data-table'
|
||||
import type { TableConfig } from '@/components/shared/data-table'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { toast } from '@/components/ui/toast'
|
||||
import { getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||
import {
|
||||
productReports,
|
||||
type ProductReportSummary,
|
||||
type ProductReturnRow,
|
||||
type ProductSalesRow,
|
||||
type ProductStockRow,
|
||||
} from '@/lib/api/reports'
|
||||
|
||||
type Tab = 'stock' | 'sales' | 'returns'
|
||||
|
||||
const TABS: { key: Tab; label: string }[] = [
|
||||
{ key: 'stock', label: 'Stock' },
|
||||
{ key: 'sales', label: 'Sales' },
|
||||
{ key: 'returns', label: 'Returns' },
|
||||
]
|
||||
|
||||
const num = (v: number | null | undefined) =>
|
||||
v == null ? '—' : v.toLocaleString('en-IN', { maximumFractionDigits: 2 })
|
||||
|
||||
const pct = (v: number | null | undefined) => (v == null ? '—' : `${v.toFixed(2)}%`)
|
||||
|
||||
const stockColumns: TableConfig<ProductStockRow>['columns'] = [
|
||||
{ key: 'name', title: 'Item', fields: [{ key: 'name', primary: true }, { key: 'sku' }], minWidth: 220 },
|
||||
{ key: 'brand', title: 'Brand', fields: [{ key: 'brand', transform: v => (v as string | null) ?? '—' }], width: 140 },
|
||||
{ key: 'category', title: 'Category', fields: ['category'], width: 150 },
|
||||
{ key: 'uom', title: 'UOM', fields: ['uom'], width: 80 },
|
||||
{ key: 'warehouseQty', title: 'Warehouse', fields: [{ key: 'warehouseQty', transform: v => num(v as number) }], width: 110 },
|
||||
{ key: 'vehicleQty', title: 'Vehicles', fields: [{ key: 'vehicleQty', transform: v => num(v as number) }], width: 100 },
|
||||
{ key: 'totalQty', title: 'Total', fields: [{ key: 'totalQty', transform: v => num(v as number) }], width: 100 },
|
||||
{ key: 'stockValue', title: 'Stock Value', fields: [{ key: 'stockValue', transform: v => num(v as number) }], width: 120 },
|
||||
]
|
||||
|
||||
const salesColumns: TableConfig<ProductSalesRow>['columns'] = [
|
||||
{ key: 'name', title: 'Item', fields: [{ key: 'name', primary: true }, { key: 'sku' }], minWidth: 220 },
|
||||
{ key: 'orders', title: 'Orders', fields: ['orders'], width: 90 },
|
||||
{ key: 'stores', title: 'Stores', fields: ['stores'], width: 90 },
|
||||
{ key: 'qtyOrdered', title: 'Qty Ordered', fields: [{ key: 'qtyOrdered', transform: v => num(v as number) }], width: 120 },
|
||||
{ key: 'qtyFulfilled', title: 'Qty Fulfilled', fields: [{ key: 'qtyFulfilled', transform: v => num(v as number) }], width: 120 },
|
||||
{ key: 'salesValue', title: 'Sales', fields: [{ key: 'salesValue', transform: v => num(v as number) }], width: 120 },
|
||||
{ key: 'margin', title: 'Margin', fields: [{ key: 'margin', transform: v => num(v as number | null) }], width: 110 },
|
||||
{ key: 'marginPercent', title: 'Margin %', fields: [{ key: 'marginPercent', transform: v => pct(v as number | null) }], width: 100 },
|
||||
]
|
||||
|
||||
const returnsColumns: TableConfig<ProductReturnRow>['columns'] = [
|
||||
{ key: 'name', title: 'Item', fields: [{ key: 'name', primary: true }, { key: 'sku' }], minWidth: 220 },
|
||||
{ key: 'returnedQty', title: 'Returned Qty', fields: [{ key: 'returnedQty', transform: v => num(v as number) }], width: 120 },
|
||||
{ key: 'returnedValue', title: 'Returned Value', fields: [{ key: 'returnedValue', transform: v => num(v as number) }], width: 130 },
|
||||
{ key: 'soldQty', title: 'Sold Qty', fields: [{ key: 'soldQty', transform: v => num(v as number) }], width: 100 },
|
||||
{ key: 'returnPercent', title: 'Return %', fields: [{ key: 'returnPercent', transform: v => pct(v as number | null) }], width: 100 },
|
||||
{
|
||||
key: 'qtyByReason',
|
||||
title: 'By Reason',
|
||||
fields: ['qtyByReason'],
|
||||
minWidth: 220,
|
||||
cellRender: row => (
|
||||
<span className="text-sm">
|
||||
{Object.entries(row.qtyByReason).map(([reason, qty]) => `${reason}: ${num(qty)}`).join(', ')}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
export function ProductReportClient() {
|
||||
const [tab, setTab] = useState<Tab>('stock')
|
||||
const [search, setSearch] = useState('')
|
||||
const [from, setFrom] = useState('')
|
||||
const [to, setTo] = useState('')
|
||||
const [lowStockOnly, setLowStockOnly] = useState(false)
|
||||
|
||||
const [stockData, setStockData] = useState<ProductStockRow[]>([])
|
||||
const [salesData, setSalesData] = useState<ProductSalesRow[]>([])
|
||||
const [returnsData, setReturnsData] = useState<ProductReturnRow[]>([])
|
||||
const [summary, setSummary] = useState<ProductReportSummary | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(20)
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
const base = { page, pageSize, search: search || undefined, from: from || undefined, to: to || undefined }
|
||||
try {
|
||||
if (tab === 'stock') {
|
||||
const res = await productReports.stock({ ...base, lowStockOnly })
|
||||
setStockData(getPaginatedItems(res))
|
||||
setTotal(res.total)
|
||||
} else if (tab === 'sales') {
|
||||
const res = await productReports.sales(base)
|
||||
setSalesData(getPaginatedItems(res))
|
||||
setTotal(res.total)
|
||||
} else {
|
||||
const res = await productReports.returns(base)
|
||||
setReturnsData(getPaginatedItems(res))
|
||||
setTotal(res.total)
|
||||
}
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to load product report', description: getApiError(err), type: 'error' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [tab, page, pageSize, search, from, to, lowStockOnly])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
useEffect(() => {
|
||||
productReports
|
||||
.summary({ from: from || undefined, to: to || undefined })
|
||||
.then(setSummary)
|
||||
.catch(err => toast.add({ title: 'Failed to load summary', description: getApiError(err), type: 'error' }))
|
||||
}, [from, to])
|
||||
|
||||
function changeTab(next: Tab) {
|
||||
setTab(next)
|
||||
setPage(1)
|
||||
setTotal(0)
|
||||
}
|
||||
|
||||
const common = { serverSide: true, stickyHeader: true, pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] } }
|
||||
|
||||
const stockConfig = useMemo<TableConfig<ProductStockRow>>(
|
||||
() => ({ ...common, rowKey: r => r.itemId, emptyMessage: 'No products found.', columns: stockColumns }),
|
||||
[pageSize],
|
||||
)
|
||||
const salesConfig = useMemo<TableConfig<ProductSalesRow>>(
|
||||
() => ({ ...common, rowKey: r => r.itemId, emptyMessage: 'No finalized sales in this period.', columns: salesColumns }),
|
||||
[pageSize],
|
||||
)
|
||||
const returnsConfig = useMemo<TableConfig<ProductReturnRow>>(
|
||||
() => ({ ...common, rowKey: r => r.itemId, emptyMessage: 'No returns in this period.', columns: returnsColumns }),
|
||||
[pageSize],
|
||||
)
|
||||
|
||||
const onServerSideChange = ({ page: p }: { page: { page: number; pageSize: number } }) => {
|
||||
setPage(p.page)
|
||||
setPageSize(p.pageSize)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-foreground">Product Report</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
Stock, sales and returns per product. Sales count fulfilled quantity on finalized invoices.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{summary && (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
{[
|
||||
['Products', num(summary.itemCount)],
|
||||
['Total stock qty', num(summary.totalQty)],
|
||||
['Stock value', num(summary.totalValue)],
|
||||
['Sales (period)', num(summary.totalSales)],
|
||||
].map(([label, value]) => (
|
||||
<Card key={label} className="rounded-3xl border-border/60">
|
||||
<CardContent className="space-y-1">
|
||||
<CardDescription>{label}</CardDescription>
|
||||
<CardTitle className="text-2xl">{value}</CardTitle>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{TABS.map(t => (
|
||||
<Button key={t.key} size="sm" variant={tab === t.key ? 'default' : 'outline'} onClick={() => changeTab(t.key)}>
|
||||
{t.label}
|
||||
</Button>
|
||||
))}
|
||||
<Input
|
||||
className="w-56"
|
||||
placeholder="Search name or SKU"
|
||||
value={search}
|
||||
onChange={e => { setSearch(e.target.value); setPage(1) }}
|
||||
/>
|
||||
{tab !== 'stock' ? (
|
||||
<>
|
||||
<Input className="w-40" type="date" value={from} onChange={e => { setFrom(e.target.value); setPage(1) }} />
|
||||
<Input className="w-40" type="date" value={to} onChange={e => { setTo(e.target.value); setPage(1) }} />
|
||||
</>
|
||||
) : (
|
||||
<Button size="sm" variant={lowStockOnly ? 'default' : 'outline'} onClick={() => { setLowStockOnly(v => !v); setPage(1) }}>
|
||||
Low stock only
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{tab === 'stock' && (
|
||||
<DataTable config={stockConfig} data={stockData} loading={loading} totalCount={total} onServerSideChange={onServerSideChange} />
|
||||
)}
|
||||
{tab === 'sales' && (
|
||||
<DataTable config={salesConfig} data={salesData} loading={loading} totalCount={total} onServerSideChange={onServerSideChange} />
|
||||
)}
|
||||
{tab === 'returns' && (
|
||||
<DataTable config={returnsConfig} data={returnsData} loading={loading} totalCount={total} onServerSideChange={onServerSideChange} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { ProductReportClient } from './_components/product-report-client'
|
||||
|
||||
export default function ProductReportPage() {
|
||||
return <ProductReportClient />
|
||||
}
|
||||
Reference in New Issue
Block a user