frontend fully integreated with the backend
This commit is contained in:
@@ -0,0 +1,356 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useFieldArray } from 'react-hook-form'
|
||||
import { useForm, zodResolver, z } from '@/lib/form'
|
||||
import { FormField } from '@/components/shared/form-field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { FieldGroup } from '@/components/ui/field'
|
||||
import { toast } from '@/components/ui/toast'
|
||||
import {
|
||||
sales as salesApi,
|
||||
stores as storesApi,
|
||||
rides as ridesApi,
|
||||
items as itemsApi,
|
||||
getApiError,
|
||||
} from '@/lib/api/index'
|
||||
import type { ItemSummaryResponse, RideResponse, StoreResponse } from '@/types/api'
|
||||
|
||||
const saleItemSchema = z.object({
|
||||
itemId: z.string().min(1, 'Item is required'),
|
||||
quantity: z.number().min(1, 'Quantity must be at least 1'),
|
||||
unitPrice: z.number().min(0.01, 'Unit price must be greater than 0'),
|
||||
})
|
||||
|
||||
const schema = z.object({
|
||||
storeId: z.string().min(1, 'Store is required'),
|
||||
rideId: z.string(),
|
||||
fulfillImmediately: z.boolean(),
|
||||
items: z.array(saleItemSchema).min(1, 'At least one item is required'),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
interface SaleSheetProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
function ensureItems<T>(value: { items?: T[] } | null | undefined): T[] {
|
||||
return Array.isArray(value?.items) ? value.items : []
|
||||
}
|
||||
|
||||
function createDefaultItem() {
|
||||
return {
|
||||
itemId: '',
|
||||
quantity: 1,
|
||||
unitPrice: 0,
|
||||
}
|
||||
}
|
||||
|
||||
export function SaleSheet({ open, onClose, onSuccess }: SaleSheetProps) {
|
||||
const [storesList, setStoresList] = useState<StoreResponse[]>([])
|
||||
const [ridesList, setRidesList] = useState<RideResponse[]>([])
|
||||
const [itemsList, setItemsList] = useState<ItemSummaryResponse[]>([])
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
storeId: '',
|
||||
rideId: '',
|
||||
fulfillImmediately: false,
|
||||
items: [createDefaultItem()],
|
||||
},
|
||||
})
|
||||
|
||||
const { fields, append, remove } = useFieldArray({
|
||||
control: form.control,
|
||||
name: 'items',
|
||||
})
|
||||
|
||||
const watchedItems = form.watch('items')
|
||||
const itemsById = useMemo(
|
||||
() => new Map(itemsList.map((item) => [item.id, item])),
|
||||
[itemsList]
|
||||
)
|
||||
const totalAmount = useMemo(
|
||||
() => watchedItems.reduce((sum, item) => sum + (Number(item.quantity) || 0) * (Number(item.unitPrice) || 0), 0),
|
||||
[watchedItems]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
|
||||
form.reset({
|
||||
storeId: '',
|
||||
rideId: '',
|
||||
fulfillImmediately: false,
|
||||
items: [createDefaultItem()],
|
||||
})
|
||||
|
||||
Promise.all([
|
||||
storesApi.list({ pageSize: 200 }),
|
||||
ridesApi.list({ pageSize: 200, rideType: 'Sale' }),
|
||||
itemsApi.list({ pageSize: 200 }),
|
||||
])
|
||||
.then(([stores, rides, items]) => {
|
||||
setStoresList(ensureItems(stores))
|
||||
setRidesList(ensureItems(rides))
|
||||
setItemsList(ensureItems(items))
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.add({ title: 'Failed to load reference data', description: getApiError(err), type: 'error' })
|
||||
})
|
||||
}, [open])
|
||||
|
||||
async function onSubmit(values: FormValues) {
|
||||
try {
|
||||
await salesApi.create({
|
||||
storeId: values.storeId,
|
||||
rideId: values.rideId || null,
|
||||
fulfillImmediately: values.fulfillImmediately,
|
||||
items: values.items,
|
||||
})
|
||||
toast.add({ title: 'Sale created', type: 'success' })
|
||||
onSuccess()
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to create sale', description: getApiError(err), type: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
|
||||
<DialogContent className="flex max-h-[85vh] flex-col overflow-hidden sm:max-w-6xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create Sale</DialogTitle>
|
||||
<DialogDescription>Record a sale for a store with one or more items.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col gap-6">
|
||||
<div className="grid min-h-0 gap-6 lg:grid-cols-3">
|
||||
<FieldGroup className="lg:col-span-2">
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="storeId"
|
||||
label="Store"
|
||||
required
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select store..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="" disabled>Select store...</SelectItem>
|
||||
{storesList.map((store) => (
|
||||
<SelectItem key={store.id} value={store.id}>
|
||||
{store.storeName} - {store.ownerName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="rideId"
|
||||
label="Ride"
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
value={(field.value as string) || '__none__'}
|
||||
onValueChange={(value) => field.onChange(value === '__none__' ? '' : value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select ride..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__none__">No ride</SelectItem>
|
||||
{ridesList.map((ride) => (
|
||||
<SelectItem key={ride.id} value={ride.id}>
|
||||
{ride.routeName} - {ride.vehicleNumberPlate}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="fulfillImmediately"
|
||||
render={({ field }) => (
|
||||
<label className="flex items-center gap-3 text-sm font-medium">
|
||||
<Checkbox
|
||||
checked={Boolean(field.value)}
|
||||
onCheckedChange={(checked) => field.onChange(Boolean(checked))}
|
||||
/>
|
||||
Fulfill immediately
|
||||
</label>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="rounded-2xl border p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-foreground">Sale Summary</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Quantity and unit price are handled in the selected item's base UOM.
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-xs uppercase tracking-wide text-muted-foreground">Total</p>
|
||||
<p className="text-lg font-semibold text-foreground">Rs. {totalAmount.toLocaleString()}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</FieldGroup>
|
||||
|
||||
<div className="flex min-h-0 flex-col rounded-2xl border p-4 lg:col-span-1">
|
||||
<div className="mb-4 flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-foreground">Items</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Only this panel scrolls when multiple items are added.
|
||||
</p>
|
||||
</div>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => append(createDefaultItem())}>
|
||||
Add Item
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
|
||||
{fields.map((fieldItem, index) => {
|
||||
const selectedItem = itemsById.get(watchedItems[index]?.itemId ?? '')
|
||||
|
||||
return (
|
||||
<div key={fieldItem.id} className="space-y-4 rounded-2xl border p-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.itemId`}
|
||||
label="Item"
|
||||
required
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
value={field.value as string}
|
||||
onValueChange={(value) => {
|
||||
field.onChange(value)
|
||||
const nextItem = value ? itemsById.get(value) : undefined
|
||||
if (nextItem) {
|
||||
form.setValue(`items.${index}.unitPrice`, nextItem.salePrice, { shouldValidate: true })
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select item..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="" disabled>Select item...</SelectItem>
|
||||
{itemsList.map((item) => (
|
||||
<SelectItem key={item.id} value={item.id}>
|
||||
{item.name} - {item.sku}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.quantity`}
|
||||
label="Quantity"
|
||||
required
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
id={`items.${index}.quantity`}
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
type="number"
|
||||
min={1}
|
||||
value={Number(field.value as number)}
|
||||
onChange={(e) => field.onChange(Number(e.target.value))}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="1"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.unitPrice`}
|
||||
label="Unit Price"
|
||||
required
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
id={`items.${index}.unitPrice`}
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
type="number"
|
||||
min={0.01}
|
||||
step="0.01"
|
||||
value={Number(field.value as number)}
|
||||
onChange={(e) => field.onChange(Number(e.target.value))}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="0.00"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{selectedItem
|
||||
? `Quantity is in ${selectedItem.baseUomName}. Unit price is for one ${selectedItem.baseUomName.toLowerCase()}.`
|
||||
: 'Quantity uses the selected item base UOM. Unit price is for one base-UOM unit.'}
|
||||
</p>
|
||||
|
||||
{fields.length > 1 && (
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => remove(index)}>
|
||||
Remove Item
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Creating...' : 'Create Sale'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||
import { HugeiconsIcon } from '@hugeicons/react'
|
||||
import { Add01Icon } from '@hugeicons/core-free-icons'
|
||||
|
||||
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 { toast } from '@/components/ui/toast'
|
||||
import { sales as salesApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||
import type { SaleResponse, SaleStatus, PaymentStatus } from '@/types/api'
|
||||
|
||||
import { SaleSheet } from './sale-sheet'
|
||||
|
||||
const fmtDate = (v: string) =>
|
||||
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
|
||||
|
||||
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
|
||||
const truncId = (id: string) => id.substring(0, 8)
|
||||
|
||||
const SALE_STATUS_VARIANT: Record<SaleStatus, 'default' | 'secondary' | 'destructive'> = {
|
||||
Pending: 'secondary',
|
||||
Completed: 'default',
|
||||
Cancelled: 'destructive',
|
||||
}
|
||||
|
||||
const PAYMENT_STATUS_VARIANT: Record<PaymentStatus, 'default' | 'secondary' | 'destructive'> = {
|
||||
Pending: 'secondary',
|
||||
PartiallyPaid: 'secondary',
|
||||
Paid: 'default',
|
||||
}
|
||||
|
||||
export function SalesClient() {
|
||||
const [data, setData] = useState<SaleResponse[]>([])
|
||||
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 fetchData = useCallback(async (p: number, ps: number) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await salesApi.list({ page: p, pageSize: ps })
|
||||
setData(getPaginatedItems(res))
|
||||
setTotal(res.total)
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to load sales', description: getApiError(err), type: 'error' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData(page, pageSize)
|
||||
}, [fetchData, page, pageSize])
|
||||
|
||||
const tableConfig = useMemo<TableConfig<SaleResponse>>(() => ({
|
||||
rowKey: 'id',
|
||||
serverSide: true,
|
||||
stickyHeader: true,
|
||||
emptyMessage: 'No sales found.',
|
||||
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
|
||||
columns: [
|
||||
{
|
||||
key: 'id',
|
||||
title: 'Sale ID',
|
||||
fields: ['id'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="font-mono text-sm">{truncId(row.id)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'storeId',
|
||||
title: 'Store ID',
|
||||
fields: ['storeId'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="font-mono text-sm">{truncId(row.storeId)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'totalAmount',
|
||||
title: 'Total',
|
||||
fields: ['totalAmount'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="text-sm font-medium">{fmtAmount(row.totalAmount)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
title: 'Status',
|
||||
fields: ['status'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<Badge variant={SALE_STATUS_VARIANT[row.status]}>{row.status}</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'paymentStatus',
|
||||
title: 'Payment',
|
||||
fields: ['paymentStatus'],
|
||||
width: 160,
|
||||
cellRender: (row) => (
|
||||
<Badge variant={PAYMENT_STATUS_VARIANT[row.paymentStatus]}>{row.paymentStatus}</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'saleDate',
|
||||
title: 'Sale Date',
|
||||
fields: [{ key: 'saleDate', transform: (v) => fmtDate(v as string) }],
|
||||
width: 140,
|
||||
},
|
||||
{
|
||||
key: 'createdAt',
|
||||
title: 'Created',
|
||||
fields: [{ key: 'createdAt', transform: (v) => fmtDate(v as string) }],
|
||||
width: 140,
|
||||
},
|
||||
],
|
||||
}), [pageSize])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-foreground">Sales</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
Sales transactions recorded against stores
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setSheetOpen(true)}>
|
||||
<HugeiconsIcon icon={Add01Icon} size={16} />
|
||||
Add Sale
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
config={tableConfig}
|
||||
data={data}
|
||||
loading={loading}
|
||||
totalCount={total}
|
||||
onServerSideChange={({ page: p }) => {
|
||||
setPage(p.page)
|
||||
setPageSize(p.pageSize)
|
||||
}}
|
||||
/>
|
||||
|
||||
<SaleSheet
|
||||
open={sheetOpen}
|
||||
onClose={() => setSheetOpen(false)}
|
||||
onSuccess={() => fetchData(page, pageSize)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
'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 { Badge } from '@/components/ui/badge'
|
||||
import { toast } from '@/components/ui/toast'
|
||||
import { orders as ordersApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||
import type { OrderResponse, OrderStatus } from '@/types/api'
|
||||
|
||||
const fmtDate = (v: string) =>
|
||||
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
|
||||
|
||||
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
|
||||
const truncId = (id: string) => id.substring(0, 8)
|
||||
|
||||
const ORDER_STATUS_VARIANT: Record<OrderStatus, 'default' | 'secondary' | 'destructive'> = {
|
||||
Pending: 'secondary',
|
||||
PartiallyFulfilled: 'secondary',
|
||||
Fulfilled: 'default',
|
||||
Cancelled: 'destructive',
|
||||
}
|
||||
|
||||
export function OrdersClient() {
|
||||
const [data, setData] = useState<OrderResponse[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(20)
|
||||
|
||||
const fetchData = useCallback(async (p: number, ps: number) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await ordersApi.list({ page: p, pageSize: ps })
|
||||
setData(getPaginatedItems(res))
|
||||
setTotal(res.total)
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to load orders', description: getApiError(err), type: 'error' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData(page, pageSize)
|
||||
}, [fetchData, page, pageSize])
|
||||
|
||||
const tableConfig = useMemo<TableConfig<OrderResponse>>(() => ({
|
||||
rowKey: 'id',
|
||||
serverSide: true,
|
||||
stickyHeader: true,
|
||||
emptyMessage: 'No orders found.',
|
||||
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
|
||||
columns: [
|
||||
{
|
||||
key: 'id',
|
||||
title: 'Order ID',
|
||||
fields: ['id'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="font-mono text-sm">{truncId(row.id)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'saleId',
|
||||
title: 'Sale ID',
|
||||
fields: ['saleId'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="font-mono text-sm">{truncId(row.saleId)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'storeId',
|
||||
title: 'Store ID',
|
||||
fields: ['storeId'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="font-mono text-sm">{truncId(row.storeId)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'totalAmount',
|
||||
title: 'Total',
|
||||
fields: ['totalAmount'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="text-sm font-medium">{fmtAmount(row.totalAmount)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
title: 'Status',
|
||||
fields: ['status'],
|
||||
width: 180,
|
||||
cellRender: (row) => (
|
||||
<Badge variant={ORDER_STATUS_VARIANT[row.status]}>{row.status}</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'orderDate',
|
||||
title: 'Order Date',
|
||||
fields: [{ key: 'orderDate', transform: (v) => fmtDate(v as string) }],
|
||||
width: 140,
|
||||
},
|
||||
{
|
||||
key: 'createdAt',
|
||||
title: 'Created',
|
||||
fields: [{ key: 'createdAt', transform: (v) => fmtDate(v as string) }],
|
||||
width: 140,
|
||||
},
|
||||
],
|
||||
}), [pageSize])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-foreground">Orders</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
Fulfillment status of store orders
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
config={tableConfig}
|
||||
data={data}
|
||||
loading={loading}
|
||||
totalCount={total}
|
||||
onServerSideChange={({ page: p }) => {
|
||||
setPage(p.page)
|
||||
setPageSize(p.pageSize)
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { OrdersClient } from './_components/orders-client'
|
||||
|
||||
export default function OrdersPage() {
|
||||
return <OrdersClient />
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { SalesClient } from './_components/sales-client'
|
||||
|
||||
export default function SalesPage() {
|
||||
return <SalesClient />
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
'use client'
|
||||
|
||||
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 {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import { FieldGroup } from '@/components/ui/field'
|
||||
import { toast } from '@/components/ui/toast'
|
||||
import { payments as paymentsApi, getApiError } from '@/lib/api/index'
|
||||
|
||||
const schema = z.object({
|
||||
saleId: z.string().min(1, 'Sale ID is required'),
|
||||
storeId: z.string().min(1, 'Store ID is required'),
|
||||
amount: z.number().min(0.01, 'Amount must be greater than 0'),
|
||||
method: z.enum(['Cash', 'Credit']),
|
||||
collectedAt: z.string().min(1, 'Date is required'),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
interface PaymentSheetProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export function PaymentSheet({ open, onClose, onSuccess }: PaymentSheetProps) {
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
saleId: '',
|
||||
storeId: '',
|
||||
amount: 0,
|
||||
method: 'Cash',
|
||||
collectedAt: '',
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset({
|
||||
saleId: '',
|
||||
storeId: '',
|
||||
amount: 0,
|
||||
method: 'Cash',
|
||||
collectedAt: '',
|
||||
})
|
||||
}
|
||||
}, [open])
|
||||
|
||||
async function onSubmit(values: FormValues) {
|
||||
try {
|
||||
await paymentsApi.create(values)
|
||||
toast.add({ title: 'Payment recorded', type: 'success' })
|
||||
onSuccess()
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to record payment', description: getApiError(err), type: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
|
||||
<DialogContent className="overflow-y-auto sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Record Payment</DialogTitle>
|
||||
<DialogDescription>Record a cash or credit payment from a store.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
|
||||
<FieldGroup>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="saleId"
|
||||
label="Sale ID"
|
||||
required
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
id="saleId"
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
value={field.value as string}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="Sale ID"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="storeId"
|
||||
label="Store ID"
|
||||
required
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
id="storeId"
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
value={field.value as string}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="Store ID"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="amount"
|
||||
label="Amount"
|
||||
required
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
id="amount"
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={Number(field.value as string)}
|
||||
onChange={(e) => field.onChange(Number(e.target.value))}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="0.00"
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="method"
|
||||
label="Payment Method"
|
||||
required
|
||||
render={({ field }) => (
|
||||
<Select
|
||||
value={field.value as string}
|
||||
onValueChange={field.onChange}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select method" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Cash">Cash</SelectItem>
|
||||
<SelectItem value="Credit">Credit</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="collectedAt"
|
||||
label="Collected At"
|
||||
required
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
id="collectedAt"
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
type="date"
|
||||
value={field.value as string}
|
||||
onChange={field.onChange}
|
||||
onBlur={field.onBlur}
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldGroup>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Saving…' : 'Record Payment'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||
import { HugeiconsIcon } from '@hugeicons/react'
|
||||
import { Add01Icon } from '@hugeicons/core-free-icons'
|
||||
|
||||
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 { toast } from '@/components/ui/toast'
|
||||
import { payments as paymentsApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||
import type { PaymentResponse, PaymentMethod } from '@/types/api'
|
||||
|
||||
import { PaymentSheet } from './payment-sheet'
|
||||
|
||||
const fmtDate = (v: string) =>
|
||||
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
|
||||
|
||||
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
|
||||
const truncId = (id: string) => id.substring(0, 8)
|
||||
|
||||
const PAYMENT_METHOD_VARIANT: Record<PaymentMethod, 'default' | 'secondary'> = {
|
||||
Cash: 'default',
|
||||
Credit: 'secondary',
|
||||
}
|
||||
|
||||
export function PaymentsClient() {
|
||||
const [data, setData] = useState<PaymentResponse[]>([])
|
||||
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 fetchData = useCallback(async (p: number, ps: number) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await paymentsApi.list({ page: p, pageSize: ps })
|
||||
setData(getPaginatedItems(res))
|
||||
setTotal(res.total)
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to load payments', description: getApiError(err), type: 'error' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData(page, pageSize)
|
||||
}, [fetchData, page, pageSize])
|
||||
|
||||
const tableConfig = useMemo<TableConfig<PaymentResponse>>(() => ({
|
||||
rowKey: 'id',
|
||||
serverSide: true,
|
||||
stickyHeader: true,
|
||||
emptyMessage: 'No payments found.',
|
||||
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
|
||||
columns: [
|
||||
{
|
||||
key: 'id',
|
||||
title: 'Payment ID',
|
||||
fields: ['id'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="font-mono text-sm">{truncId(row.id)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'storeId',
|
||||
title: 'Store ID',
|
||||
fields: ['storeId'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="font-mono text-sm">{truncId(row.storeId)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'amount',
|
||||
title: 'Amount',
|
||||
fields: ['amount'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="text-sm font-medium">{fmtAmount(row.amount)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'method',
|
||||
title: 'Method',
|
||||
fields: ['method'],
|
||||
width: 120,
|
||||
cellRender: (row) => (
|
||||
<Badge variant={PAYMENT_METHOD_VARIANT[row.method]}>{row.method}</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'collectedAt',
|
||||
title: 'Collected At',
|
||||
fields: [{ key: 'collectedAt', transform: (v) => fmtDate(v as string) }],
|
||||
width: 140,
|
||||
},
|
||||
{
|
||||
key: 'collectedBy',
|
||||
title: 'Collected By',
|
||||
fields: ['collectedBy'],
|
||||
minWidth: 160,
|
||||
cellRender: (row) => (
|
||||
<span className="text-sm text-muted-foreground">{row.collectedBy}</span>
|
||||
),
|
||||
},
|
||||
],
|
||||
}), [pageSize])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-foreground">Payments</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
Cash and credit payments collected from stores
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setSheetOpen(true)}>
|
||||
<HugeiconsIcon icon={Add01Icon} size={16} />
|
||||
Record Payment
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
config={tableConfig}
|
||||
data={data}
|
||||
loading={loading}
|
||||
totalCount={total}
|
||||
onServerSideChange={({ page: p }) => {
|
||||
setPage(p.page)
|
||||
setPageSize(p.pageSize)
|
||||
}}
|
||||
/>
|
||||
|
||||
<PaymentSheet
|
||||
open={sheetOpen}
|
||||
onClose={() => setSheetOpen(false)}
|
||||
onSuccess={() => fetchData(page, pageSize)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PaymentsClient } from './_components/payments-client'
|
||||
|
||||
export default function PaymentsPage() {
|
||||
return <PaymentsClient />
|
||||
}
|
||||
Reference in New Issue
Block a user