/** * expense-modal.js — New Expense Modal * * Dependencies: window.API.accounting.* (api.js) * * Two main modes: * - Create: openExpenseModal({ onSaved }) — leeres Formular * * The modal includes a sub-modal for "Add new vendor" inline. * * Action buttons: "Save & Close" and "Save & New". */ import '../utils/api.js'; // ──────────────────────────────────────────────────────────────────── // State (modul-lokal) // ──────────────────────────────────────────────────────────────────── let modalEl = null; let onSavedCb = null; let vendors = []; // alle Vendors aus Cache let expenseAccounts = []; // alle Expense-Categories aus Cache let paymentAccounts = []; // alle Bank/CreditCard-Accounts let paymentMethods = []; // alle Payment-Methods (live) let selectedVendorId = null; let selectedVendorName = ''; let lineCount = 0; let isSaving = false; // ──────────────────────────────────────────────────────────────────── // Helpers // ──────────────────────────────────────────────────────────────────── function todayISO() { return new Date().toISOString().split('T')[0]; } function escapeHtml(s) { if (s == null) return ''; return String(s) .replace(/&/g, '&').replace(//g, '>') .replace(/"/g, '"').replace(/'/g, '''); } function escapeAttr(s) { return String(s || '') .replace(/&/g, '&').replace(/"/g, '"') .replace(//g, '>'); } function fmtMoney(n) { if (n == null || isNaN(n)) return '$0.00'; return n.toLocaleString('en-US', { style: 'currency', currency: 'USD' }); } // ──────────────────────────────────────────────────────────────────── // Public Entry // ──────────────────────────────────────────────────────────────────── export async function openExpenseModal({ onSaved } = {}) { onSavedCb = onSaved || null; selectedVendorId = null; selectedVendorName = ''; lineCount = 0; isSaving = false; // Lade Stammdaten parallel (alles aus dem Cache → schnell) try { [vendors, expenseAccounts, paymentAccounts, paymentMethods] = await Promise.all([ window.API.accounting.getVendors('', 1000), window.API.accounting.getExpenseAccounts(), window.API.accounting.getPaymentAccounts(), window.API.accounting.getPaymentMethods() ]); // Errors aus dem Backend abfangen for (const [name, data] of [['vendors', vendors], ['expenseAccounts', expenseAccounts], ['paymentAccounts', paymentAccounts], ['paymentMethods', paymentMethods]]) { if (data && data.error) { alert(`Failed to load ${name}: ${data.error}\n\nTry "Sync from QBO" first.`); return; } } } catch (err) { alert('Failed to load expense modal data: ' + err.message); return; } renderModal(); } function closeModal() { if (modalEl) { modalEl.remove(); modalEl = null; } } function resetForm() { selectedVendorId = null; selectedVendorName = ''; document.getElementById('exp-vendor-search').value = ''; document.getElementById('exp-vendor-id').value = ''; document.getElementById('exp-ref-no').value = ''; document.getElementById('exp-memo').value = ''; document.getElementById('exp-date').value = todayISO(); document.getElementById('exp-lines-tbody').innerHTML = ''; lineCount = 0; addLine(); updateTotal(); } // ──────────────────────────────────────────────────────────────────── // Render // ──────────────────────────────────────────────────────────────────── function renderModal() { closeModal(); // safety const html = ` `; document.body.insertAdjacentHTML('beforeend', html); modalEl = document.getElementById('expense-modal'); // Initial: eine leere Linie addLine(); updateTotal(); } // ──────────────────────────────────────────────────────────────────── // Vendor Search // ──────────────────────────────────────────────────────────────────── function onVendorInput() { const inputEl = document.getElementById('exp-vendor-search'); const dropdownEl = document.getElementById('exp-vendor-dropdown'); const q = (inputEl.value || '').trim().toLowerCase(); // Wenn Suche != aktuell ausgewählter Vendor → Selection invalidieren if (selectedVendorName && inputEl.value !== selectedVendorName) { selectedVendorId = null; selectedVendorName = ''; document.getElementById('exp-vendor-id').value = ''; } // Filter Vendors clientseitig (wir haben sie alle im Cache) const filtered = q ? vendors.filter(v => v.displayName.toLowerCase().includes(q)).slice(0, 50) : vendors.slice(0, 50); let html = ''; if (q && !filtered.some(v => v.displayName.toLowerCase() === q)) { // "Add new" Option oben html += `
+ Add new vendor: ${escapeHtml(inputEl.value)}
`; } if (filtered.length === 0 && !q) { html += `
Type to search…
`; } else { html += filtered.map(v => `
${escapeHtml(v.displayName)}
${v.email ? `
${escapeHtml(v.email)}
` : ''}
`).join(''); } dropdownEl.innerHTML = html; dropdownEl.classList.remove('hidden'); // Auto-close on outside click if (!dropdownEl._outsideHandlerInstalled) { dropdownEl._outsideHandlerInstalled = true; document.addEventListener('click', (e) => { if (!dropdownEl.contains(e.target) && e.target !== inputEl) { dropdownEl.classList.add('hidden'); } }); } } function selectVendor(id, name) { selectedVendorId = id; selectedVendorName = name; document.getElementById('exp-vendor-search').value = name; document.getElementById('exp-vendor-id').value = id; document.getElementById('exp-vendor-dropdown').classList.add('hidden'); } // ──────────────────────────────────────────────────────────────────── // Add New Vendor (sub-Modal) // ──────────────────────────────────────────────────────────────────── function openAddVendor(prefilledName = '') { document.getElementById('exp-vendor-dropdown').classList.add('hidden'); const html = `

