// payment-modal.js — ES Module v3 (clean) // Invoice payments: multi-invoice, partial, overpay // No downpayment functionality let bankAccounts = []; let paymentMethods = []; let selectedInvoices = []; // { invoice, payAmount } let dataLoaded = false; // ============================================================ // Load QBO Data // ============================================================ async function loadQboData() { if (dataLoaded) return; try { const [accRes, pmRes] = await Promise.all([ fetch('/api/qbo/accounts'), fetch('/api/qbo/payment-methods') ]); if (accRes.ok) bankAccounts = await accRes.json(); if (pmRes.ok) paymentMethods = await pmRes.json(); dataLoaded = true; } catch (e) { console.error('Error loading QBO data:', e); } } // ============================================================ // Open / Close // ============================================================ export async function openPaymentModal(invoiceIds = []) { await loadQboData(); selectedInvoices = []; for (const id of invoiceIds) { try { const res = await fetch(`/api/invoices/${id}`); const data = await res.json(); if (data.invoice) { selectedInvoices.push({ invoice: data.invoice, payAmount: parseFloat(data.invoice.total) }); } } catch (e) { console.error('Error loading invoice:', id, e); } } ensureModalElement(); renderModalContent(); document.getElementById('payment-modal').classList.add('active'); } export function closePaymentModal() { const modal = document.getElementById('payment-modal'); if (modal) modal.classList.remove('active'); selectedInvoices = []; } // ============================================================ // Add / Remove Invoices // ============================================================ async function addInvoiceById() { const input = document.getElementById('payment-add-invoice-id'); const searchVal = input.value.trim(); if (!searchVal) return; try { const res = await fetch('/api/invoices'); const allInvoices = await res.json(); const match = allInvoices.find(inv => String(inv.id) === searchVal || String(inv.invoice_number) === searchVal ); if (!match) { alert(`No invoice with #/ID "${searchVal}" found.`); return; } if (!match.qbo_id) { alert('This invoice has not been exported to QBO yet.'); return; } if (match.paid_date) { alert('This invoice is already paid.'); return; } if (selectedInvoices.find(si => si.invoice.id === match.id)) { alert('Invoice already in list.'); return; } if (selectedInvoices.length > 0 && match.customer_id !== selectedInvoices[0].invoice.customer_id) { alert('All invoices must belong to the same customer.'); return; } const detailRes = await fetch(`/api/invoices/${match.id}`); const detailData = await detailRes.json(); selectedInvoices.push({ invoice: detailData.invoice, payAmount: parseFloat(detailData.invoice.total) }); renderInvoiceList(); updateTotal(); input.value = ''; } catch (e) { console.error('Error adding invoice:', e); alert('Error searching for invoice.'); } } function removeInvoice(invoiceId) { selectedInvoices = selectedInvoices.filter(si => si.invoice.id !== invoiceId); renderInvoiceList(); updateTotal(); } function updatePayAmount(invoiceId, newAmount) { const si = selectedInvoices.find(s => s.invoice.id === invoiceId); if (si) { si.payAmount = Math.max(0, parseFloat(newAmount) || 0); } renderInvoiceList(); updateTotal(); } // ============================================================ // DOM // ============================================================ function ensureModalElement() { let modal = document.getElementById('payment-modal'); if (!modal) { modal = document.createElement('div'); modal.id = 'payment-modal'; modal.className = 'modal fixed inset-0 bg-black bg-opacity-50 z-50 justify-center items-start pt-10 overflow-y-auto'; document.body.appendChild(modal); } } function renderModalContent() { const modal = document.getElementById('payment-modal'); if (!modal) return; const accountOptions = bankAccounts.map(a => ``).join(''); const filtered = paymentMethods.filter(p => /check|ach/i.test(p.name)); const methods = filtered.length > 0 ? filtered : paymentMethods; const methodOptions = methods.map(p => ``).join(''); const today = new Date().toISOString().split('T')[0]; modal.innerHTML = `

šŸ’° Record Payment

