Dev #23
@@ -1,6 +1,6 @@
|
||||
'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'
|
||||
@@ -22,14 +22,14 @@ import {
|
||||
} 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'
|
||||
import { payments as paymentsApi, sales as salesApi, users as usersApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||
import type { SaleResponse, UserResponse } from '@/types/api'
|
||||
|
||||
const schema = z.object({
|
||||
saleId: z.string().min(1, 'Sale ID is required'),
|
||||
storeId: z.string().min(1, 'Store ID is required'),
|
||||
saleId: z.string().min(1, 'Sale 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'),
|
||||
collectedByUserId: z.string().min(1, 'Collected by is required'),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
@@ -40,28 +40,44 @@ interface PaymentSheetProps {
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
|
||||
const truncId = (id: string) => id.substring(0, 8)
|
||||
|
||||
export function PaymentSheet({ open, onClose, onSuccess }: PaymentSheetProps) {
|
||||
const [salesList, setSalesList] = useState<SaleResponse[]>([])
|
||||
const [usersList, setUsersList] = useState<UserResponse[]>([])
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
saleId: '',
|
||||
storeId: '',
|
||||
amount: 0,
|
||||
method: 'Cash',
|
||||
collectedAt: '',
|
||||
collectedByUserId: '',
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset({
|
||||
saleId: '',
|
||||
storeId: '',
|
||||
amount: 0,
|
||||
method: 'Cash',
|
||||
collectedAt: '',
|
||||
if (!open) return
|
||||
|
||||
form.reset({
|
||||
saleId: '',
|
||||
amount: 0,
|
||||
method: 'Cash',
|
||||
collectedByUserId: '',
|
||||
})
|
||||
|
||||
Promise.all([
|
||||
salesApi.list({ pageSize: 200 }),
|
||||
usersApi.list({ pageSize: 200 }),
|
||||
])
|
||||
.then(([salesRes, usersRes]) => {
|
||||
setSalesList(getPaginatedItems(salesRes).filter((s) => s.status !== 'Cancelled'))
|
||||
setUsersList(getPaginatedItems(usersRes))
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.add({ title: 'Failed to load reference data', description: getApiError(err), type: 'error' })
|
||||
})
|
||||
}
|
||||
}, [open])
|
||||
|
||||
async function onSubmit(values: FormValues) {
|
||||
@@ -80,7 +96,7 @@ export function PaymentSheet({ open, onClose, onSuccess }: PaymentSheetProps) {
|
||||
<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>
|
||||
<DialogDescription>Record a cash or credit payment against a sale.</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
|
||||
@@ -88,38 +104,22 @@ export function PaymentSheet({ open, onClose, onSuccess }: PaymentSheetProps) {
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="saleId"
|
||||
label="Sale ID"
|
||||
label="Sale"
|
||||
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}
|
||||
/>
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select sale..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="" disabled>Select sale...</SelectItem>
|
||||
{salesList.map((sale) => (
|
||||
<SelectItem key={sale.id} value={sale.id}>
|
||||
{truncId(sale.id)} — {fmtAmount(sale.totalAmount)} ({sale.paymentStatus})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -135,7 +135,7 @@ export function PaymentSheet({ open, onClose, onSuccess }: PaymentSheetProps) {
|
||||
ref={field.ref}
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={Number(field.value as string)}
|
||||
value={Number(field.value as number)}
|
||||
onChange={(e) => field.onChange(Number(e.target.value))}
|
||||
onBlur={field.onBlur}
|
||||
placeholder="0.00"
|
||||
@@ -167,20 +167,24 @@ export function PaymentSheet({ open, onClose, onSuccess }: PaymentSheetProps) {
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="collectedAt"
|
||||
label="Collected At"
|
||||
name="collectedByUserId"
|
||||
label="Collected By"
|
||||
description="Temporary — required until auth resolves the logged-in user automatically."
|
||||
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}
|
||||
/>
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select user..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="" disabled>Select user...</SelectItem>
|
||||
{usersList.map((user) => (
|
||||
<SelectItem key={user.id} value={user.id}>
|
||||
{user.fullName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
</FieldGroup>
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
'use client'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import type { PaymentResponse, PaymentMethod } from '@/types/api'
|
||||
|
||||
const PAYMENT_METHOD_VARIANT: Record<PaymentMethod, 'default' | 'secondary'> = {
|
||||
Cash: 'default',
|
||||
Credit: 'secondary',
|
||||
}
|
||||
|
||||
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
|
||||
const truncId = (id: string) => id.substring(0, 8)
|
||||
|
||||
const fmtDateTime = (v: string) =>
|
||||
new Date(v).toLocaleString('en-GB', {
|
||||
day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit',
|
||||
})
|
||||
|
||||
interface PaymentViewSheetProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
payment: PaymentResponse | null
|
||||
storeName?: string
|
||||
collectedByName?: string
|
||||
}
|
||||
|
||||
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 PaymentViewSheet({ open, onClose, payment, storeName, collectedByName }: PaymentViewSheetProps) {
|
||||
if (!payment) return null
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
|
||||
<DialogContent className="overflow-y-auto sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Payment Details</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col">
|
||||
<Row label="Payment ID" value={<span className="font-mono">{truncId(payment.id)}</span>} />
|
||||
<Row label="Sale ID" value={<span className="font-mono">{truncId(payment.saleId)}</span>} />
|
||||
<Row label="Store" value={storeName ?? <span className="font-mono">{truncId(payment.storeId)}</span>} />
|
||||
<Row label="Amount" value={fmtAmount(payment.amount)} />
|
||||
<Row label="Method" value={<Badge variant={PAYMENT_METHOD_VARIANT[payment.method]}>{payment.method}</Badge>} />
|
||||
<Row label="Collected At" value={fmtDateTime(payment.collectedAt)} />
|
||||
<Row label="Collected By" value={collectedByName ?? <span className="font-mono">{truncId(payment.collectedBy)}</span>} />
|
||||
<Row label="Created At" value={fmtDateTime(payment.createdAt)} />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -9,10 +9,11 @@ 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 { payments as paymentsApi, stores as storesApi, users as usersApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||
import type { PaymentResponse, PaymentMethod, StoreResponse, UserResponse } from '@/types/api'
|
||||
|
||||
import { PaymentSheet } from './payment-sheet'
|
||||
import { PaymentViewSheet } from './payment-view-sheet'
|
||||
|
||||
const fmtDate = (v: string) =>
|
||||
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
|
||||
@@ -33,6 +34,19 @@ export function PaymentsClient() {
|
||||
const [pageSize, setPageSize] = useState(20)
|
||||
|
||||
const [sheetOpen, setSheetOpen] = useState(false)
|
||||
const [viewOpen, setViewOpen] = useState(false)
|
||||
const [selectedPayment, setSelectedPayment] = useState<PaymentResponse | null>(null)
|
||||
const [storesList, setStoresList] = useState<StoreResponse[]>([])
|
||||
const [usersList, setUsersList] = useState<UserResponse[]>([])
|
||||
|
||||
const storeNameById = useMemo(
|
||||
() => new Map(storesList.map((s) => [s.id, s.storeName])),
|
||||
[storesList]
|
||||
)
|
||||
const userNameById = useMemo(
|
||||
() => new Map(usersList.map((u) => [u.id, u.fullName])),
|
||||
[usersList]
|
||||
)
|
||||
|
||||
const fetchData = useCallback(async (p: number, ps: number) => {
|
||||
setLoading(true)
|
||||
@@ -51,6 +65,20 @@ export function PaymentsClient() {
|
||||
fetchData(page, pageSize)
|
||||
}, [fetchData, page, pageSize])
|
||||
|
||||
useEffect(() => {
|
||||
storesApi.list({ pageSize: 200 })
|
||||
.then((res) => setStoresList(getPaginatedItems(res)))
|
||||
.catch((err) => toast.add({ title: 'Failed to load stores', description: getApiError(err), type: 'error' }))
|
||||
usersApi.list({ pageSize: 200 })
|
||||
.then((res) => setUsersList(getPaginatedItems(res)))
|
||||
.catch((err) => toast.add({ title: 'Failed to load users', description: getApiError(err), type: 'error' }))
|
||||
}, [])
|
||||
|
||||
function handleView(row: PaymentResponse) {
|
||||
setSelectedPayment(row)
|
||||
setViewOpen(true)
|
||||
}
|
||||
|
||||
const tableConfig = useMemo<TableConfig<PaymentResponse>>(() => ({
|
||||
rowKey: 'id',
|
||||
serverSide: true,
|
||||
@@ -69,11 +97,11 @@ export function PaymentsClient() {
|
||||
},
|
||||
{
|
||||
key: 'storeId',
|
||||
title: 'Store ID',
|
||||
title: 'Store',
|
||||
fields: ['storeId'],
|
||||
width: 140,
|
||||
minWidth: 160,
|
||||
cellRender: (row) => (
|
||||
<span className="font-mono text-sm">{truncId(row.storeId)}</span>
|
||||
<span className="text-sm">{storeNameById.get(row.storeId) ?? truncId(row.storeId)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -106,11 +134,20 @@ export function PaymentsClient() {
|
||||
fields: ['collectedBy'],
|
||||
minWidth: 160,
|
||||
cellRender: (row) => (
|
||||
<span className="text-sm text-muted-foreground">{row.collectedBy}</span>
|
||||
<span className="text-sm text-muted-foreground">{userNameById.get(row.collectedBy) ?? truncId(row.collectedBy)}</span>
|
||||
),
|
||||
},
|
||||
],
|
||||
}), [pageSize])
|
||||
rowActions: {
|
||||
actions: () => [
|
||||
{
|
||||
action: 'view',
|
||||
label: 'View payment',
|
||||
onClick: handleView,
|
||||
},
|
||||
],
|
||||
},
|
||||
}), [pageSize, storeNameById, userNameById])
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -143,6 +180,14 @@ export function PaymentsClient() {
|
||||
onClose={() => setSheetOpen(false)}
|
||||
onSuccess={() => fetchData(page, pageSize)}
|
||||
/>
|
||||
|
||||
<PaymentViewSheet
|
||||
open={viewOpen}
|
||||
onClose={() => setViewOpen(false)}
|
||||
payment={selectedPayment}
|
||||
storeName={selectedPayment ? storeNameById.get(selectedPayment.storeId) : undefined}
|
||||
collectedByName={selectedPayment ? userNameById.get(selectedPayment.collectedBy) : undefined}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user