+ New Vendor

Address (optional)

`; document.body.insertAdjacentHTML('beforeend', html); setTimeout(() => document.getElementById('ven-name').focus(), 50); } function closeAddVendor() { const m = document.getElementById('vendor-add-modal'); if (m) m.remove(); } async function saveAddVendor() { const name = document.getElementById('ven-name').value.trim(); if (!name) { showVenError('Name is required'); document.getElementById('ven-name').focus(); return; } const data = { name, email: document.getElementById('ven-email').value.trim() || null, phone: document.getElementById('ven-phone').value.trim() || null, notes: document.getElementById('ven-notes').value.trim() || null, address: { line1: document.getElementById('ven-line1').value.trim() || null, line2: document.getElementById('ven-line2').value.trim() || null, city: document.getElementById('ven-city').value.trim() || null, state: document.getElementById('ven-state').value.trim() || null, zip: document.getElementById('ven-zip').value.trim() || null, country: document.getElementById('ven-country').value.trim() || null } }; const btn = document.getElementById('ven-save-btn'); btn.disabled = true; btn.textContent = 'Saving…'; try { const result = await window.API.accounting.createVendor(data); if (result.error) { showVenError(result.error); btn.disabled = false; btn.textContent = 'Save Vendor'; return; } // Vendor in lokale Liste aufnehmen, sofort selektieren if (!result.existed) { vendors.push({ id: result.id, displayName: result.displayName, companyName: result.displayName, email: result.email, phone: result.phone, active: true }); // Liste alphabetisch halten vendors.sort((a, b) => a.displayName.localeCompare(b.displayName)); } selectVendor(result.id, result.displayName); closeAddVendor(); } catch (err) { showVenError(err.message || 'Failed to save vendor'); btn.disabled = false; btn.textContent = 'Save Vendor'; } } function showVenError(msg) { const el = document.getElementById('ven-error'); el.textContent = msg; el.classList.remove('hidden'); } // ──────────────────────────────────────────────────────────────────── // Lines // ──────────────────────────────────────────────────────────────────── function addLine() { lineCount++; const tbody = document.getElementById('exp-lines-tbody'); const tr = document.createElement('tr'); tr.className = 'border-t'; tr.dataset.lineIndex = lineCount; tr.innerHTML = ` ${lineCount} `; tbody.appendChild(tr); } function removeLine(btn) { const tr = btn.closest('tr'); if (tr) { tr.remove(); // Re-number visible lines const rows = document.querySelectorAll('#exp-lines-tbody tr'); rows.forEach((r, i) => { r.firstElementChild.textContent = i + 1; }); updateTotal(); } } function clearLines() { document.getElementById('exp-lines-tbody').innerHTML = ''; lineCount = 0; addLine(); updateTotal(); } function getLines() { const rows = document.querySelectorAll('#exp-lines-tbody tr'); return Array.from(rows).map(r => ({ accountId: r.querySelector('.exp-line-account').value, description: r.querySelector('.exp-line-desc').value.trim() || null, amount: parseFloat(r.querySelector('.exp-line-amount').value) })); } function updateTotal() { const total = getLines() .filter(l => isFinite(l.amount)) .reduce((sum, l) => sum + l.amount, 0); document.getElementById('exp-total').textContent = fmtMoney(total); } // ──────────────────────────────────────────────────────────────────── // Save // ──────────────────────────────────────────────────────────────────── async function save(mode) { if (isSaving) return; hideError(); // Validate if (!selectedVendorId) { return showError('Please select or add a vendor.'); } const paymentAccountId = document.getElementById('exp-payment-account').value; if (!paymentAccountId) { return showError('Please select a payment account.'); } const txnDate = document.getElementById('exp-date').value; if (!txnDate) { return showError('Please enter a date.'); } const lines = getLines().filter(l => l.accountId && isFinite(l.amount) && l.amount > 0); if (lines.length === 0) { return showError('At least one line with category and positive amount is required.'); } // Auch ungültige Lines flaggen const invalidLines = getLines().filter(l => (l.accountId && (!isFinite(l.amount) || l.amount <= 0)) || (!l.accountId && isFinite(l.amount) && l.amount > 0) ); if (invalidLines.length > 0) { return showError('Some lines have a category but no amount, or vice versa. Please complete or remove them.'); } const payload = { vendorId: selectedVendorId, paymentAccountId, txnDate, paymentMethodId: document.getElementById('exp-payment-method').value || null, refNo: document.getElementById('exp-ref-no').value.trim() || null, memo: document.getElementById('exp-memo').value.trim() || null, lines }; isSaving = true; setButtonsDisabled(true); try { const result = await window.API.accounting.createExpense(payload); if (result.error) { showError(result.error); return; } if (typeof onSavedCb === 'function') { try { onSavedCb(result); } catch (e) { console.warn('onSaved cb threw:', e); } } if (mode === 'close') { closeModal(); } else if (mode === 'new') { // Form leeren, Modal offen lassen resetForm(); // kleiner Toast showToast(`✅ Saved Purchase #${result.id} — ${fmtMoney(result.totalAmt)}`); } } catch (err) { showError(err.message || 'Save failed'); } finally { isSaving = false; setButtonsDisabled(false); } } function setButtonsDisabled(disabled) { const a = document.getElementById('exp-save-new-btn'); const b = document.getElementById('exp-save-close-btn'); if (a) a.disabled = disabled; if (b) b.disabled = disabled; if (a) a.textContent = disabled ? 'Saving…' : 'Save & New'; if (b) b.textContent = disabled ? 'Saving…' : 'Save & Close'; } function showError(msg) { const el = document.getElementById('exp-error'); if (el) { el.textContent = msg; el.classList.remove('hidden'); } } function hideError() { const el = document.getElementById('exp-error'); if (el) el.classList.add('hidden'); } function showToast(msg) { const id = 'exp-toast-' + Date.now(); const div = document.createElement('div'); div.id = id; div.className = 'fixed bottom-6 right-6 bg-green-600 text-white px-4 py-2 rounded-md shadow-lg z-[70] text-sm'; div.textContent = msg; document.body.appendChild(div); setTimeout(() => div.remove(), 3000); } // ──────────────────────────────────────────────────────────────────── // Expose // ──────────────────────────────────────────────────────────────────── window.expenseModal = { open: openExpenseModal, close: closeModal, onVendorInput, selectVendor, openAddVendor, closeAddVendor, saveAddVendor, addLine, removeLine, clearLines, updateTotal, save };