Total Payment: $0.00
`; renderInvoiceList(); updateTotal(); } function renderInvoiceList() { const container = document.getElementById('payment-invoice-list'); if (!container) return; if (selectedInvoices.length === 0) { container.innerHTML = `
No invoices selected — add below
`; return; } container.innerHTML = selectedInvoices.map(si => { const inv = si.invoice; const total = parseFloat(inv.total); const isPartial = si.payAmount < total; const isOver = si.payAmount > total; return `
#${inv.invoice_number || 'Draft'} ${inv.customer_name || ''} (Total: $${total.toFixed(2)}) ${isPartial ? 'Partial' : ''} ${isOver ? 'Overpay' : ''}
$
`; }).join(''); } function updateTotal() { const totalEl = document.getElementById('payment-total'); const noteEl = document.getElementById('payment-overpay-note'); if (!totalEl) return; const payTotal = selectedInvoices.reduce((s, si) => s + si.payAmount, 0); const invTotal = selectedInvoices.reduce((s, si) => s + parseFloat(si.invoice.total), 0); totalEl.textContent = `$${payTotal.toFixed(2)}`; if (noteEl) { if (payTotal > invTotal && invTotal > 0) { noteEl.textContent = `āš ļø Overpayment of $${(payTotal - invTotal).toFixed(2)} will be stored as customer credit in QBO.`; noteEl.classList.remove('hidden'); } else { noteEl.classList.add('hidden'); } } } // ============================================================ // Submit // ============================================================ async function submitPayment() { if (selectedInvoices.length === 0) { alert('Please add at least one invoice.'); return; } const paymentDate = document.getElementById('payment-date').value; const reference = document.getElementById('payment-reference').value; const methodSelect = document.getElementById('payment-method'); const depositSelect = document.getElementById('payment-deposit-to'); if (!paymentDate || !methodSelect.value || !depositSelect.value) { alert('Please fill in all fields.'); return; } const total = selectedInvoices.reduce((s, si) => s + si.payAmount, 0); const invTotal = selectedInvoices.reduce((s, si) => s + parseFloat(si.invoice.total), 0); const nums = selectedInvoices.map(si => `#${si.invoice.invoice_number || si.invoice.id}`).join(', '); const hasPartial = selectedInvoices.some(si => si.payAmount < parseFloat(si.invoice.total)); const hasOverpay = total > invTotal; let msg = `Record payment of $${total.toFixed(2)} for ${nums}?`; if (hasPartial) msg += '\nāš ļø Contains partial payment(s).'; if (hasOverpay) msg += `\nāš ļø $${(total - invTotal).toFixed(2)} overpayment → customer credit.`; if (!confirm(msg)) return; const submitBtn = document.getElementById('payment-submit-btn'); submitBtn.innerHTML = 'ā³ Processing...'; submitBtn.disabled = true; if (typeof showSpinner === 'function') showSpinner('Recording payment in QBO...'); try { const response = await fetch('/api/qbo/record-payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ invoice_payments: selectedInvoices.map(si => ({ invoice_id: si.invoice.id, amount: si.payAmount })), payment_date: paymentDate, reference_number: reference, payment_method_id: methodSelect.value, payment_method_name: methodSelect.options[methodSelect.selectedIndex]?.text || '', deposit_to_account_id: depositSelect.value, deposit_to_account_name: depositSelect.options[depositSelect.selectedIndex]?.text || '' }) }); const result = await response.json(); if (response.ok) { alert(`āœ… ${result.message}`); closePaymentModal(); if (window.invoiceView) window.invoiceView.loadInvoices(); } else { alert(`āŒ Error: ${result.error}`); } } catch (e) { console.error('Payment error:', e); alert('Network error.'); } finally { submitBtn.innerHTML = 'šŸ’° Record Payment in QBO'; submitBtn.disabled = false; if (typeof hideSpinner === 'function') hideSpinner(); } } // ============================================================ // Expose // ============================================================ window.paymentModal = { open: openPaymentModal, close: closePaymentModal, submit: submitPayment, addById: addInvoiceById, removeInvoice: removeInvoice, updateAmount: updatePayAmount, updateTotal: updateTotal };