"use client"; import { useState } from "react"; import { createPurchaseOrder } from "@/lib/actions"; import type { ContactRow, OrderItemOption } from "@/lib/types"; type PurchaseOrderFormProps = { vendors: ContactRow[]; items: OrderItemOption[]; }; type DraftLine = { rowId: number; partId: number | ""; quantity: number; amount: number; }; function createEmptyLine(rowId: number): DraftLine { return { rowId, partId: "", quantity: 1, amount: 0 }; } export function PurchaseOrderForm({ vendors, items }: PurchaseOrderFormProps) { const [lines, setLines] = useState([createEmptyLine(1)]); function updateLine(rowId: number, patch: Partial) { setLines((current) => current.map((line) => { if (line.rowId !== rowId) { return line; } const nextLine = { ...line, ...patch }; if (patch.partId && typeof patch.partId === "number") { const item = items.find((candidate) => candidate.id === patch.partId); if (item) { nextLine.amount = item.unitCost; } } return nextLine; }) ); } function addLine() { setLines((current) => [...current, createEmptyLine(Date.now())]); } function removeLine(rowId: number) { setLines((current) => (current.length === 1 ? current : current.filter((line) => line.rowId !== rowId))); } const payload = JSON.stringify( lines .filter((line) => typeof line.partId === "number") .map((line) => ({ partId: line.partId, quantity: line.quantity, amount: line.amount })) ); return (
{lines.map((line, index) => (
updateLine(line.rowId, { quantity: Number(event.target.value) || 0 })} />
updateLine(line.rowId, { amount: Number(event.target.value) || 0 })} />
))}