frontend fully integreated with the backend

This commit is contained in:
Kalana B. Thilakarathna
2026-08-25 23:47:33 +05:30
parent 1bee5f91c6
commit 83d3272784
151 changed files with 10724 additions and 573 deletions
@@ -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 />
}