Update sales UI
This commit is contained in:
@@ -1,354 +0,0 @@
|
|||||||
'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,
|
|
||||||
getPaginatedItems,
|
|
||||||
} 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 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(getPaginatedItems(stores))
|
|
||||||
setRidesList(getPaginatedItems(rides))
|
|
||||||
setItemsList(getPaginatedItems(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,111 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import { Separator } from '@/components/ui/separator'
|
||||||
|
import type { SaleResponse, SaleStatus, PaymentStatus } from '@/types/api'
|
||||||
|
|
||||||
|
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',
|
||||||
|
}
|
||||||
|
|
||||||
|
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
|
||||||
|
const truncId = (id: string) => id.substring(0, 8)
|
||||||
|
|
||||||
|
const fmtDateTime = (v: string | null) =>
|
||||||
|
v
|
||||||
|
? new Date(v).toLocaleString('en-GB', {
|
||||||
|
day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit',
|
||||||
|
})
|
||||||
|
: '—'
|
||||||
|
|
||||||
|
interface SaleViewSheetProps {
|
||||||
|
open: boolean
|
||||||
|
onClose: () => void
|
||||||
|
sale: SaleResponse | null
|
||||||
|
}
|
||||||
|
|
||||||
|
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 SaleViewSheet({ open, onClose, sale }: SaleViewSheetProps) {
|
||||||
|
if (!sale) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
|
||||||
|
<DialogContent className="overflow-y-auto sm:max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Sale Details</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<Row label="Sale ID" value={<span className="font-mono">{truncId(sale.id)}</span>} />
|
||||||
|
<Row label="Store ID" value={<span className="font-mono">{truncId(sale.storeId)}</span>} />
|
||||||
|
<Row label="Status" value={<Badge variant={SALE_STATUS_VARIANT[sale.status]}>{sale.status}</Badge>} />
|
||||||
|
<Row label="Payment Status" value={<Badge variant={PAYMENT_STATUS_VARIANT[sale.paymentStatus]}>{sale.paymentStatus}</Badge>} />
|
||||||
|
<Row label="Total Amount" value={fmtAmount(sale.totalAmount)} />
|
||||||
|
<Row label="Fulfill Immediately" value={sale.fulfillImmediately ? 'Yes' : 'No'} />
|
||||||
|
<Row label="Order Status" value={sale.orderStatus} />
|
||||||
|
<Row label="Sale Date" value={fmtDateTime(sale.saleDate)} />
|
||||||
|
<Row label="Completed At" value={fmtDateTime(sale.completedAt)} />
|
||||||
|
<Row label="Created At" value={fmtDateTime(sale.createdAt)} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium mb-2">Items ({sale.items.length})</p>
|
||||||
|
<div className="overflow-x-auto rounded-md border">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead className="bg-muted/50">
|
||||||
|
<tr>
|
||||||
|
<th className="text-left font-medium px-3 py-2">Item</th>
|
||||||
|
<th className="text-right font-medium px-3 py-2">Quantity</th>
|
||||||
|
<th className="text-right font-medium px-3 py-2">Fulfilled</th>
|
||||||
|
<th className="text-right font-medium px-3 py-2">Unit Price</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{sale.items.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={4} className="text-center text-muted-foreground px-3 py-4">
|
||||||
|
No items on this sale.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
sale.items.map((item) => (
|
||||||
|
<tr key={item.itemId} className="border-t">
|
||||||
|
<td className="px-3 py-2 font-mono">{truncId(item.itemId)}</td>
|
||||||
|
<td className="text-right px-3 py-2">{item.quantity}</td>
|
||||||
|
<td className="text-right px-3 py-2">{item.quantityFulfilled}</td>
|
||||||
|
<td className="text-right px-3 py-2">{fmtAmount(item.unitPrice)}</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useState, useEffect, useCallback, useMemo } from 'react'
|
import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
import { HugeiconsIcon } from '@hugeicons/react'
|
import { HugeiconsIcon } from '@hugeicons/react'
|
||||||
import { Add01Icon } from '@hugeicons/core-free-icons'
|
import { Add01Icon } from '@hugeicons/core-free-icons'
|
||||||
|
|
||||||
@@ -12,7 +13,7 @@ import { toast } from '@/components/ui/toast'
|
|||||||
import { sales as salesApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
import { sales as salesApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||||
import type { SaleResponse, SaleStatus, PaymentStatus } from '@/types/api'
|
import type { SaleResponse, SaleStatus, PaymentStatus } from '@/types/api'
|
||||||
|
|
||||||
import { SaleSheet } from './sale-sheet'
|
import { SaleViewSheet } from './sale-view-sheet'
|
||||||
|
|
||||||
const fmtDate = (v: string) =>
|
const fmtDate = (v: string) =>
|
||||||
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
|
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
|
||||||
@@ -33,12 +34,14 @@ const PAYMENT_STATUS_VARIANT: Record<PaymentStatus, 'default' | 'secondary' | 'd
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function SalesClient() {
|
export function SalesClient() {
|
||||||
|
const router = useRouter()
|
||||||
const [data, setData] = useState<SaleResponse[]>([])
|
const [data, setData] = useState<SaleResponse[]>([])
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [total, setTotal] = useState(0)
|
const [total, setTotal] = useState(0)
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [pageSize, setPageSize] = useState(20)
|
const [pageSize, setPageSize] = useState(20)
|
||||||
const [sheetOpen, setSheetOpen] = useState(false)
|
const [viewOpen, setViewOpen] = useState(false)
|
||||||
|
const [selectedSale, setSelectedSale] = useState<SaleResponse | null>(null)
|
||||||
|
|
||||||
const fetchData = useCallback(async (p: number, ps: number) => {
|
const fetchData = useCallback(async (p: number, ps: number) => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
@@ -57,6 +60,21 @@ export function SalesClient() {
|
|||||||
fetchData(page, pageSize)
|
fetchData(page, pageSize)
|
||||||
}, [fetchData, page, pageSize])
|
}, [fetchData, page, pageSize])
|
||||||
|
|
||||||
|
function handleView(row: SaleResponse) {
|
||||||
|
setSelectedSale(row)
|
||||||
|
setViewOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleCancel(row: SaleResponse) {
|
||||||
|
try {
|
||||||
|
await salesApi.cancel(row.id)
|
||||||
|
toast.add({ title: 'Sale cancelled', type: 'success' })
|
||||||
|
fetchData(page, pageSize)
|
||||||
|
} catch (err) {
|
||||||
|
toast.add({ title: 'Failed to cancel sale', description: getApiError(err), type: 'error' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const tableConfig = useMemo<TableConfig<SaleResponse>>(() => ({
|
const tableConfig = useMemo<TableConfig<SaleResponse>>(() => ({
|
||||||
rowKey: 'id',
|
rowKey: 'id',
|
||||||
serverSide: true,
|
serverSide: true,
|
||||||
@@ -122,6 +140,21 @@ export function SalesClient() {
|
|||||||
width: 140,
|
width: 140,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
rowActions: {
|
||||||
|
actions: () => [
|
||||||
|
{
|
||||||
|
action: 'view',
|
||||||
|
label: 'View sale',
|
||||||
|
onClick: handleView,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
action: 'cancel',
|
||||||
|
label: 'Cancel sale',
|
||||||
|
onClick: handleCancel,
|
||||||
|
visible: (target) => target.status !== 'Cancelled',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
}), [pageSize])
|
}), [pageSize])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -133,7 +166,7 @@ export function SalesClient() {
|
|||||||
Sales transactions recorded against stores
|
Sales transactions recorded against stores
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Button onClick={() => setSheetOpen(true)}>
|
<Button onClick={() => router.push('/sales/new')}>
|
||||||
<HugeiconsIcon icon={Add01Icon} size={16} />
|
<HugeiconsIcon icon={Add01Icon} size={16} />
|
||||||
Add Sale
|
Add Sale
|
||||||
</Button>
|
</Button>
|
||||||
@@ -150,10 +183,10 @@ export function SalesClient() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<SaleSheet
|
<SaleViewSheet
|
||||||
open={sheetOpen}
|
open={viewOpen}
|
||||||
onClose={() => setSheetOpen(false)}
|
onClose={() => setViewOpen(false)}
|
||||||
onSuccess={() => fetchData(page, pageSize)}
|
sale={selectedSale}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,412 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
import { useFieldArray, useWatch } from 'react-hook-form'
|
||||||
|
import { HugeiconsIcon } from '@hugeicons/react'
|
||||||
|
import { ArrowLeft01Icon, Add01Icon, Delete02Icon } from '@hugeicons/core-free-icons'
|
||||||
|
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 { FieldGroup } from '@/components/ui/field'
|
||||||
|
import { Separator } from '@/components/ui/separator'
|
||||||
|
import { toast } from '@/components/ui/toast'
|
||||||
|
import {
|
||||||
|
sales as salesApi,
|
||||||
|
stores as storesApi,
|
||||||
|
rides as ridesApi,
|
||||||
|
items as itemsApi,
|
||||||
|
users as usersApi,
|
||||||
|
getApiError,
|
||||||
|
getPaginatedItems,
|
||||||
|
} from '@/lib/api/index'
|
||||||
|
import type { ItemSummaryResponse, RideResponse, StoreResponse, UserResponse } 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'),
|
||||||
|
saleDate: z.string().min(1, 'Sale date is required'),
|
||||||
|
createdByUserId: z.string().min(1, 'Created by 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>
|
||||||
|
|
||||||
|
function createDefaultItem() {
|
||||||
|
return { itemId: '', quantity: 1, unitPrice: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
function todayIso() {
|
||||||
|
return new Date().toISOString().slice(0, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
|
||||||
|
|
||||||
|
export default function NewSalePage() {
|
||||||
|
const router = useRouter()
|
||||||
|
const [storesList, setStoresList] = useState<StoreResponse[]>([])
|
||||||
|
const [ridesList, setRidesList] = useState<RideResponse[]>([])
|
||||||
|
const [itemsList, setItemsList] = useState<ItemSummaryResponse[]>([])
|
||||||
|
const [usersList, setUsersList] = useState<UserResponse[]>([])
|
||||||
|
|
||||||
|
const form = useForm<FormValues>({
|
||||||
|
resolver: zodResolver(schema),
|
||||||
|
defaultValues: {
|
||||||
|
storeId: '',
|
||||||
|
saleDate: todayIso(),
|
||||||
|
createdByUserId: '',
|
||||||
|
rideId: '',
|
||||||
|
fulfillImmediately: false,
|
||||||
|
items: [createDefaultItem()],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const { fields, append, remove } = useFieldArray({
|
||||||
|
control: form.control,
|
||||||
|
name: 'items',
|
||||||
|
})
|
||||||
|
|
||||||
|
const watchedItems = useWatch({ control: form.control, name: '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(() => {
|
||||||
|
Promise.all([
|
||||||
|
storesApi.list({ pageSize: 200 }),
|
||||||
|
ridesApi.list({ pageSize: 200, rideType: 'Sale' }),
|
||||||
|
itemsApi.list({ pageSize: 200 }),
|
||||||
|
usersApi.list({ pageSize: 200 }),
|
||||||
|
])
|
||||||
|
.then(([stores, rides, items, usersRes]) => {
|
||||||
|
setStoresList(getPaginatedItems(stores))
|
||||||
|
setRidesList(getPaginatedItems(rides))
|
||||||
|
setItemsList(getPaginatedItems(items))
|
||||||
|
setUsersList(getPaginatedItems(usersRes))
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
toast.add({ title: 'Failed to load reference data', description: getApiError(err), type: 'error' })
|
||||||
|
})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
async function onSubmit(values: FormValues) {
|
||||||
|
try {
|
||||||
|
await salesApi.create({
|
||||||
|
storeId: values.storeId,
|
||||||
|
saleDate: values.saleDate,
|
||||||
|
rideId: values.rideId || null,
|
||||||
|
fulfillImmediately: values.fulfillImmediately,
|
||||||
|
items: values.items,
|
||||||
|
createdByUserId: values.createdByUserId,
|
||||||
|
})
|
||||||
|
toast.add({ title: 'Sale created', type: 'success' })
|
||||||
|
router.push('/sales')
|
||||||
|
} catch (err) {
|
||||||
|
toast.add({ title: 'Failed to create sale', description: getApiError(err), type: 'error' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-6">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => router.push('/sales')}>
|
||||||
|
<HugeiconsIcon icon={ArrowLeft01Icon} size={16} strokeWidth={2} />
|
||||||
|
Back
|
||||||
|
</Button>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-semibold text-foreground">Create Sale</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">Record a sale for a store with one or more items.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
|
||||||
|
<div className="rounded-2xl border p-6">
|
||||||
|
<h3 className="mb-4 text-sm font-medium text-foreground">Sale Details</h3>
|
||||||
|
<FieldGroup>
|
||||||
|
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<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="saleDate"
|
||||||
|
label="Sale Date"
|
||||||
|
required
|
||||||
|
render={({ field, invalid }) => (
|
||||||
|
<Input
|
||||||
|
id="saleDate"
|
||||||
|
name={field.name}
|
||||||
|
ref={field.ref}
|
||||||
|
type="date"
|
||||||
|
value={field.value as string}
|
||||||
|
onChange={field.onChange}
|
||||||
|
onBlur={field.onBlur}
|
||||||
|
aria-invalid={invalid}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<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 (van sale)
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</FieldGroup>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-2xl border p-6">
|
||||||
|
<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">
|
||||||
|
Quantity and unit price use the selected item's base UOM.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => append(createDefaultItem())}>
|
||||||
|
<HugeiconsIcon icon={Add01Icon} size={16} />
|
||||||
|
Add Item
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="overflow-x-auto rounded-xl border">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead className="bg-muted/50">
|
||||||
|
<tr>
|
||||||
|
<th className="min-w-[220px] px-3 py-2 text-left font-medium">Item</th>
|
||||||
|
<th className="w-28 px-3 py-2 text-left font-medium">Quantity</th>
|
||||||
|
<th className="w-32 px-3 py-2 text-left font-medium">Unit Price</th>
|
||||||
|
<th className="w-32 px-3 py-2 text-right font-medium">Line Total</th>
|
||||||
|
<th className="w-10 px-3 py-2"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{fields.map((fieldItem, index) => {
|
||||||
|
const selectedItem = itemsById.get(watchedItems[index]?.itemId ?? '')
|
||||||
|
const lineTotal = (Number(watchedItems[index]?.quantity) || 0) * (Number(watchedItems[index]?.unitPrice) || 0)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<tr key={fieldItem.id} className="border-t align-top">
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name={`items.${index}.itemId`}
|
||||||
|
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>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
{selectedItem && (
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">
|
||||||
|
In {selectedItem.baseUomName}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name={`items.${index}.quantity`}
|
||||||
|
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}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name={`items.${index}.unitPrice`}
|
||||||
|
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}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
<td className="px-3 py-2 text-right font-medium">{fmtAmount(lineTotal)}</td>
|
||||||
|
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={fields.length === 1}
|
||||||
|
onClick={() => remove(index)}
|
||||||
|
>
|
||||||
|
<HugeiconsIcon icon={Delete02Icon} size={16} />
|
||||||
|
</Button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<div className="w-full rounded-2xl border p-6 sm:w-96">
|
||||||
|
<h3 className="text-sm font-medium text-foreground">Sale Summary</h3>
|
||||||
|
<p className="mt-1 text-sm text-muted-foreground">
|
||||||
|
{watchedItems.length} item{watchedItems.length === 1 ? '' : 's'} on this sale.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<Separator className="my-4" />
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<p className="text-sm font-medium text-foreground">Total</p>
|
||||||
|
<p className="text-xl font-semibold text-foreground">{fmtAmount(totalAmount)}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-6 flex flex-col gap-2">
|
||||||
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||||
|
{form.formState.isSubmitting ? 'Creating...' : 'Create Sale'}
|
||||||
|
</Button>
|
||||||
|
<Button type="button" variant="outline" onClick={() => router.push('/sales')}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -22,9 +22,12 @@ export interface SaleItemBody {
|
|||||||
|
|
||||||
export interface SaleBody {
|
export interface SaleBody {
|
||||||
storeId: string
|
storeId: string
|
||||||
|
saleDate: string
|
||||||
rideId?: string | null
|
rideId?: string | null
|
||||||
fulfillImmediately?: boolean
|
fulfillImmediately?: boolean
|
||||||
items: SaleItemBody[]
|
items: SaleItemBody[]
|
||||||
|
// TEMPORARY: required while auth doesn't resolve a logged-in user server-side — see testbug.md #28.
|
||||||
|
createdByUserId: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SaleListParams extends PageParams {
|
export interface SaleListParams extends PageParams {
|
||||||
|
|||||||
Reference in New Issue
Block a user