import { IconButton, MenuItem, Table, TableBody, TableCell, TableHead, TableRow, TextField } from '@mui/material'; import DeleteIcon from '@mui/icons-material/Delete'; import { MoneyCell } from '../../../components/common/MoneyCell'; import type { GLAccount, TaxCode } from '../../../types/api'; export interface APDocumentLineDraft { key: number; description: string; quantity: string; unitPrice: string; expenseGLAccountId: number | ''; taxCodeId: number | ''; } let keySeed = 0; export const blankAPDocumentLine = (): APDocumentLineDraft => ({ key: keySeed++, description: '', quantity: '1', unitPrice: '', expenseGLAccountId: '', taxCodeId: '', }); export function apLineTotals(line: APDocumentLineDraft, taxCodes: TaxCode[]) { const quantity = Number(line.quantity) || 0; const unitPrice = Number(line.unitPrice) || 0; const subtotal = quantity * unitPrice; const rate = line.taxCodeId ? Number(taxCodes.find((t) => t.id === line.taxCodeId)?.ratePercent ?? 0) : 0; const tax = subtotal * (rate / 100); return { subtotal, tax, total: subtotal + tax }; } interface APDocumentLineEditorProps { lines: APDocumentLineDraft[]; onChange: (lines: APDocumentLineDraft[]) => void; expenseAccounts: GLAccount[]; taxCodes: TaxCode[]; } export function APDocumentLineEditor({ lines, onChange, expenseAccounts, taxCodes }: APDocumentLineEditorProps) { const updateLine = (key: number, patch: Partial) => onChange(lines.map((line) => (line.key === key ? { ...line, ...patch } : line))); const removeLine = (key: number) => onChange(lines.length > 1 ? lines.filter((line) => line.key !== key) : lines); return ( Description Qty Unit Price Expense Account Tax Amount {lines.map((line) => { const { total } = apLineTotals(line, taxCodes); return ( updateLine(line.key, { description: e.target.value })} /> updateLine(line.key, { quantity: e.target.value })} slotProps={{ htmlInput: { min: 0, step: '0.01', style: { textAlign: 'right' } } }} /> updateLine(line.key, { unitPrice: e.target.value })} slotProps={{ htmlInput: { min: 0, step: '0.01', style: { textAlign: 'right' } } }} /> updateLine(line.key, { expenseGLAccountId: Number(e.target.value) })} > {expenseAccounts.map((account) => ( {account.accountCode} — {account.accountName} ))} updateLine(line.key, { taxCodeId: e.target.value ? Number(e.target.value) : '' })} > None {taxCodes.map((taxCode) => ( {taxCode.code} ({Number(taxCode.ratePercent)}%) ))} removeLine(line.key)} disabled={lines.length <= 1}> ); })}
); }