JEISA-WEBAPP/src/components/purchase-orders/PurchaseOrderForm.tsx

351 lines
12 KiB
TypeScript
Raw Normal View History

2025-09-11 11:39:50 +00:00
"use client"
import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm, useFieldArray } from "react-hook-form"
2025-09-11 11:39:50 +00:00
import * as z from "zod"
import { useState, useEffect, useCallback } from "react" // Import useState and useEffect
2025-09-11 11:39:50 +00:00
import { Button } from "@/components/ui/button"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select" // Import Select components
import { showSuccess, showError } from "@/utils/toast"
import pb from "@/lib/pocketbase"
// Define the schema for a single item in the purchase order
const itemSchema = z.object({
stockItemId: z.string().min(1, { message: "Stock item ID is required." }),
itemName: z.string().min(1, { message: "Item name is required." }),
quantity: z.number().int().positive(),
sku: z.string(),
costPrice: z.number(),
2025-09-11 11:39:50 +00:00
})
// Define the type for the items array
type ItemSchemaType = z.infer<typeof itemSchema>;
// Define the schema for the purchase order form
const purchaseOrderFormSchema = z.object({
supplierName: z.string().min(1, { message: "Supplier name is required." }),
orderDate: z.date({ required_error: "Order date is required." }),
items: z.array(itemSchema).min(1, { message: "At least one item is required." }),
})
2025-09-11 11:39:50 +00:00
interface PurchaseOrderFormProps {
setOpen: (open: boolean) => void
refreshData: () => void
2025-09-11 11:39:50 +00:00
}
// Define the type for a supplier
type Supplier = {
id: string
name: string
}
// Define the type for a stock item
type StockItem = {
id: string
name: string
sku: string
costPrice: number
}
export function PurchaseOrderForm({ setOpen, refreshData }: PurchaseOrderFormProps) {
const [suppliers, setSuppliers] = useState<Supplier[]>([]) // State to hold suppliers
const [stockItems, setStockItems] = useState<StockItem[]>([]) // State to hold stock items
// Fetch suppliers when the component mounts
const fetchSuppliers = useCallback(async () => {
try {
const records = await pb.collection('suppliers').getFullList({
sort: '-created',
});
const formattedSuppliers: Supplier[] = records.map((item: any) => ({
id: item.id,
name: item.supplier_name, // Use the correct field name from PocketBase
}));
setSuppliers(formattedSuppliers);
} catch (error) {
console.error("Error fetching suppliers:", error);
showError("Failed to load suppliers.");
}
}, []);
// Fetch stock items when the component mounts
const fetchStockItems = useCallback(async () => {
try {
const records = await pb.collection('stock_items').getFullList({
sort: '-created',
});
const formattedStockItems: StockItem[] = records.map((item: any) => ({
id: item.id,
name: item.name,
sku: item.sku,
costPrice: item.cost_price, // Assuming cost_price is the field in stock_items
}));
setStockItems(formattedStockItems);
} catch (error) {
console.error("Error fetching stock items:", error);
showError("Failed to load stock items.");
}
}, []);
useEffect(() => {
fetchSuppliers();
fetchStockItems();
}, [fetchSuppliers, fetchStockItems]);
const form = useForm<z.infer<typeof purchaseOrderFormSchema>>({
resolver: zodResolver(purchaseOrderFormSchema),
2025-09-11 11:39:50 +00:00
defaultValues: {
supplierName: "",
orderDate: new Date(),
items: [{
stockItemId: "",
itemName: "",
quantity: 1,
sku: "",
costPrice: 0,
}],
2025-09-11 11:39:50 +00:00
},
})
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "items",
});
// Function to add a new item row
const addItem = () => {
append({
stockItemId: "",
itemName: "",
quantity: 1,
sku: "",
costPrice: 0,
});
}
// Function to remove an item row
const removeItem = (index: number) => {
remove(index);
}
// Function to handle changes in item fields
const handleItemChange = (index: number, field: keyof ItemSchemaType, value: any) => {
const currentItems = form.getValues("items");
const newItems = [...currentItems];
const currentItem = newItems[index] as ItemSchemaType;
if (field === "quantity") {
currentItem[field] = parseInt(value, 10) || 0;
} else if (field === "costPrice") {
currentItem[field] = parseFloat(value) || 0;
} else {
currentItem[field] = value;
}
newItems[index] = currentItem;
form.setValue("items", newItems);
}
// Function to handle stock item selection from dropdown
const handleStockItemSelect = (index: number, selectedItemName: string) => {
const selectedStockItem = stockItems.find(item => item.name === selectedItemName);
if (selectedStockItem) {
// Update the form fields with the selected stock item's details
handleItemChange(index, "stockItemId", selectedStockItem.id);
handleItemChange(index, "itemName", selectedStockItem.name);
handleItemChange(index, "sku", selectedStockItem.sku);
handleItemChange(index, "costPrice", selectedStockItem.costPrice);
// Quantity remains as is or defaults to 1 if not set
if (form.getValues("items")[index].quantity === 0) {
handleItemChange(index, "quantity", 1);
}
}
}
async function onSubmit(values: z.infer<typeof purchaseOrderFormSchema>) {
2025-09-11 11:39:50 +00:00
try {
// Find the selected supplier's ID
const selectedSupplier = suppliers.find(s => s.name === values.supplierName);
if (!selectedSupplier) {
showError("Invalid supplier selected.");
return;
}
// Prepare data for PocketBase
const purchaseOrderData = {
supplierName: values.supplierName, // This will be the supplier's name for display
supplier: selectedSupplier.id, // This will be the relation to the suppliers collection
orderDate: values.orderDate.toISOString(),
status: "Pending Approval",
items: values.items.map(item => item.stockItemId),
quantities: values.items.map(item => item.quantity), // Keep quantities array as well if needed elsewhere
};
await pb.collection('purchase_orders').create(purchaseOrderData);
showSuccess("Purchase order created successfully!");
form.reset();
setOpen(false);
refreshData();
} catch (error) {
console.error("Error creating purchase order:", error);
showError("Failed to create purchase order. Please check the form and try again.");
2025-09-11 11:39:50 +00:00
}
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
2025-09-11 11:39:50 +00:00
<FormField
control={form.control}
name="supplierName"
2025-09-11 11:39:50 +00:00
render={({ field }) => (
<FormItem>
<FormLabel>Supplier</FormLabel>
<Select onValueChange={(value) => {
field.onChange(value);
}} value={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select a supplier" />
</SelectTrigger>
</FormControl>
<SelectContent>
{suppliers.map((supplier) => (
<SelectItem key={supplier.id} value={supplier.name}>
{supplier.name}
</SelectItem>
))}
</SelectContent>
</Select>
2025-09-11 11:39:50 +00:00
<FormMessage />
</FormItem>
)}
/>
2025-09-11 11:39:50 +00:00
<FormField
control={form.control}
name="orderDate"
2025-09-11 11:39:50 +00:00
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Order Date</FormLabel>
<FormControl>
<Input
type="date"
{...field}
onChange={(e) => field.onChange(new Date(e.target.value))}
value={field.value instanceof Date ? field.value.toISOString().split('T')[0] : ''}
/>
</FormControl>
2025-09-11 11:39:50 +00:00
<FormMessage />
</FormItem>
)}
/>
{/* Items Section */}
<div className="border p-4 rounded-md">
<h3 className="text-lg font-semibold mb-4">Order Items</h3>
{fields.map((item, index) => (
<div key={item.id} className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-[2fr,1fr,1fr,1fr,auto] gap-4 mb-4 items-center">
<FormField
control={form.control}
name={`items.${index}.itemName`}
render={({ field }) => (
<FormItem>
<FormLabel>Item Name</FormLabel>
<Select
onValueChange={(selectedValue) => handleStockItemSelect(index, selectedValue)}
value={field.value} // Set the current value of the item name
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select item" />
</SelectTrigger>
</FormControl>
<SelectContent>
{stockItems.map((stockItem) => (
<SelectItem key={stockItem.id} value={stockItem.name}>
{stockItem.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`items.${index}.sku`}
render={({ field }) => (
<FormItem>
<FormLabel>SKU</FormLabel>
<FormControl>
{/* Display SKU, but it's managed by handleStockItemSelect */}
<Input {...field} readOnly placeholder="SKU" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`items.${index}.quantity`}
render={({ field }) => (
<FormItem>
<FormLabel>Quantity</FormLabel>
<FormControl>
<Input type="number" {...field} onChange={(e) => handleItemChange(index, "quantity", e.target.value)} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`items.${index}.costPrice`}
render={({ field }) => (
<FormItem>
<FormLabel>Unit Price (ZAR)</FormLabel>
<FormControl>
<Input type="number" step="0.01" {...field} onChange={(e) => handleItemChange(index, "costPrice", e.target.value)} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-center md:justify-start">
{fields.length > 1 && (
<Button type="button" variant="outline" size="icon" onClick={() => removeItem(index)} className="w-full sm:w-auto">
-
</Button>
)}
</div>
</div>
))}
<Button type="button" variant="outline" onClick={addItem} className="mt-2">
Add Item
</Button>
</div>
<Button type="submit" className="w-full">Create Purchase Order</Button>
2025-09-11 11:39:50 +00:00
</form>
</Form>
)
}