PO shops fe fixes

This commit is contained in:
2026-09-24 15:04:42 +05:30
parent 3b0a5f0d3f
commit 1ec5426d15
5 changed files with 498 additions and 31 deletions
@@ -0,0 +1,279 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { useParams, 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 { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import { toast } from '@/components/ui/toast'
import {
shopPos as shopPosApi,
items as itemsApi,
priceLists as priceListsApi,
getApiError,
getPaginatedItems,
} from '@/lib/api/index'
import type { ItemSummaryResponse, ShopPOResponse } from '@/types/api'
const lineItemSchema = 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({
items: z.array(lineItemSchema).min(1, 'At least one item is required'),
})
type FormValues = z.infer<typeof schema>
function createDefaultItem() {
return { itemId: '', quantity: 1, unitPrice: 0 }
}
const fmtAmount = (n: number) => `Rs. ${n.toLocaleString()}`
export default function EditShopPOPage() {
const router = useRouter()
const { id } = useParams<{ id: string }>()
const [po, setPo] = useState<ShopPOResponse | null>(null)
const [itemsList, setItemsList] = useState<ItemSummaryResponse[]>([])
const [loading, setLoading] = useState(true)
const form = useForm<FormValues>({
resolver: zodResolver(schema),
defaultValues: { 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, line) => sum + (Number(line.quantity) || 0) * (Number(line.unitPrice) || 0), 0),
[watchedItems]
)
useEffect(() => {
Promise.all([shopPosApi.get(id), itemsApi.list({ pageSize: 200 })])
.then(([poRes, items]) => {
setPo(poRes)
setItemsList(getPaginatedItems(items))
form.reset({
items: poRes.items
.filter((i) => i.isActive)
.map((i) => ({ itemId: i.itemId, quantity: i.quantity, unitPrice: i.unitPrice })),
})
})
.catch((err) => {
toast.add({ title: 'Failed to load Shop PO', description: getApiError(err), type: 'error' })
})
.finally(() => setLoading(false))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id])
async function resolveAndSetPrice(index: number, itemId: string) {
const today = new Date().toISOString().slice(0, 10)
if (po) {
try {
const resolution = await priceListsApi.resolve({ itemId, storeId: po.storeId, saleDate: today })
form.setValue(`items.${index}.unitPrice`, resolution.price, { shouldValidate: true })
return
} catch {
// No resolvable price for this store — fall back to item default.
}
}
const item = itemsById.get(itemId)
if (item) form.setValue(`items.${index}.unitPrice`, item.salePrice, { shouldValidate: true })
}
async function onSubmit(values: FormValues) {
try {
await shopPosApi.updateItems(id, { items: values.items })
toast.add({ title: 'Shop PO updated', type: 'success' })
router.push('/sales')
} catch (err) {
toast.add({ title: 'Failed to update Shop PO', description: getApiError(err), type: 'error' })
}
}
if (loading) return <p className="text-sm text-muted-foreground">Loading...</p>
if (!po) return <p className="text-sm text-muted-foreground">Shop PO not found.</p>
const locked = !!po.confirmedAt || po.status === 'Cancelled'
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">Edit Shop PO</h1>
<p className="text-sm text-muted-foreground">
{po.storeName} — items can only be changed before the PO is confirmed.
</p>
</div>
</div>
{locked && (
<p className="rounded-xl border border-destructive/40 p-4 text-sm text-destructive">
This Shop PO is {po.confirmedAt ? 'confirmed' : 'cancelled'} and can no longer be edited.
</p>
)}
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-6">
<div className="rounded-2xl border p-6">
<div className="mb-4 flex items-start justify-between gap-4">
<h3 className="text-sm font-medium text-foreground">Items</h3>
<Button type="button" variant="outline" size="sm" disabled={locked} 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 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}
disabled={locked}
onValueChange={(value) => {
field.onChange(value)
if (value) resolveAndSetPrice(index, value)
}}
>
<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>
)}
/>
</td>
<td className="px-3 py-2">
<FormField
control={form.control}
name={`items.${index}.quantity`}
render={({ field, invalid }) => (
<Input
type="number"
min={1}
disabled={locked}
value={Number(field.value as number)}
onChange={(e) => field.onChange(Number(e.target.value))}
onBlur={field.onBlur}
aria-invalid={invalid}
/>
)}
/>
</td>
<td className="px-3 py-2">
<FormField
control={form.control}
name={`items.${index}.unitPrice`}
render={({ field, invalid }) => (
<Input
type="number"
min={0.01}
step="0.01"
disabled={locked}
value={Number(field.value as number)}
onChange={(e) => field.onChange(Number(e.target.value))}
onBlur={field.onBlur}
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={locked || 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">Order Summary</h3>
<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={locked || form.formState.isSubmitting}>
{form.formState.isSubmitting ? 'Saving...' : 'Save Changes'}
</Button>
<Button type="button" variant="outline" onClick={() => router.push('/sales')}>
Cancel
</Button>
</div>
</div>
</div>
</form>
</div>
)
}
@@ -11,6 +11,7 @@ import { shopPos as shopPosApi, getApiError } from '@/lib/api/index'
import type { ShopPOResponse, ShopPOStatus } from '@/types/api'
import { ConfirmShopPODialog } from '../_components/confirm-shop-po-dialog'
import { CancelShopPODialog } from '../_components/cancel-shop-po-dialog'
const PO_STATUS_VARIANT: Record<ShopPOStatus, 'default' | 'secondary' | 'destructive'> = {
Pending: 'secondary',
@@ -44,6 +45,7 @@ export default function ShopPOViewPage() {
const [po, setPo] = useState<ShopPOResponse | null>(null)
const [loading, setLoading] = useState(true)
const [confirmOpen, setConfirmOpen] = useState(false)
const [cancelOpen, setCancelOpen] = useState(false)
useEffect(() => {
let cancelled = false
@@ -65,17 +67,6 @@ export default function ShopPOViewPage() {
}
}, [params.id, router])
async function handleCancel() {
if (!po) return
try {
const updated = await shopPosApi.cancel(po.id)
setPo(updated)
toast.add({ title: 'Shop PO cancelled', type: 'success' })
} catch (err) {
toast.add({ title: 'Failed to cancel Shop PO', description: getApiError(err), type: 'error' })
}
}
if (loading) {
return (
<div className="flex flex-col gap-6">
@@ -120,7 +111,7 @@ export default function ShopPOViewPage() {
</Button>
)}
{po.status !== 'Cancelled' && po.status !== 'Fulfilled' && (
<Button type="button" variant="outline" onClick={handleCancel}>
<Button type="button" variant="outline" onClick={() => setCancelOpen(true)}>
Cancel PO
</Button>
)}
@@ -212,6 +203,12 @@ export default function ShopPOViewPage() {
}}
po={po}
/>
<CancelShopPODialog
open={cancelOpen}
onClose={() => setCancelOpen(false)}
onSuccess={setPo}
po={po}
/>
</div>
)
}