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.
This commit is contained in:
SJCoetz 2026-05-24 00:11:37 +02:00
parent 6db980b4ca
commit d4be480ecb
7 changed files with 202 additions and 50 deletions

View file

@ -0,0 +1,24 @@
/// <reference path="../pb_data/types.d.ts" />
migrate((app) => {
const collection = app.findCollectionByNameOrId("pbc_1342968361");
// Add snapshot_items JSON field to store item details at time of PO creation
collection.fields.addAt(4, new Field({
"hidden": false,
"id": "",
"maxSize": 0,
"name": "snapshot_items",
"presentable": false,
"required": false,
"system": false,
"type": "json"
}));
return app.save(collection);
}, (app) => {
const collection = app.findCollectionByNameOrId("pbc_1342968361");
collection.fields.removeByName("snapshot_items");
return app.save(collection);
});

View file

@ -165,10 +165,18 @@ export function BookOutForm({ setOpen, refreshData }: BookOutFormProps) {
// Create one book out record per item with its quantity
for (const item of values.items) {
// Deduct stock first
const stockItem = await pb.collection('stock_items').getOne(item.stockItemId);
const newQty = (stockItem.quantity || 0) - item.quantity;
if (newQty < 0) {
throw new Error(`Insufficient stock for "${item.itemName}". Available: ${stockItem.quantity}, Requested: ${item.quantity}`);
}
await pb.collection('stock_items').update(item.stockItemId, { quantity: newQty });
const bookOutData = {
bookOutDate: values.bookOutDate.toISOString(),
customer: values.customer,
items: [item.stockItemId], // single item ID in array
items: [item.stockItemId],
quantity: item.quantity,
date_booked_out: values.bookOutDate.toISOString(),
};
@ -188,7 +196,7 @@ export function BookOutForm({ setOpen, refreshData }: BookOutFormProps) {
// Log the error
await logger.logError('Failed to book out stock', error, 'admin', 'book-out');
showError("Failed to book out stock. Please check the form and try again.");
showError(error instanceof Error ? error.message : "Failed to book out stock. Please check the form and try again.");
}
}

View file

@ -22,8 +22,10 @@ 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({
@ -39,19 +41,30 @@ interface EditPurchaseOrderDialogProps {
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: order.items.map((item, idx) => ({
rows: sourceItems.map((item) => ({
stockItemId: item.stockItemId,
itemName: item.itemName,
quantity: order.quantities[idx] ?? 1,
sku: item.sku,
quantity: item.quantity,
unitPriceGBP: Number(item.costPriceGBP ?? 0),
entryMode: item.entryMode || 'stock',
})),
},
})
const { fields } = useFieldArray({
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "rows",
})
@ -66,22 +79,43 @@ export function EditPurchaseOrderDialog({ open, onOpenChange, order, refreshData
[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))
// If there are new attachments, set status to Ordered
if (files.length > 0) {
formData.append('status', 'Ordered')
}
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, idx) => {
const existingGBP = Number(order.items[idx].costPriceGBP ?? 0)
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 && newGBP !== existingGBP) {
if (Number.isFinite(newGBP) && newGBP >= 0) {
await pb.collection("stock_items").update(r.stockItemId, { cost_price_gbp: newGBP })
}
}))
@ -103,7 +137,7 @@ export function EditPurchaseOrderDialog({ open, onOpenChange, order, refreshData
<DialogContent className="mx-4 sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Edit Purchase Order</DialogTitle>
<DialogDescription>Order ID: {order.id}</DialogDescription>
<DialogDescription>{order.orderNumber || order.id}</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
@ -112,7 +146,7 @@ export function EditPurchaseOrderDialog({ open, onOpenChange, order, refreshData
{fields.map((field, index) => (
<div
key={field.id}
className="grid grid-cols-1 md:grid-cols-[minmax(220px,1fr),110px,140px] gap-4 mb-4 items-start"
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}
@ -127,6 +161,19 @@ export function EditPurchaseOrderDialog({ open, onOpenChange, order, refreshData
</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`}
@ -167,11 +214,19 @@ export function EditPurchaseOrderDialog({ open, onOpenChange, order, refreshData
</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-gray-600">Items total (GBP)</div>
<div className="text-sm text-muted-foreground">Items total (GBP)</div>
<div className="text-lg font-semibold">£{subtotalGBP.toFixed(2)}</div>
</div>
</div>

View file

@ -300,6 +300,35 @@ export function PurchaseOrderForm({ setOpen, refreshData }: PurchaseOrderFormPro
})
);
// Build snapshot items — store full details so PO survives stock item deletion
const snapshotItems = await Promise.all(
values.items.map(async (item) => {
if (item.entryMode === 'manual') {
const existing = stockItems.find(si => si.sku === item.manualSku && item.manualSku);
const stockItemId = existing ? existing.id : '';
return {
stockItemId,
itemName: item.manualDescription || item.manualSku || 'Unnamed Item',
sku: item.manualSku || '',
quantity: item.quantity,
costPrice: 0,
costPriceGBP: item.manualUnitPrice || 0,
entryMode: 'manual' as const,
};
}
const stockItem = stockItems.find(si => si.id === item.stockItemId);
return {
stockItemId: item.stockItemId,
itemName: item.itemName,
sku: item.sku,
quantity: item.quantity,
costPrice: Number(item.costPrice || 0),
costPriceGBP: Number(stockItem?.costPriceGBP || 0),
entryMode: 'stock' as const,
};
})
);
// Build the PO data
const purchaseOrderData: Record<string, any> = {
order_number: values.orderNumber,
@ -311,6 +340,7 @@ export function PurchaseOrderForm({ setOpen, refreshData }: PurchaseOrderFormPro
status: "Pending",
items: resolvedItems,
quantities: values.items.map(item => item.quantity),
snapshot_items: snapshotItems,
};
// Use FormData for file attachments

View file

@ -33,6 +33,7 @@ export type PurchaseOrder = {
carriageCharge?: number
items: Array<{ stockItemId: string; itemName: string; quantity: number; sku: string; costPrice: number; costPriceGBP: number }>
quantities: number[]
snapshotItems?: Array<{ stockItemId: string; itemName: string; quantity: number; sku: string; costPrice: number; costPriceGBP: number; entryMode?: 'stock' | 'manual' }>
supplier?: {
name: string
address: string
@ -141,12 +142,10 @@ export const createColumns = ({ onDownloadPdf, onViewOrder, onEditOrder, onManag
<Eye className="mr-2 h-4 w-4" />
View Order
</DropdownMenuItem>
{!!onEditOrder && (
<DropdownMenuItem onClick={() => onEditOrder(order)}>
<Pencil className="mr-2 h-4 w-4" />
Edit Order
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={() => onEditOrder?.(order)}>
<Pencil className="mr-2 h-4 w-4" />
Edit Order
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onDownloadPdf(order)}>
<Download className="mr-2 h-4 w-4" />
Download PDF

View file

@ -18,7 +18,7 @@ export function LowStockReport() {
setLoading(true)
try {
const records = await pb.collection("stock_items").getFullList({
filter: `quantity < ${threshold}`,
filter: `quantity < ${threshold} && stock_item = true`,
sort: "quantity",
})
const formatted: LowStockRecord[] = records.map((item: any) => ({

View file

@ -1,5 +1,6 @@
import { useState, useEffect, useCallback } from "react";
import { PurchaseOrderForm } from "@/components/purchase-orders/PurchaseOrderForm";
import { EditPurchaseOrderDialog } from "@/components/purchase-orders/EditPurchaseOrderDialog";
import { Button } from "@/components/ui/button";
import { PlusCircle } from "lucide-react";
import {
@ -84,6 +85,8 @@ const PurchaseOrders = () => {
const [selectedOrderForView, setSelectedOrderForView] = useState<PurchaseOrder | null>(null);
const [attachmentsDialogOpen, setAttachmentsDialogOpen] = useState(false);
const [selectedOrderForAttachments, setSelectedOrderForAttachments] = useState<PurchaseOrder | null>(null);
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [selectedOrderForEdit, setSelectedOrderForEdit] = useState<PurchaseOrder | null>(null);
const fetchPurchaseOrders = useCallback(async () => {
try {
@ -92,33 +95,51 @@ const PurchaseOrders = () => {
expand: 'items,supplierName',
});
const formattedData = records.items.map((record) => ({
id: record.id,
supplierName: record.supplierName,
orderDate: record.orderDate,
status: record.status,
itemCount: record.items?.length || 0,
orderNumber: record.order_number || record.id,
accountRef: record.account_ref || '',
salesOrderNo: record.sales_order_no || '',
carriageCharge: record.carriage_charge || 0,
items: (record.expand?.items || []).map((item: any) => ({
stockItemId: item.id,
itemName: item.name,
quantity: item.quantity,
sku: item.sku,
costPrice: item.cost_price,
costPriceGBP: item.cost_price_gbp || 0,
})),
quantities: record.quantities || [],
supplier: record.expand?.supplierName ? {
name: record.expand.supplierName.supplier_name || '',
address: record.expand.supplierName.suppier_address || '',
email: record.expand.supplierName.supplier_email || '',
phone: record.expand.supplierName.supplier_phone_number || '',
} : null,
attachments: record.attachments || [],
}));
const formattedData = records.items.map((record) => {
// Use snapshot_items if available, otherwise fall back to live expand
const useSnapshot = record.snapshot_items && Array.isArray(record.snapshot_items) && record.snapshot_items.length > 0;
const items = useSnapshot
? record.snapshot_items.map((item: any) => ({
stockItemId: item.stockItemId || '',
itemName: item.itemName || 'Unknown',
quantity: item.quantity || 0,
sku: item.sku || '',
costPrice: item.costPrice || 0,
costPriceGBP: item.costPriceGBP || 0,
}))
: (record.expand?.items || []).map((item: any) => ({
stockItemId: item.id,
itemName: item.name,
quantity: item.quantity,
sku: item.sku,
costPrice: item.cost_price,
costPriceGBP: item.cost_price_gbp || 0,
}));
const snapshotItems = useSnapshot ? record.snapshot_items : undefined;
return {
id: record.id,
supplierName: record.supplierName,
orderDate: record.orderDate,
status: record.status,
itemCount: items.length,
orderNumber: record.order_number || record.id,
accountRef: record.account_ref || '',
salesOrderNo: record.sales_order_no || '',
carriageCharge: record.carriage_charge || 0,
items,
snapshotItems,
quantities: useSnapshot ? items.map((i: any) => i.quantity) : (record.quantities || []),
supplier: record.expand?.supplierName ? {
name: record.expand.supplierName.supplier_name || '',
address: record.expand.supplierName.suppier_address || '',
email: record.expand.supplierName.supplier_email || '',
phone: record.expand.supplierName.supplier_phone_number || '',
} : null,
attachments: record.attachments || [],
};
});
setPurchaseOrders(formattedData);
} catch (err) {
@ -148,7 +169,12 @@ const PurchaseOrders = () => {
setAttachmentsDialogOpen(true);
}, []);
const columns = createColumns({ onDownloadPdf: handleDownloadPdf, onViewOrder: handleViewOrder, onManageAttachments: handleManageAttachments });
const handleEditOrder = useCallback((order: PurchaseOrder) => {
setSelectedOrderForEdit(order);
setEditDialogOpen(true);
}, []);
const columns = createColumns({ onDownloadPdf: handleDownloadPdf, onViewOrder: handleViewOrder, onEditOrder: handleEditOrder, onManageAttachments: handleManageAttachments });
return (
<div className="space-y-6">
@ -236,6 +262,16 @@ const PurchaseOrders = () => {
)}
</DialogContent>
</Dialog>
{/* Edit Order Dialog */}
{selectedOrderForEdit && (
<EditPurchaseOrderDialog
open={editDialogOpen}
onOpenChange={setEditDialogOpen}
order={selectedOrderForEdit}
refreshData={handleRefreshData}
/>
)}
</div>
);
};