import { useEffect, useState } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { api } from '../api'; export default function OrderNew() { const navigate = useNavigate(); const [searchParams] = useSearchParams(); const preselectedCustomerId = searchParams.get('customer'); const [customers, setCustomers] = useState([]); const [products, setProducts] = useState([]); const [customerId, setCustomerId] = useState(preselectedCustomerId || ''); const [walkInName, setWalkInName] = useState(''); const [items, setItems] = useState([]); const [status, setStatus] = useState('pending'); const [paymentMethod, setPaymentMethod] = useState(''); const [amountPaid, setAmountPaid] = useState(''); const [notes, setNotes] = useState(''); const [loading, setLoading] = useState(true); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); useEffect(() => { Promise.all([ api('/customers').then((r) => r.json()), api('/products').then((r) => r.json()), ]) .then(([c, p]) => { setCustomers(c); setProducts(p); if (preselectedCustomerId) setCustomerId(preselectedCustomerId); }) .catch(() => setError('Failed to load data')) .finally(() => setLoading(false)); }, [preselectedCustomerId]); function addLine() { const productId = products[0]?.id; if (!productId) return; setItems((prev) => [...prev, { product_id: productId, quantity: 1 }]); } function updateLine(index, field, value) { setItems((prev) => prev.map((line, i) => (i === index ? { ...line, [field]: value } : line))); } function removeLine(index) { setItems((prev) => prev.filter((_, i) => i !== index)); } const productById = Object.fromEntries(products.map((p) => [p.id, p])); let total = 0; for (const line of items) { const p = productById[line.product_id]; if (p) total += p.price * (Number(line.quantity) || 0); } function handleSubmit(e) { e.preventDefault(); if (items.length === 0 || products.length === 0) { setError(items.length === 0 ? 'Add at least one item.' : 'No products in inventory. Add products first.'); return; } const payload = { customer_id: customerId ? Number(customerId) : null, walk_in_name: !customerId && walkInName.trim() ? walkInName.trim() : undefined, status, payment_method: paymentMethod || null, amount_paid: amountPaid !== '' ? Number(amountPaid) : 0, notes: notes.trim() || null, items: items.map((line) => ({ product_id: line.product_id, quantity: Number(line.quantity) || 0, })).filter((line) => line.quantity > 0), }; if (payload.items.length === 0) { setError('Add at least one item with quantity > 0.'); return; } setSubmitting(true); setError(null); api('/orders', { method: 'POST', body: payload, }) .then((r) => { if (!r.ok) return r.json().then((e) => Promise.reject(new Error(e.error || 'Failed'))); return r.json(); }) .then((order) => navigate(`/orders/${order.id}`)) .catch((e) => setError(e.message)) .finally(() => setSubmitting(false)); } if (loading) return
Loading...
; return ( <>{error}
} > ); }