"use client"; import { useState } from "react"; import { useParams, useRouter } from "next/navigation"; import useSWR from "swr"; import { Card, CardContent, CardHeader, CardTitle, } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { ArrowLeft, Plus, Trash2, Package, Save } from "lucide-react"; import { toast } from "sonner"; import { formatCurrency } from "@/lib/format"; import type { Customer, Product } from "@/lib/types"; const fetcher = (url: string) => fetch(url).then((r) => r.json()); interface OrderLineItem { product_id: string; quantity: string; unit_price: string; notes: string; } export default function NewOrderPage() { const params = useParams(); const router = useRouter(); const customerId = params.id as string; const [loading, setLoading] = useState(false); const [form, setForm] = useState({ po_number: "", customer_ref: "", status: "draft", order_date: new Date().toISOString().slice(0, 10), due_date: "", notes: "", }); const [items, setItems] = useState([ { product_id: "", quantity: "1", unit_price: "", notes: "" }, ]); const { data: customer } = useSWR( `/api/customers/${customerId}`, fetcher ); const { data: products = [] } = useSWR("/api/products", fetcher); function addLine() { setItems([ ...items, { product_id: "", quantity: "1", unit_price: "", notes: "" }, ]); } function removeLine(index: number) { if (items.length <= 1) return; setItems(items.filter((_, i) => i !== index)); } function updateLine(index: number, field: keyof OrderLineItem, value: string) { const updated = [...items]; updated[index] = { ...updated[index], [field]: value }; setItems(updated); } function getLineTotal(item: OrderLineItem) { const qty = Number(item.quantity) || 0; const price = Number(item.unit_price) || 0; return qty * price; } const orderTotal = items.reduce((sum, item) => sum + getLineTotal(item), 0); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); if (!form.po_number) { toast.error("PO Number is required"); return; } const validItems = items.filter((item) => item.product_id); if (validItems.length === 0) { toast.error("Add at least one product line item"); return; } setLoading(true); try { const res = await fetch("/api/orders", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ customer_id: Number(customerId), ...form, due_date: form.due_date || null, items: validItems.map((item) => ({ product_id: Number(item.product_id), quantity: Number(item.quantity) || 1, unit_price: Number(item.unit_price) || 0, notes: item.notes || null, })), }), }); if (!res.ok) { const err = await res.json(); throw new Error(err.error || "Failed to create order"); } toast.success("Purchase order created"); router.push(`/customers/${customerId}`); } catch (err) { toast.error( err instanceof Error ? err.message : "Failed to create order" ); } finally { setLoading(false); } } return (
{/* Header */}

New Purchase Order

{customer ? `Creating order for ${customer.name} (${customer.code})` : "Loading..."}

{/* Order Details */} Order Details
setForm({ ...form, po_number: e.target.value }) } placeholder="PO-2026-001" className="font-mono" required />
setForm({ ...form, customer_ref: e.target.value }) } placeholder="Their internal ref" />
setForm({ ...form, order_date: e.target.value }) } />
setForm({ ...form, due_date: e.target.value }) } />