JEISA-WEBAPP/src/components/purchase-orders/EditPurchaseOrderDialog.tsx
SJCoetz d4be480ecb Add PO snapshot_items and edit/order handling
Add a PocketBase migration and store snapshot_items on purchase order creation so POs keep item details even if stock items change or are deleted. Wire snapshot_items through the UI: PurchaseOrders list prefers snapshot data when present; EditPurchaseOrderDialog supports snapshot fallback, SKU, entryMode (stock/manual), add/remove rows, and updates stock item GBP prices for stock-mode items. BookOutForm now deducts stock quantities on booking out and surfaces precise errors. Minor UI and behavior tweaks: low-stock report filters only actual stock items, columns typing includes snapshotItems, and edit action/menu is always available with an Edit dialog integrated into the PurchaseOrders page.
2026-05-24 00:11:37 +02:00

246 lines
8.5 KiB
TypeScript

"use client"
import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm, useFieldArray } from "react-hook-form"
import * as z from "zod"
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import pb from "@/lib/pocketbase"
import { PurchaseOrder } from "./columns"
import { showError, showSuccess } from "@/utils/toast"
import { AttachmentUpload, AttachmentList } from "./AttachmentUpload"
const rowSchema = z.object({
stockItemId: z.string(),
itemName: z.string(),
sku: z.string(),
quantity: z.coerce.number().int().min(1),
unitPriceGBP: z.coerce.number().min(0),
entryMode: z.enum(['stock', 'manual']).default('stock'),
})
const formSchema = z.object({
rows: z.array(rowSchema),
})
interface EditPurchaseOrderDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
order: PurchaseOrder
refreshData: () => void
}
export function EditPurchaseOrderDialog({ open, onOpenChange, order, refreshData }: EditPurchaseOrderDialogProps) {
const [files, setFiles] = React.useState<File[]>([])
// Use snapshot_items if available, fall back to live items
const sourceItems = order.snapshotItems && order.snapshotItems.length > 0
? order.snapshotItems
: order.items.map((item, idx) => ({
...item,
entryMode: 'stock' as const,
}))
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
rows: sourceItems.map((item) => ({
stockItemId: item.stockItemId,
itemName: item.itemName,
sku: item.sku,
quantity: item.quantity,
unitPriceGBP: Number(item.costPriceGBP ?? 0),
entryMode: item.entryMode || 'stock',
})),
},
})
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "rows",
})
const rowsValues = form.watch("rows")
const subtotalGBP = React.useMemo(
() =>
(rowsValues || []).reduce(
(sum, r) => sum + (Number(r.quantity || 0) * Number(r.unitPriceGBP || 0)),
0
),
[rowsValues]
)
const addItem = () => {
append({
stockItemId: '',
itemName: '',
sku: '',
quantity: 1,
unitPriceGBP: 0,
entryMode: 'manual',
})
}
const onSubmit = async (values: z.infer<typeof formSchema>) => {
try {
// Build updated snapshot
const updatedSnapshot = values.rows.map(r => ({
stockItemId: r.stockItemId,
itemName: r.itemName,
sku: r.sku,
quantity: r.quantity,
costPrice: 0,
costPriceGBP: r.unitPriceGBP,
entryMode: r.entryMode,
}))
const formData = new FormData()
formData.append('quantities', JSON.stringify(values.rows.map(r => r.quantity)))
formData.append('snapshot_items', JSON.stringify(updatedSnapshot))
files.forEach(f => formData.append('attachments', f))
await pb.collection("purchase_orders").update(order.id, formData)
// Update stock item GBP prices for stock-mode items if changed
try {
await Promise.all(values.rows.map(async (r) => {
if (r.entryMode !== 'stock' || !r.stockItemId) return
const newGBP = Number(r.unitPriceGBP || 0)
if (Number.isFinite(newGBP) && newGBP >= 0) {
await pb.collection("stock_items").update(r.stockItemId, { cost_price_gbp: newGBP })
}
}))
} catch (e) {
console.error("Stock price update error:", e)
}
showSuccess("Purchase order updated")
refreshData()
onOpenChange(false)
} catch (e: any) {
console.error("Update order error:", e)
showError("Failed to update purchase order")
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="mx-4 sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Edit Purchase Order</DialogTitle>
<DialogDescription>{order.orderNumber || order.id}</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<div className="border p-4 rounded-md">
<h3 className="text-lg font-semibold mb-4">Items</h3>
{fields.map((field, index) => (
<div
key={field.id}
className="grid grid-cols-1 md:grid-cols-[minmax(220px,1fr),120px,110px,140px,auto] gap-4 mb-4 items-start"
>
<FormField
control={form.control}
name={`rows.${index}.itemName`}
render={({ field }) => (
<FormItem>
<FormLabel>Item</FormLabel>
<FormControl>
<Input readOnly {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`rows.${index}.sku`}
render={({ field }) => (
<FormItem>
<FormLabel>SKU</FormLabel>
<FormControl>
<Input readOnly {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`rows.${index}.quantity`}
render={({ field }) => (
<FormItem>
<FormLabel>Qty</FormLabel>
<FormControl>
<Input
type="text"
inputMode="numeric"
pattern="[0-9]*"
className="text-right md:w-28"
value={field.value ?? ""}
onChange={(e) => field.onChange(e.target.value.replace(/[^0-9]/g, ""))}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`rows.${index}.unitPriceGBP`}
render={({ field }) => (
<FormItem>
<FormLabel>Unit Price (£)</FormLabel>
<FormControl>
<Input
type="text"
inputMode="decimal"
pattern="^[0-9]*[.,]?[0-9]*$"
className="text-right md:w-36"
value={field.value ?? ""}
onChange={(e) => field.onChange(e.target.value.replace(",", "."))}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex items-start pt-5">
<Button type="button" variant="outline" size="icon" onClick={() => remove(index)}>
-
</Button>
</div>
</div>
))}
<Button type="button" variant="outline" onClick={addItem} className="mt-2">
Add Item
</Button>
<div className="mt-4 border-t pt-4">
<div className="flex items-center justify-end gap-6">
<div className="text-sm text-muted-foreground">Items total (GBP)</div>
<div className="text-lg font-semibold">£{subtotalGBP.toFixed(2)}</div>
</div>
</div>
</div>
<AttachmentList files={order.attachments || []} orderId={order.id} />
<AttachmentUpload
orderId={order.id}
existingFiles={order.attachments || []}
onFilesChange={setFiles}
/>
<Button type="submit" className="w-full">Save Changes</Button>
</form>
</Form>
</DialogContent>
</Dialog>
)
}