"use client"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Plus, Trash2 } from "lucide-react"; import { formatCurrency } from "@/lib/pb-helpers"; interface LineItem { id?: string; description: string; quantity: number; cost_price: number; markup?: number; selling_price: number; } interface LineItemsTableProps { items: LineItem[]; onChange: (items: LineItem[]) => void; readOnly?: boolean; } export function LineItemsTable({ items, onChange, readOnly = false }: LineItemsTableProps) { const updateItem = (index: number, field: keyof LineItem, value: string | number) => { const updated = [...items]; const item = { ...updated[index], [field]: value }; if (field === "cost_price" || field === "markup") { const cost = field === "cost_price" ? Number(value) : item.cost_price; const markup = field === "markup" ? Number(value) : item.markup || 0; item.selling_price = Number((cost * (1 + markup / 100)).toFixed(2)); } updated[index] = item; onChange(updated); }; const addItem = () => { onChange([ ...items, { description: "", quantity: 1, cost_price: 0, markup: 0, selling_price: 0, }, ]); }; const removeItem = (index: number) => { onChange(items.filter((_, i) => i !== index)); }; const subtotal = items.reduce((sum, item) => sum + item.selling_price * item.quantity, 0); const vat = subtotal * 0.15; const total = subtotal + vat; return (
Description Qty Cost Markup % Selling Total {!readOnly && } {items.length === 0 ? ( No line items. Click "Add Item" to add one. ) : ( items.map((item, index) => ( {readOnly ? ( item.description ) : ( updateItem(index, "description", e.target.value)} placeholder="Item description" /> )} {readOnly ? ( item.quantity ) : ( updateItem(index, "quantity", Number(e.target.value))} /> )} {readOnly ? ( formatCurrency(item.cost_price) ) : ( updateItem(index, "cost_price", Number(e.target.value))} /> )} {readOnly ? ( `${item.markup || 0}%` ) : ( updateItem(index, "markup", Number(e.target.value))} /> )} {formatCurrency(item.selling_price)} {formatCurrency(item.selling_price * item.quantity)} {!readOnly && ( )} )) )}
{!readOnly && ( )}
Subtotal {formatCurrency(subtotal)}
VAT (15%) {formatCurrency(vat)}
Grand Total {formatCurrency(total)}
); }