Add order return management
This commit is contained in:
+293
@@ -0,0 +1,293 @@
|
||||
'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 { 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 { HugeiconsIcon } from '@hugeicons/react'
|
||||
import { Add01Icon, Delete02Icon } from '@hugeicons/core-free-icons'
|
||||
import {
|
||||
saleReturns as saleReturnsApi,
|
||||
orders as ordersApi,
|
||||
stores as storesApi,
|
||||
items as itemsApi,
|
||||
users as usersApi,
|
||||
getApiError,
|
||||
getPaginatedItems,
|
||||
} from '@/lib/api/index'
|
||||
import type { OrderResponse, ItemSummaryResponse, UserResponse, ReturnReasonCode } from '@/types/api'
|
||||
|
||||
const REASON_CODES: ReturnReasonCode[] = ['Expired', 'Damaged', 'OrderError', 'Other']
|
||||
|
||||
const returnItemSchema = z.object({
|
||||
itemId: z.string().min(1, 'Item is required'),
|
||||
quantity: z.number().min(1, 'Quantity must be at least 1'),
|
||||
reasonCode: z.enum(['Expired', 'Damaged', 'OrderError', 'Other']),
|
||||
})
|
||||
|
||||
const schema = z.object({
|
||||
orderId: z.string().min(1, 'Order is required'),
|
||||
mode: z.enum(['CreditDeduction', 'ItemExchange']),
|
||||
createdByUserId: z.string().min(1, 'Created by is required'),
|
||||
items: z.array(returnItemSchema).min(1, 'At least one item is required'),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
interface OrderReturnDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
function defaultItem() {
|
||||
return { itemId: '', quantity: 1, reasonCode: 'Damaged' as ReturnReasonCode }
|
||||
}
|
||||
|
||||
export function OrderReturnDialog({ open, onClose, onSuccess }: OrderReturnDialogProps) {
|
||||
const [ordersList, setOrdersList] = useState<OrderResponse[]>([])
|
||||
const [storeNameById, setStoreNameById] = useState<Map<string, string>>(new Map())
|
||||
const [itemsList, setItemsList] = useState<ItemSummaryResponse[]>([])
|
||||
const [usersList, setUsersList] = useState<UserResponse[]>([])
|
||||
const [selectedOrder, setSelectedOrder] = useState<OrderResponse | null>(null)
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { orderId: '', mode: 'CreditDeduction', createdByUserId: '', items: [defaultItem()] },
|
||||
})
|
||||
|
||||
const { fields, append, remove } = useFieldArray({ control: form.control, name: 'items' })
|
||||
const itemsById = useMemo(() => new Map(itemsList.map((i) => [i.id, i])), [itemsList])
|
||||
|
||||
const eligibleOrders = useMemo(
|
||||
() => ordersList.filter((o) => o.status !== 'Cancelled' && o.status !== 'Fulfilled'),
|
||||
[ordersList]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
form.reset({ orderId: '', mode: 'CreditDeduction', createdByUserId: '', items: [defaultItem()] })
|
||||
setSelectedOrder(null)
|
||||
Promise.all([
|
||||
ordersApi.list(),
|
||||
storesApi.list({ pageSize: 200 }),
|
||||
itemsApi.list({ pageSize: 200 }),
|
||||
usersApi.list({ pageSize: 200 }),
|
||||
])
|
||||
.then(([orderList, storeList, itemsRes, usersRes]) => {
|
||||
setOrdersList(orderList)
|
||||
setStoreNameById(new Map(getPaginatedItems(storeList).map((s) => [s.id, s.storeName])))
|
||||
setItemsList(getPaginatedItems(itemsRes))
|
||||
setUsersList(getPaginatedItems(usersRes))
|
||||
})
|
||||
.catch((err) => toast.add({ title: 'Failed to load reference data', description: getApiError(err), type: 'error' }))
|
||||
}, [open])
|
||||
|
||||
function handleOrderChange(orderId: string | null) {
|
||||
form.setValue('orderId', orderId ?? '', { shouldValidate: true })
|
||||
const order = orderId ? ordersList.find((o) => o.id === orderId) ?? null : null
|
||||
setSelectedOrder(order)
|
||||
}
|
||||
|
||||
async function onSubmit(values: FormValues) {
|
||||
try {
|
||||
await saleReturnsApi.create(values.orderId, {
|
||||
mode: values.mode,
|
||||
items: values.items,
|
||||
createdByUserId: values.createdByUserId,
|
||||
})
|
||||
toast.add({ title: 'Order return recorded', type: 'success' })
|
||||
onSuccess()
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to record return', description: getApiError(err), type: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => { if (!v) onClose() }}>
|
||||
<DialogContent className="flex max-h-[85vh] flex-col overflow-hidden sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Record Order Return</DialogTitle>
|
||||
<DialogDescription>
|
||||
Record items a store returned against an open order. Only items the store has previously
|
||||
ordered can be returned.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto">
|
||||
<FieldGroup>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="orderId"
|
||||
label="Order"
|
||||
required
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={handleOrderChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select order..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="" disabled>Select order...</SelectItem>
|
||||
{eligibleOrders.map((o) => (
|
||||
<SelectItem key={o.id} value={o.id}>
|
||||
{storeNameById.get(o.storeId) ?? o.storeId.slice(0, 8)} — {o.id.slice(0, 8).toUpperCase()} ({o.status})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="mode"
|
||||
label="Return Mode"
|
||||
required
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select mode..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="CreditDeduction">Credit Deduction</SelectItem>
|
||||
<SelectItem value="ItemExchange">Item Exchange</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="createdByUserId"
|
||||
label="Created By"
|
||||
description="Temporary — required until auth resolves the logged-in user automatically."
|
||||
required
|
||||
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>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</FieldGroup>
|
||||
|
||||
{selectedOrder && (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm font-medium text-foreground">Items to Return</p>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => append(defaultItem())}>
|
||||
<HugeiconsIcon icon={Add01Icon} size={14} strokeWidth={2} />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{fields.map((f, index) => (
|
||||
<div key={f.id} className="grid grid-cols-[1fr_100px_140px_auto] items-start gap-3 rounded-xl border p-3">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.itemId`}
|
||||
label="Item"
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select item..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="" disabled>Select item...</SelectItem>
|
||||
{selectedOrder.items.map((oi) => {
|
||||
const item = itemsById.get(oi.itemId)
|
||||
return (
|
||||
<SelectItem key={oi.itemId} value={oi.itemId}>
|
||||
{item?.name ?? oi.itemId.slice(0, 8)} {item ? `— ${item.sku}` : ''}
|
||||
</SelectItem>
|
||||
)
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.quantity`}
|
||||
label="Qty"
|
||||
render={({ field, invalid }) => (
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
value={Number(field.value as number)}
|
||||
onChange={(e) => field.onChange(Number(e.target.value))}
|
||||
onBlur={field.onBlur}
|
||||
aria-invalid={invalid}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.reasonCode`}
|
||||
label="Reason"
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Reason..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{REASON_CODES.map((code) => (
|
||||
<SelectItem key={code} value={code}>{code}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
|
||||
{fields.length > 1 && (
|
||||
<Button type="button" variant="outline" size="sm" className="mt-6" onClick={() => remove(index)}>
|
||||
<HugeiconsIcon icon={Delete02Icon} size={14} strokeWidth={2} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting || !selectedOrder}>
|
||||
{form.formState.isSubmitting ? 'Saving…' : 'Record Return'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
import { useFieldArray } from 'react-hook-form'
|
||||
import { useForm, zodResolver, z } from '@/lib/form'
|
||||
import { FormField } from '@/components/shared/form-field'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
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 { saleReturns as saleReturnsApi, getApiError } from '@/lib/api/index'
|
||||
import type { SaleReturnResponse, ReturnReasonCode } from '@/types/api'
|
||||
|
||||
const REASON_CODES: ReturnReasonCode[] = ['Expired', 'Damaged', 'OrderError', 'Other']
|
||||
|
||||
const schema = z.object({
|
||||
items: z.array(z.object({
|
||||
itemId: z.string(),
|
||||
itemName: z.string(),
|
||||
reasonCode: z.enum(['Expired', 'Damaged', 'OrderError', 'Other']),
|
||||
})),
|
||||
})
|
||||
|
||||
type FormValues = z.infer<typeof schema>
|
||||
|
||||
interface OrderReturnEditDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
ret: SaleReturnResponse | null
|
||||
}
|
||||
|
||||
export function OrderReturnEditDialog({ open, onClose, onSuccess, ret }: OrderReturnEditDialogProps) {
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { items: [] },
|
||||
})
|
||||
|
||||
const { fields } = useFieldArray({ control: form.control, name: 'items' })
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !ret) return
|
||||
form.reset({
|
||||
items: ret.items.map((i) => ({ itemId: i.itemId, itemName: i.itemName, reasonCode: i.reasonCode })),
|
||||
})
|
||||
}, [open, ret])
|
||||
|
||||
if (!ret) return null
|
||||
|
||||
async function onSubmit(values: FormValues) {
|
||||
try {
|
||||
await saleReturnsApi.updateReasons(ret!.id, {
|
||||
items: values.items.map((i) => ({ itemId: i.itemId, reasonCode: i.reasonCode })),
|
||||
})
|
||||
toast.add({ title: 'Return updated', type: 'success' })
|
||||
onSuccess()
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to update return', description: getApiError(err), type: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => { if (!v) onClose() }}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Edit Order Return</DialogTitle>
|
||||
<DialogDescription>
|
||||
The return was already applied to stock and the order total when it was recorded, so
|
||||
quantity and mode can't be changed. Only each line's reason can be corrected.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
|
||||
<FieldGroup>
|
||||
{fields.map((f, index) => (
|
||||
<div key={f.id} className="flex items-center justify-between gap-4">
|
||||
<span className="text-sm font-medium">{f.itemName}</span>
|
||||
<div className="w-40">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.reasonCode`}
|
||||
render={({ field }) => (
|
||||
<Select value={field.value as string} onValueChange={field.onChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Reason..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{REASON_CODES.map((code) => (
|
||||
<SelectItem key={code} value={code}>{code}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</FieldGroup>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>Cancel</Button>
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Saving…' : 'Save Changes'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
'use client'
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import type { SaleReturnResponse, ReturnMode } from '@/types/api'
|
||||
|
||||
const MODE_LABEL: Record<ReturnMode, string> = {
|
||||
CreditDeduction: 'Credit Deduction',
|
||||
ItemExchange: 'Item Exchange',
|
||||
}
|
||||
|
||||
const fmtDateTime = (v: string) =>
|
||||
new Date(v).toLocaleString('en-GB', {
|
||||
day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit',
|
||||
})
|
||||
|
||||
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
|
||||
|
||||
interface OrderReturnViewSheetProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
ret: SaleReturnResponse | null
|
||||
storeName?: 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 OrderReturnViewSheet({ open, onClose, ret, storeName }: OrderReturnViewSheetProps) {
|
||||
if (!ret) return null
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
|
||||
<DialogContent className="overflow-y-auto sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Order Return Details</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col">
|
||||
{storeName && <Row label="Store" value={storeName} />}
|
||||
<Row label="Order ID" value={<span className="font-mono text-xs">{ret.orderId}</span>} />
|
||||
<Row label="Mode" value={<Badge>{MODE_LABEL[ret.mode]}</Badge>} />
|
||||
<Row label="Total Credit Amount" value={fmtAmount(ret.totalCreditAmount)} />
|
||||
<Row label="Order Total After" value={fmtAmount(ret.orderTotalAmountAfter)} />
|
||||
<Row label="Created" value={fmtDateTime(ret.createdAt)} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-2 text-sm font-medium text-foreground">Returned Items</p>
|
||||
<div className="overflow-x-auto rounded-xl border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/50">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left font-medium">Item</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Qty</th>
|
||||
<th className="px-3 py-2 text-left font-medium">Reason</th>
|
||||
<th className="px-3 py-2 text-right font-medium">Unit Price</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{ret.items.map((item) => (
|
||||
<tr key={item.id} className="border-t">
|
||||
<td className="px-3 py-2">
|
||||
{item.itemName}
|
||||
<span className="ml-1 text-xs text-muted-foreground">({item.sku})</span>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right">{item.quantity}</td>
|
||||
<td className="px-3 py-2">{item.reasonCode}</td>
|
||||
<td className="px-3 py-2 text-right">{fmtAmount(item.unitPrice)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
'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 { saleReturns as saleReturnsApi, orders as ordersApi, stores as storesApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||
import type { SaleReturnResponse, ReturnMode } from '@/types/api'
|
||||
import { OrderReturnViewSheet } from './order-return-view-sheet'
|
||||
import { OrderReturnDialog } from './order-return-dialog'
|
||||
import { OrderReturnEditDialog } from './order-return-edit-dialog'
|
||||
|
||||
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 MODE_VARIANT: Record<ReturnMode, 'default' | 'secondary'> = {
|
||||
CreditDeduction: 'default',
|
||||
ItemExchange: 'secondary',
|
||||
}
|
||||
|
||||
export function OrderReturnsClient() {
|
||||
const [data, setData] = useState<SaleReturnResponse[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [pageSize, setPageSize] = useState(20)
|
||||
const [storeNameByOrderId, setStoreNameByOrderId] = useState<Map<string, string>>(new Map())
|
||||
const [viewing, setViewing] = useState<SaleReturnResponse | null>(null)
|
||||
const [viewOpen, setViewOpen] = useState(false)
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [editing, setEditing] = useState<SaleReturnResponse | null>(null)
|
||||
const [editOpen, setEditOpen] = useState(false)
|
||||
|
||||
function openView(row: SaleReturnResponse) {
|
||||
setViewing(row)
|
||||
setViewOpen(true)
|
||||
}
|
||||
|
||||
function openEdit(row: SaleReturnResponse) {
|
||||
setEditing(row)
|
||||
setEditOpen(true)
|
||||
}
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [returns, orderList, storeList] = await Promise.all([
|
||||
saleReturnsApi.list(),
|
||||
ordersApi.list(),
|
||||
storesApi.list({ pageSize: 200 }),
|
||||
])
|
||||
const storeNameById = new Map(getPaginatedItems(storeList).map((s) => [s.id, s.storeName]))
|
||||
const map = new Map(orderList.map((o) => [o.id, storeNameById.get(o.storeId) ?? '—']))
|
||||
setStoreNameByOrderId(map)
|
||||
setData(returns)
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to load order returns', description: getApiError(err), type: 'error' })
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
const tableConfig = useMemo<TableConfig<SaleReturnResponse>>(() => ({
|
||||
rowKey: 'id',
|
||||
stickyHeader: true,
|
||||
emptyMessage: 'No order returns recorded yet.',
|
||||
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
|
||||
columns: [
|
||||
{
|
||||
key: 'store',
|
||||
title: 'Store',
|
||||
fields: ['orderId'],
|
||||
minWidth: 200,
|
||||
cellRender: (row) => (
|
||||
<span className="text-sm font-medium">{storeNameByOrderId.get(row.orderId) ?? '—'}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'mode',
|
||||
title: 'Mode',
|
||||
fields: ['mode'],
|
||||
width: 160,
|
||||
cellRender: (row) => (
|
||||
<Badge variant={MODE_VARIANT[row.mode]}>{row.mode === 'CreditDeduction' ? 'Credit Deduction' : 'Item Exchange'}</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'itemCount',
|
||||
title: 'Items',
|
||||
fields: ['items'],
|
||||
width: 100,
|
||||
cellRender: (row) => (
|
||||
<span className="text-sm text-muted-foreground">{row.items.length}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'totalCreditAmount',
|
||||
title: 'Credit Amount',
|
||||
fields: ['totalCreditAmount'],
|
||||
width: 140,
|
||||
cellRender: (row) => (
|
||||
<span className="text-sm font-medium">{fmtAmount(row.totalCreditAmount)}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'createdAt',
|
||||
title: 'Created',
|
||||
fields: [{ key: 'createdAt', transform: (v) => fmtDate(v as string) }],
|
||||
width: 140,
|
||||
},
|
||||
],
|
||||
rowActions: {
|
||||
actions: () => [
|
||||
{
|
||||
action: 'view',
|
||||
label: 'View return',
|
||||
onClick: openView,
|
||||
},
|
||||
{
|
||||
action: 'edit',
|
||||
label: 'Edit return',
|
||||
onClick: openEdit,
|
||||
},
|
||||
],
|
||||
},
|
||||
}), [pageSize, storeNameByOrderId])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-foreground">Order Returns</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
Items a store returned during a sale visit
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setCreateOpen(true)}>
|
||||
<HugeiconsIcon icon={Add01Icon} size={16} strokeWidth={2} />
|
||||
Record Return
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
config={tableConfig}
|
||||
data={data}
|
||||
loading={loading}
|
||||
totalCount={data.length}
|
||||
onServerSideChange={({ page: p }) => {
|
||||
setPageSize(p.pageSize)
|
||||
}}
|
||||
/>
|
||||
|
||||
<OrderReturnViewSheet
|
||||
open={viewOpen}
|
||||
onClose={() => setViewOpen(false)}
|
||||
ret={viewing}
|
||||
storeName={viewing ? storeNameByOrderId.get(viewing.orderId) : undefined}
|
||||
/>
|
||||
|
||||
<OrderReturnDialog
|
||||
open={createOpen}
|
||||
onClose={() => setCreateOpen(false)}
|
||||
onSuccess={fetchData}
|
||||
/>
|
||||
|
||||
<OrderReturnEditDialog
|
||||
open={editOpen}
|
||||
onClose={() => setEditOpen(false)}
|
||||
onSuccess={fetchData}
|
||||
ret={editing}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { OrderReturnsClient } from './_components/order-returns-client'
|
||||
|
||||
export default function OrderReturnsPage() {
|
||||
return <OrderReturnsClient />
|
||||
}
|
||||
Reference in New Issue
Block a user