This commit is contained in:
2026-05-07 10:06:14 -05:00
parent e01c5367bc
commit 5b3da47d87
6 changed files with 1414 additions and 226 deletions

View File

@@ -127,6 +127,11 @@
<div id="accounting-register-controls"></div> <div id="accounting-register-controls"></div>
</section> </section>
<section class="mb-6">
<h3 class="text-md font-semibold text-gray-700 mb-3">Expenses</h3>
<div id="accounting-expenses"></div>
</section>
<section class="mb-6"> <section class="mb-6">
<h3 class="text-md font-semibold text-gray-700 mb-3">Reports</h3> <h3 class="text-md font-semibold text-gray-700 mb-3">Reports</h3>
<div id="accounting-reports"></div> <div id="accounting-reports"></div>

View File

@@ -0,0 +1,649 @@
/**
* 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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
function escapeAttr(s) {
return String(s || '')
.replace(/&/g, '&amp;').replace(/"/g, '&quot;')
.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
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 = `
<div id="expense-modal" class="modal fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full flex items-start justify-center z-50">
<div class="relative mx-auto p-6 border w-full max-w-5xl shadow-lg rounded-lg bg-white my-8">
<div class="flex justify-between items-center mb-5">
<h3 class="text-2xl font-bold text-gray-900">📝 New Expense</h3>
<button onclick="window.expenseModal.close()" class="text-gray-400 hover:text-gray-600">
<svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
</svg>
</button>
</div>
<!-- Header Row -->
<div class="grid grid-cols-3 gap-4 mb-4">
<div class="relative">
<label class="block text-sm font-medium text-gray-700 mb-1">Payee (Vendor) *</label>
<input type="text" id="exp-vendor-search" autocomplete="off"
oninput="window.expenseModal.onVendorInput()"
onfocus="window.expenseModal.onVendorInput()"
placeholder="Type to search…"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500">
<input type="hidden" id="exp-vendor-id">
<div id="exp-vendor-dropdown"
class="hidden absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-72 overflow-auto"></div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Payment Account *</label>
<select id="exp-payment-account" class="w-full px-3 py-2 border border-gray-300 rounded-md">
<option value="">— Select —</option>
${paymentAccounts.map(a => `
<option value="${a.id}" data-type="${escapeAttr(a.accountType)}">
${escapeHtml(a.name)} (${escapeHtml(a.accountType)})
</option>`).join('')}
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Date *</label>
<input type="date" id="exp-date" value="${todayISO()}"
class="w-full px-3 py-2 border border-gray-300 rounded-md">
</div>
</div>
<div class="grid grid-cols-3 gap-4 mb-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Payment Method</label>
<select id="exp-payment-method" class="w-full px-3 py-2 border border-gray-300 rounded-md">
<option value="">— None —</option>
${paymentMethods.map(m => `<option value="${m.id}">${escapeHtml(m.name)}</option>`).join('')}
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Ref No.</label>
<input type="text" id="exp-ref-no" maxlength="21"
class="w-full px-3 py-2 border border-gray-300 rounded-md"
placeholder="e.g. invoice number, check no.">
</div>
<div></div>
</div>
<!-- Line Items -->
<div class="mb-4 border border-gray-200 rounded-lg overflow-hidden">
<div class="bg-gray-50 px-3 py-2 border-b text-sm font-medium text-gray-700 flex items-center justify-between">
<span>Category Lines</span>
<div class="flex items-center gap-2">
<button type="button" onclick="window.expenseModal.addLine()"
class="px-3 py-1 bg-green-600 hover:bg-green-700 text-white rounded text-xs font-medium">
+ Add Line
</button>
<button type="button" onclick="window.expenseModal.clearLines()"
class="px-3 py-1 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded text-xs">
Clear
</button>
</div>
</div>
<table class="min-w-full text-sm">
<thead class="bg-gray-50">
<tr>
<th class="px-3 py-1.5 text-left font-medium text-gray-700">#</th>
<th class="px-3 py-1.5 text-left font-medium text-gray-700">Category *</th>
<th class="px-3 py-1.5 text-left font-medium text-gray-700">Description</th>
<th class="px-3 py-1.5 text-right font-medium text-gray-700">Amount *</th>
<th class="px-3 py-1.5"></th>
</tr>
</thead>
<tbody id="exp-lines-tbody"></tbody>
<tfoot class="bg-gray-50 border-t">
<tr>
<td colspan="3" class="px-3 py-2 text-right font-medium text-gray-700">Total:</td>
<td class="px-3 py-2 text-right font-bold text-gray-900" id="exp-total">$0.00</td>
<td></td>
</tr>
</tfoot>
</table>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-1">Memo</label>
<textarea id="exp-memo" rows="2"
class="w-full px-3 py-2 border border-gray-300 rounded-md"
placeholder="Internal note (visible in QBO)"></textarea>
</div>
<div id="exp-error" class="hidden mb-4 p-3 bg-red-50 border border-red-200 rounded text-sm text-red-700"></div>
<div class="flex justify-end gap-3">
<button type="button" onclick="window.expenseModal.close()"
class="px-5 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-md">
Cancel
</button>
<button type="button" id="exp-save-new-btn" onclick="window.expenseModal.save('new')"
class="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md font-medium">
Save &amp; New
</button>
<button type="button" id="exp-save-close-btn" onclick="window.expenseModal.save('close')"
class="px-5 py-2 bg-green-600 hover:bg-green-700 text-white rounded-md font-medium">
Save &amp; Close
</button>
</div>
</div>
</div>`;
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 += `
<div class="px-3 py-2 cursor-pointer bg-blue-50 hover:bg-blue-100 border-b border-blue-200 text-blue-700 font-medium"
onclick="window.expenseModal.openAddVendor('${escapeAttr(inputEl.value)}')">
+ Add new vendor: <strong>${escapeHtml(inputEl.value)}</strong>
</div>`;
}
if (filtered.length === 0 && !q) {
html += `<div class="px-3 py-2 text-gray-500 text-sm">Type to search…</div>`;
} else {
html += filtered.map(v => `
<div class="px-3 py-2 cursor-pointer hover:bg-gray-100 text-sm"
onclick="window.expenseModal.selectVendor('${v.id}', '${escapeAttr(v.displayName)}')">
<div class="font-medium text-gray-900">${escapeHtml(v.displayName)}</div>
${v.email ? `<div class="text-xs text-gray-500">${escapeHtml(v.email)}</div>` : ''}
</div>`).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 = `
<div id="vendor-add-modal" class="fixed inset-0 bg-gray-700 bg-opacity-60 z-[60] flex items-start justify-center overflow-y-auto">
<div class="relative mx-auto p-6 border w-full max-w-2xl shadow-lg rounded-lg bg-white my-8">
<div class="flex justify-between items-center mb-4">
<h3 class="text-xl font-bold text-gray-900">+ New Vendor</h3>
<button onclick="window.expenseModal.closeAddVendor()" class="text-gray-400 hover:text-gray-600">
<svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
</svg>
</button>
</div>
<div class="space-y-3">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Name *</label>
<input type="text" id="ven-name" value="${escapeAttr(prefilledName)}"
class="w-full px-3 py-2 border border-gray-300 rounded-md">
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Email</label>
<input type="email" id="ven-email" class="w-full px-3 py-2 border border-gray-300 rounded-md">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Phone</label>
<input type="tel" id="ven-phone" class="w-full px-3 py-2 border border-gray-300 rounded-md">
</div>
</div>
<div class="border-t pt-3 mt-3">
<p class="text-xs font-medium text-gray-500 uppercase mb-2">Address (optional)</p>
<div class="space-y-2">
<input type="text" id="ven-line1" placeholder="Street address 1" class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
<input type="text" id="ven-line2" placeholder="Street address 2" class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
<div class="grid grid-cols-3 gap-2">
<input type="text" id="ven-city" placeholder="City" class="px-3 py-2 border border-gray-300 rounded-md text-sm">
<input type="text" id="ven-state" placeholder="State" class="px-3 py-2 border border-gray-300 rounded-md text-sm">
<input type="text" id="ven-zip" placeholder="ZIP" class="px-3 py-2 border border-gray-300 rounded-md text-sm">
</div>
<input type="text" id="ven-country" placeholder="Country (optional)" class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm">
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Notes</label>
<textarea id="ven-notes" rows="2" class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm"></textarea>
</div>
<div id="ven-error" class="hidden p-2 bg-red-50 border border-red-200 rounded text-sm text-red-700"></div>
</div>
<div class="flex justify-end gap-3 mt-5">
<button onclick="window.expenseModal.closeAddVendor()"
class="px-5 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-md">Cancel</button>
<button id="ven-save-btn" onclick="window.expenseModal.saveAddVendor()"
class="px-5 py-2 bg-green-600 hover:bg-green-700 text-white rounded-md font-medium">
Save Vendor
</button>
</div>
</div>
</div>`;
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 = `
<td class="px-3 py-1.5 text-gray-500 text-xs">${lineCount}</td>
<td class="px-3 py-1.5">
<select class="exp-line-account w-full px-2 py-1 border border-gray-300 rounded-md text-sm">
<option value="">— Select category —</option>
${expenseAccounts.map(a => `
<option value="${a.id}" title="${escapeAttr(a.fullyQualifiedName || a.name)}">
${escapeHtml(a.fullyQualifiedName || a.name)}
</option>`).join('')}
</select>
</td>
<td class="px-3 py-1.5">
<input type="text" class="exp-line-desc w-full px-2 py-1 border border-gray-300 rounded-md text-sm" placeholder="(optional)">
</td>
<td class="px-3 py-1.5">
<input type="number" step="0.01" min="0" class="exp-line-amount w-32 px-2 py-1 border border-gray-300 rounded-md text-sm text-right"
oninput="window.expenseModal.updateTotal()">
</td>
<td class="px-3 py-1.5 text-center">
<button type="button" onclick="window.expenseModal.removeLine(this)"
class="text-red-500 hover:text-red-700 text-lg leading-none">×</button>
</td>`;
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
};

View File

@@ -116,8 +116,8 @@ const API = {
auth: () => window.location.href = '/auth/qbo' auth: () => window.location.href = '/auth/qbo'
}, },
// Accounting API (Phase 1 — read-only)
accounting: { accounting: {
// Phase 1
getAccounts: (type = null, activeOnly = true) => { getAccounts: (type = null, activeOnly = true) => {
const params = new URLSearchParams(); const params = new URLSearchParams();
if (type) params.set('type', type); if (type) params.set('type', type);
@@ -125,7 +125,6 @@ const API = {
const qs = params.toString(); const qs = params.toString();
return fetch('/api/accounting/accounts' + (qs ? '?' + qs : '')).then(r => r.json()); return fetch('/api/accounting/accounts' + (qs ? '?' + qs : '')).then(r => r.json());
}, },
syncAccounts: () => fetch('/api/accounting/sync-accounts', { method: 'POST' }).then(r => r.json()),
getRegister: (accountId, startDate, endDate) => { getRegister: (accountId, startDate, endDate) => {
const params = new URLSearchParams({ accountId }); const params = new URLSearchParams({ accountId });
if (startDate) params.set('startDate', startDate); if (startDate) params.set('startDate', startDate);
@@ -139,6 +138,41 @@ const API = {
getBalanceSheet: (asOfDate, accountingMethod = 'Accrual') => { getBalanceSheet: (asOfDate, accountingMethod = 'Accrual') => {
const params = new URLSearchParams({ asOfDate, accountingMethod }); const params = new URLSearchParams({ asOfDate, accountingMethod });
return fetch('/api/accounting/reports/balance-sheet?' + params.toString()).then(r => r.json()); return fetch('/api/accounting/reports/balance-sheet?' + params.toString()).then(r => r.json());
},
// Phase 2 Lieferung 1 — Sync + Cache-Reads
syncAccounts: () => fetch('/api/accounting/sync-accounts', { method: 'POST' }).then(r => r.json()),
syncVendors: () => fetch('/api/accounting/sync-vendors', { method: 'POST' }).then(r => r.json()),
getSyncStatus: () => fetch('/api/accounting/sync-status').then(r => r.json()),
getVendors: (search = '', limit = 200) => {
const params = new URLSearchParams();
if (search) params.set('search', search);
if (limit) params.set('limit', String(limit));
const qs = params.toString();
return fetch('/api/accounting/vendors' + (qs ? '?' + qs : '')).then(r => r.json());
},
getExpenseAccounts: () => fetch('/api/accounting/expense-accounts').then(r => r.json()),
getPaymentAccounts: () => fetch('/api/accounting/payment-accounts').then(r => r.json()),
getPaymentMethods: () => fetch('/api/accounting/payment-methods').then(r => r.json()),
// Phase 2 Lieferung 2 — Mutations + List
createVendor: (data) => fetch('/api/accounting/vendors', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}).then(r => r.json()),
createExpense: (data) => fetch('/api/accounting/expenses', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}).then(r => r.json()),
listExpenses: (startDate, endDate, onlyMine = false) => {
const params = new URLSearchParams({ startDate, endDate });
if (onlyMine) params.set('onlyMine', 'true');
return fetch('/api/accounting/expenses?' + params.toString()).then(r => r.json());
} }
}, },

View File

@@ -1,24 +1,24 @@
/** /**
* accounting-view.js — Phase 1, read-only * accounting-view.js
* *
* Drei Bereiche: * Phase 1: Accounts Overview, Register, Reports
* 1) Accounts Overview — Cards mit Bank- und Credit-Card-Balances * Phase 2 Lieferung 2: Expenses-Section + Auto-Sync-on-First-Open-of-Day
* 2) Register — read-only Liste der Transaktionen für ein Konto
* 3) Reports — Profit & Loss + Balance Sheet
*/ */
import '../utils/api.js'; // ← NEU
import '../utils/api.js';
import { formatDate } from '../utils/helpers.js'; import { formatDate } from '../utils/helpers.js';
import { openExpenseModal } from '../modals/expense-modal.js';
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
// State (modul-lokal) // State (modul-lokal)
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
let allAccounts = []; // alle aktiven Accounts (gesamt, für Dropdown) let allAccounts = [];
let registerAccountId = null; // aktuell ausgewählter Account fürs Register let registerAccountId = null;
let registerStartDate = null; let registerStartDate = null;
let registerEndDate = null; let registerEndDate = null;
let registerLoadSeq = 0;
// Reports
let plStartDate = null; let plStartDate = null;
let plEndDate = null; let plEndDate = null;
let plAccountingMethod = 'Accrual'; let plAccountingMethod = 'Accrual';
@@ -26,7 +26,13 @@ let plAccountingMethod = 'Accrual';
let bsAsOfDate = null; let bsAsOfDate = null;
let bsAccountingMethod = 'Accrual'; let bsAccountingMethod = 'Accrual';
let registerLoadSeq = 0; let expStartDate = null;
let expEndDate = null;
let expOnlyMine = false;
// Auto-Sync nur einmal pro View-Mount
let autoSyncDoneThisOpen = false;
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
// Helpers // Helpers
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
@@ -34,22 +40,16 @@ let registerLoadSeq = 0;
function fmtMoney(n) { function fmtMoney(n) {
if (n == null || isNaN(n)) return ''; if (n == null || isNaN(n)) return '';
return n.toLocaleString('en-US', { return n.toLocaleString('en-US', {
style: 'currency', style: 'currency', currency: 'USD',
currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2
minimumFractionDigits: 2,
maximumFractionDigits: 2
}); });
} }
function todayISO() { function todayISO() { return new Date().toISOString().split('T')[0]; }
return new Date().toISOString().split('T')[0];
}
function firstOfMonthISO() { function firstOfMonthISO() {
const d = new Date(); const d = new Date();
return new Date(d.getFullYear(), d.getMonth(), 1).toISOString().split('T')[0]; return new Date(d.getFullYear(), d.getMonth(), 1).toISOString().split('T')[0];
} }
function firstOfYearISO() { function firstOfYearISO() {
const d = new Date(); const d = new Date();
return new Date(d.getFullYear(), 0, 1).toISOString().split('T')[0]; return new Date(d.getFullYear(), 0, 1).toISOString().split('T')[0];
@@ -58,11 +58,8 @@ function firstOfYearISO() {
function escapeHtml(s) { function escapeHtml(s) {
if (s == null) return ''; if (s == null) return '';
return String(s) return String(s)
.replace(/&/g, '&amp;') .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/</g, '&lt;') .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
} }
function showError(slotId, message) { function showError(slotId, message) {
@@ -89,7 +86,7 @@ function showLoading(slotId, message = 'Loading…') {
} }
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
// Toolbar (top-of-tab heading + sync button) // Toolbar
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
export function injectToolbar() { export function injectToolbar() {
@@ -98,8 +95,13 @@ export function injectToolbar() {
c.innerHTML = ` c.innerHTML = `
<div class="flex items-center gap-3 mb-4 p-4 bg-white rounded-lg shadow-sm border border-gray-200"> <div class="flex items-center gap-3 mb-4 p-4 bg-white rounded-lg shadow-sm border border-gray-200">
<h2 class="text-lg font-semibold text-gray-800">Accounting</h2> <h2 class="text-lg font-semibold text-gray-800">Accounting</h2>
<span class="text-sm text-gray-400">read-only</span> <span class="text-sm text-gray-400">read-only registers · expense entry</span>
<div class="ml-auto flex items-center gap-2"> <div class="ml-auto flex items-center gap-2">
<span id="accounting-sync-status" class="text-xs text-gray-500"></span>
<button onclick="window.accountingView.manualSync()"
class="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-md text-sm font-medium border border-gray-300">
🔄 Sync from QBO
</button>
<button onclick="window.accountingView.refreshAll()" <button onclick="window.accountingView.refreshAll()"
class="px-3 py-1.5 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700"> class="px-3 py-1.5 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700">
↻ Refresh ↻ Refresh
@@ -108,6 +110,71 @@ export function injectToolbar() {
</div>`; </div>`;
} }
// ────────────────────────────────────────────────────────────────────
// Auto-Sync beim ersten Öffnen des Tages
// ────────────────────────────────────────────────────────────────────
async function maybeAutoSyncCaches() {
if (autoSyncDoneThisOpen) return;
autoSyncDoneThisOpen = true;
try {
const status = await window.API.accounting.getSyncStatus();
const accStale = status.accounts && status.accounts.staleToday;
const venStale = status.vendors && status.vendors.staleToday;
if (!accStale && !venStale) {
updateSyncStatusBadge(status);
return;
}
const syncBadge = document.getElementById('accounting-sync-status');
if (syncBadge) syncBadge.textContent = '🔄 Syncing caches…';
const tasks = [];
if (accStale) tasks.push(window.API.accounting.syncAccounts());
if (venStale) tasks.push(window.API.accounting.syncVendors());
await Promise.all(tasks);
const newStatus = await window.API.accounting.getSyncStatus();
updateSyncStatusBadge(newStatus);
console.log('✅ Auto-synced QBO caches (first open of day)');
} catch (err) {
console.warn('Auto-sync failed:', err.message);
const syncBadge = document.getElementById('accounting-sync-status');
if (syncBadge) syncBadge.textContent = '⚠️ Sync failed';
}
}
export async function manualSync() {
const syncBadge = document.getElementById('accounting-sync-status');
if (syncBadge) syncBadge.textContent = '🔄 Syncing…';
try {
await Promise.all([
window.API.accounting.syncAccounts(),
window.API.accounting.syncVendors()
]);
const status = await window.API.accounting.getSyncStatus();
updateSyncStatusBadge(status);
} catch (err) {
if (syncBadge) syncBadge.textContent = '⚠️ Sync failed';
alert('Sync failed: ' + err.message);
}
}
function updateSyncStatusBadge(status) {
const el = document.getElementById('accounting-sync-status');
if (!el) return;
const a = status.accounts;
const v = status.vendors;
if (a?.last_synced_at && v?.last_synced_at) {
const aTime = new Date(a.last_synced_at).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
el.innerHTML = `Synced @ ${aTime} · ${a.last_sync_count} accts · ${v.last_sync_count} vendors`;
} else {
el.textContent = 'Not yet synced';
}
}
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
// Accounts Overview // Accounts Overview
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
@@ -117,37 +184,20 @@ export async function loadAccountsOverview() {
showLoading(slot, 'Loading accounts from QBO…'); showLoading(slot, 'Loading accounts from QBO…');
try { try {
// Wir laden alle aktiven Accounts in einem Rutsch und filtern client-seitig.
const accounts = await window.API.accounting.getAccounts(null, true); const accounts = await window.API.accounting.getAccounts(null, true);
if (accounts.error) return showError(slot, accounts.error);
if (accounts.error) {
showError(slot, accounts.error);
return;
}
allAccounts = accounts; allAccounts = accounts;
const cards = accounts.filter(a => a.accountType === 'Bank' || a.accountType === 'Credit Card');
// Bank/Credit Card Cards rendern
const cards = accounts.filter(a =>
a.accountType === 'Bank' || a.accountType === 'Credit Card'
);
const el = document.getElementById(slot); const el = document.getElementById(slot);
if (!cards.length) { if (!cards.length) {
el.innerHTML = ` el.innerHTML = `<div class="p-4 bg-gray-50 border border-gray-200 rounded-lg text-gray-600">No bank or credit card accounts found.</div>`;
<div class="p-4 bg-gray-50 border border-gray-200 rounded-lg text-gray-600">
No bank or credit card accounts found in QBO.
</div>`;
} else { } else {
el.innerHTML = ` el.innerHTML = `<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">${cards.map(renderAccountCard).join('')}</div>`;
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
${cards.map(a => renderAccountCard(a)).join('')}
</div>`;
} }
// Register-Dropdown füttern (nur Bank + Credit Card)
populateRegisterAccountDropdown(cards); populateRegisterAccountDropdown(cards);
} catch (err) { } catch (err) {
console.error('Accounts load failed:', err); console.error('Accounts load failed:', err);
showError(slot, err.message || 'Failed to load accounts'); showError(slot, err.message || 'Failed to load accounts');
@@ -159,9 +209,7 @@ function renderAccountCard(a) {
const accent = isBank ? 'border-blue-200 bg-blue-50' : 'border-purple-200 bg-purple-50'; const accent = isBank ? 'border-blue-200 bg-blue-50' : 'border-purple-200 bg-purple-50';
const label = isBank ? 'Bank' : 'Credit Card'; const label = isBank ? 'Bank' : 'Credit Card';
const labelColor = isBank ? 'text-blue-700' : 'text-purple-700'; const labelColor = isBank ? 'text-blue-700' : 'text-purple-700';
const bal = a.currentBalance; const balText = a.currentBalance != null ? fmtMoney(a.currentBalance) : '—';
const balText = bal != null ? fmtMoney(bal) : '—';
// Bei Credit Cards ist ein positiver CurrentBalance i.d.R. eine Schuld; nur Hinweis, keine Vorzeichenakrobatik.
return ` return `
<div class="rounded-lg border ${accent} p-4 cursor-pointer hover:shadow-md transition" <div class="rounded-lg border ${accent} p-4 cursor-pointer hover:shadow-md transition"
onclick="window.accountingView.selectRegisterAccount('${a.id}')"> onclick="window.accountingView.selectRegisterAccount('${a.id}')">
@@ -172,8 +220,7 @@ function renderAccountCard(a) {
<div class="text-base font-semibold text-gray-900 mb-2">${escapeHtml(a.name)}</div> <div class="text-base font-semibold text-gray-900 mb-2">${escapeHtml(a.name)}</div>
<div class="text-2xl font-bold text-gray-900">${balText}</div> <div class="text-2xl font-bold text-gray-900">${balText}</div>
${a.accountSubType ? `<div class="text-xs text-gray-500 mt-1">${escapeHtml(a.accountSubType)}</div>` : ''} ${a.accountSubType ? `<div class="text-xs text-gray-500 mt-1">${escapeHtml(a.accountSubType)}</div>` : ''}
</div> </div>`;
`;
} }
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
@@ -183,22 +230,15 @@ function renderAccountCard(a) {
function populateRegisterAccountDropdown(bankCardAccounts) { function populateRegisterAccountDropdown(bankCardAccounts) {
const sel = document.getElementById('reg-account'); const sel = document.getElementById('reg-account');
if (!sel) return; if (!sel) return;
const current = registerAccountId || sel.value; const current = registerAccountId || sel.value;
sel.innerHTML = `<option value="">— Select account —</option>` + sel.innerHTML = `<option value="">— Select account —</option>` +
bankCardAccounts.map(a => bankCardAccounts.map(a => `<option value="${a.id}">${escapeHtml(a.name)} (${a.accountType})</option>`).join('');
`<option value="${a.id}">${escapeHtml(a.name)} (${a.accountType})</option>` if (current && bankCardAccounts.find(a => a.id === current)) sel.value = current;
).join('');
if (current && bankCardAccounts.find(a => a.id === current)) {
sel.value = current;
}
} }
export function injectRegisterControls() { export function injectRegisterControls() {
const c = document.getElementById('accounting-register-controls'); const c = document.getElementById('accounting-register-controls');
if (!c) return; if (!c) return;
if (!registerStartDate) registerStartDate = firstOfMonthISO(); if (!registerStartDate) registerStartDate = firstOfMonthISO();
if (!registerEndDate) registerEndDate = todayISO(); if (!registerEndDate) registerEndDate = todayISO();
@@ -212,13 +252,11 @@ export function injectRegisterControls() {
</div> </div>
<div> <div>
<label class="block text-xs font-medium text-gray-700 mb-1">Start Date</label> <label class="block text-xs font-medium text-gray-700 mb-1">Start Date</label>
<input type="date" id="reg-start" value="${registerStartDate}" <input type="date" id="reg-start" value="${registerStartDate}" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm">
class="px-3 py-1.5 border border-gray-300 rounded-md text-sm">
</div> </div>
<div> <div>
<label class="block text-xs font-medium text-gray-700 mb-1">End Date</label> <label class="block text-xs font-medium text-gray-700 mb-1">End Date</label>
<input type="date" id="reg-end" value="${registerEndDate}" <input type="date" id="reg-end" value="${registerEndDate}" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm">
class="px-3 py-1.5 border border-gray-300 rounded-md text-sm">
</div> </div>
<button onclick="window.accountingView.loadRegister()" <button onclick="window.accountingView.loadRegister()"
class="px-4 py-1.5 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700"> class="px-4 py-1.5 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700">
@@ -252,22 +290,12 @@ export async function loadRegister() {
const slot = 'accounting-register-table'; const slot = 'accounting-register-table';
showLoading(slot, 'Loading register from QBO…'); showLoading(slot, 'Loading register from QBO…');
const mySeq = ++registerLoadSeq;
const mySeq = ++registerLoadSeq; // ← merken, welcher Call das ist
try { try {
const result = await window.API.accounting.getRegister( const result = await window.API.accounting.getRegister(registerAccountId, registerStartDate, registerEndDate);
registerAccountId, registerStartDate, registerEndDate
);
// Wenn inzwischen ein neuerer Call gestartet wurde → Result verwerfen
if (mySeq !== registerLoadSeq) return; if (mySeq !== registerLoadSeq) return;
if (result.error) return showError(slot, result.error);
if (result.error) {
showError(slot, result.error);
return;
}
renderRegisterTable(result); renderRegisterTable(result);
} catch (err) { } catch (err) {
if (mySeq !== registerLoadSeq) return; if (mySeq !== registerLoadSeq) return;
@@ -280,28 +308,15 @@ function renderRegisterTable(result) {
const el = document.getElementById('accounting-register-table'); const el = document.getElementById('accounting-register-table');
if (!el) return; if (!el) return;
let rows = result.rows || []; let rows = (result.rows || []).slice().sort((a, b) => (b.date || '').localeCompare(a.date || ''));
const meta = result.meta || {}; const meta = result.meta || {};
// ── Punkt 1: neueste Einträge oben ──
rows = rows.slice().sort((a, b) => {
const da = a.date || '';
const db = b.date || '';
if (db !== da) return db.localeCompare(da);
return 0;
});
if (!rows.length) { if (!rows.length) {
el.innerHTML = ` el.innerHTML = `<div class="p-4 bg-gray-50 border border-gray-200 rounded-lg text-gray-600">No transactions in selected range.</div>`;
<div class="p-4 bg-gray-50 border border-gray-200 rounded-lg text-gray-600">
No transactions in selected range.
</div>`;
return; return;
} }
const tbody = rows.map(r => renderRegisterRow(r)).join(''); const tbody = rows.map(renderRegisterRow).join('');
// ── Punkt 5: dynamische Anzahl ──
el.innerHTML = ` el.innerHTML = `
<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden"> <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
<div class="px-4 py-2 border-b bg-gray-50 flex items-center justify-between"> <div class="px-4 py-2 border-b bg-gray-50 flex items-center justify-between">
@@ -335,15 +350,14 @@ function renderRegisterTable(result) {
function renderRegisterRow(r) { function renderRegisterRow(r) {
const isSplit = r.splitAccount === '-Split-'; const isSplit = r.splitAccount === '-Split-';
const splitCellContent = isSplit ? renderSplitCell(r) : escapeHtml(r.splitAccount || ''); const splitContent = isSplit ? renderSplitCell(r) : escapeHtml(r.splitAccount || '');
return ` return `
<tr class="border-t hover:bg-gray-50 align-top"> <tr class="border-t hover:bg-gray-50 align-top">
<td class="px-3 py-2 text-sm whitespace-nowrap">${escapeHtml(r.date || '')}</td> <td class="px-3 py-2 text-sm whitespace-nowrap">${escapeHtml(r.date || '')}</td>
<td class="px-3 py-2 text-sm">${escapeHtml(r.type || '')}</td> <td class="px-3 py-2 text-sm">${escapeHtml(r.type || '')}</td>
<td class="px-3 py-2 text-sm">${escapeHtml(r.docNum || '')}</td> <td class="px-3 py-2 text-sm">${escapeHtml(r.docNum || '')}</td>
<td class="px-3 py-2 text-sm">${escapeHtml(r.payee || '')}</td> <td class="px-3 py-2 text-sm">${escapeHtml(r.payee || '')}</td>
<td class="px-3 py-2 text-sm text-gray-600">${splitCellContent}</td> <td class="px-3 py-2 text-sm text-gray-600">${splitContent}</td>
<td class="px-3 py-2 text-sm text-gray-500">${escapeHtml(r.memo || '')}</td> <td class="px-3 py-2 text-sm text-gray-500">${escapeHtml(r.memo || '')}</td>
<td class="px-3 py-2 text-sm text-right whitespace-nowrap ${r.amount < 0 ? 'text-red-600' : 'text-gray-900'}"> <td class="px-3 py-2 text-sm text-right whitespace-nowrap ${r.amount < 0 ? 'text-red-600' : 'text-gray-900'}">
${r.amount != null ? fmtMoney(r.amount) : ''} ${r.amount != null ? fmtMoney(r.amount) : ''}
@@ -351,90 +365,59 @@ function renderRegisterRow(r) {
</tr>`; </tr>`;
} }
// Punkt 4: Split-Aufschlüsselung
function renderSplitCell(r) { function renderSplitCell(r) {
if (!r.splits || !r.splits.length) { if (!r.splits || !r.splits.length) return `<span class="text-gray-500 italic">-Split-</span>`;
return `<span class="text-gray-500 italic">-Split-</span>`;
}
const lines = r.splits.map(s => ` const lines = r.splits.map(s => `
<div class="flex justify-between gap-3 text-xs"> <div class="flex justify-between gap-3 text-xs">
<span class="text-gray-700">${escapeHtml(s.account || '?')}</span> <span class="text-gray-700">${escapeHtml(s.account || '?')}</span>
<span class="text-gray-600 whitespace-nowrap">${s.amount != null ? fmtMoney(s.amount) : ''}</span> <span class="text-gray-600 whitespace-nowrap">${s.amount != null ? fmtMoney(s.amount) : ''}</span>
</div> </div>`).join('');
`).join('');
return `<div class="space-y-0.5">${lines}</div>`; return `<div class="space-y-0.5">${lines}</div>`;
} }
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
// Reports — P&L + Balance Sheet // Reports
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
export function injectReportsControls() { export function injectReportsControls() {
const c = document.getElementById('accounting-reports'); const c = document.getElementById('accounting-reports');
if (!c) return; if (!c) return;
if (!plStartDate) plStartDate = firstOfYearISO(); if (!plStartDate) plStartDate = firstOfYearISO();
if (!plEndDate) plEndDate = todayISO(); if (!plEndDate) plEndDate = todayISO();
if (!bsAsOfDate) bsAsOfDate = todayISO(); if (!bsAsOfDate) bsAsOfDate = todayISO();
c.innerHTML = ` c.innerHTML = `
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4"> <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
<!-- P&L -->
<div class="bg-white rounded-lg shadow-sm border border-gray-200"> <div class="bg-white rounded-lg shadow-sm border border-gray-200">
<div class="px-4 py-3 border-b bg-gray-50"> <div class="px-4 py-3 border-b bg-gray-50"><h3 class="font-semibold text-gray-800">Profit &amp; Loss</h3></div>
<h3 class="font-semibold text-gray-800">Profit &amp; Loss</h3>
</div>
<div class="p-4"> <div class="p-4">
<div class="flex flex-wrap items-end gap-3 mb-3"> <div class="flex flex-wrap items-end gap-3 mb-3">
<div> <div><label class="block text-xs font-medium text-gray-700 mb-1">Start</label>
<label class="block text-xs font-medium text-gray-700 mb-1">Start</label> <input type="date" id="pl-start" value="${plStartDate}" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm"></div>
<input type="date" id="pl-start" value="${plStartDate}" <div><label class="block text-xs font-medium text-gray-700 mb-1">End</label>
class="px-3 py-1.5 border border-gray-300 rounded-md text-sm"> <input type="date" id="pl-end" value="${plEndDate}" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm"></div>
</div> <div><label class="block text-xs font-medium text-gray-700 mb-1">Method</label>
<div>
<label class="block text-xs font-medium text-gray-700 mb-1">End</label>
<input type="date" id="pl-end" value="${plEndDate}"
class="px-3 py-1.5 border border-gray-300 rounded-md text-sm">
</div>
<div>
<label class="block text-xs font-medium text-gray-700 mb-1">Method</label>
<select id="pl-method" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm"> <select id="pl-method" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm">
<option value="Accrual" ${plAccountingMethod === 'Accrual' ? 'selected' : ''}>Accrual</option> <option value="Accrual" ${plAccountingMethod === 'Accrual' ? 'selected' : ''}>Accrual</option>
<option value="Cash" ${plAccountingMethod === 'Cash' ? 'selected' : ''}>Cash</option> <option value="Cash" ${plAccountingMethod === 'Cash' ? 'selected' : ''}>Cash</option>
</select> </select></div>
</div> <button onclick="window.accountingView.loadProfitLoss()" class="px-3 py-1.5 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700">Run</button>
<button onclick="window.accountingView.loadProfitLoss()"
class="px-3 py-1.5 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700">
Run
</button>
</div> </div>
<div id="pl-result"></div> <div id="pl-result"></div>
</div> </div>
</div> </div>
<!-- Balance Sheet -->
<div class="bg-white rounded-lg shadow-sm border border-gray-200"> <div class="bg-white rounded-lg shadow-sm border border-gray-200">
<div class="px-4 py-3 border-b bg-gray-50"> <div class="px-4 py-3 border-b bg-gray-50"><h3 class="font-semibold text-gray-800">Balance Sheet</h3></div>
<h3 class="font-semibold text-gray-800">Balance Sheet</h3>
</div>
<div class="p-4"> <div class="p-4">
<div class="flex flex-wrap items-end gap-3 mb-3"> <div class="flex flex-wrap items-end gap-3 mb-3">
<div> <div><label class="block text-xs font-medium text-gray-700 mb-1">As of</label>
<label class="block text-xs font-medium text-gray-700 mb-1">As of</label> <input type="date" id="bs-asof" value="${bsAsOfDate}" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm"></div>
<input type="date" id="bs-asof" value="${bsAsOfDate}" <div><label class="block text-xs font-medium text-gray-700 mb-1">Method</label>
class="px-3 py-1.5 border border-gray-300 rounded-md text-sm">
</div>
<div>
<label class="block text-xs font-medium text-gray-700 mb-1">Method</label>
<select id="bs-method" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm"> <select id="bs-method" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm">
<option value="Accrual" ${bsAccountingMethod === 'Accrual' ? 'selected' : ''}>Accrual</option> <option value="Accrual" ${bsAccountingMethod === 'Accrual' ? 'selected' : ''}>Accrual</option>
<option value="Cash" ${bsAccountingMethod === 'Cash' ? 'selected' : ''}>Cash</option> <option value="Cash" ${bsAccountingMethod === 'Cash' ? 'selected' : ''}>Cash</option>
</select> </select></div>
</div> <button onclick="window.accountingView.loadBalanceSheet()" class="px-3 py-1.5 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700">Run</button>
<button onclick="window.accountingView.loadBalanceSheet()"
class="px-3 py-1.5 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700">
Run
</button>
</div> </div>
<div id="bs-result"></div> <div id="bs-result"></div>
</div> </div>
@@ -446,58 +429,30 @@ export async function loadProfitLoss() {
plStartDate = document.getElementById('pl-start').value; plStartDate = document.getElementById('pl-start').value;
plEndDate = document.getElementById('pl-end').value; plEndDate = document.getElementById('pl-end').value;
plAccountingMethod = document.getElementById('pl-method').value; plAccountingMethod = document.getElementById('pl-method').value;
showLoading('pl-result', 'Loading P&L from QBO…'); showLoading('pl-result', 'Loading P&L from QBO…');
try { try {
const data = await window.API.accounting.getProfitAndLoss( const data = await window.API.accounting.getProfitAndLoss(plStartDate, plEndDate, plAccountingMethod);
plStartDate, plEndDate, plAccountingMethod
);
if (data.error) return showError('pl-result', data.error); if (data.error) return showError('pl-result', data.error);
document.getElementById('pl-result').innerHTML = renderQboReport(data); document.getElementById('pl-result').innerHTML = renderQboReport(data);
} catch (err) { } catch (err) { showError('pl-result', err.message || 'Failed to load P&L'); }
showError('pl-result', err.message || 'Failed to load P&L');
}
} }
export async function loadBalanceSheet() { export async function loadBalanceSheet() {
bsAsOfDate = document.getElementById('bs-asof').value; bsAsOfDate = document.getElementById('bs-asof').value;
bsAccountingMethod = document.getElementById('bs-method').value; bsAccountingMethod = document.getElementById('bs-method').value;
showLoading('bs-result', 'Loading Balance Sheet from QBO…'); showLoading('bs-result', 'Loading Balance Sheet from QBO…');
try { try {
const data = await window.API.accounting.getBalanceSheet( const data = await window.API.accounting.getBalanceSheet(bsAsOfDate, bsAccountingMethod);
bsAsOfDate, bsAccountingMethod
);
if (data.error) return showError('bs-result', data.error); if (data.error) return showError('bs-result', data.error);
document.getElementById('bs-result').innerHTML = renderQboReport(data); document.getElementById('bs-result').innerHTML = renderQboReport(data);
} catch (err) { } catch (err) { showError('bs-result', err.message || 'Failed to load Balance Sheet'); }
showError('bs-result', err.message || 'Failed to load Balance Sheet');
}
} }
// ────────────────────────────────────────────────────────────────────
// Generic QBO Report Renderer (P&L + Balance Sheet)
// QBO Reports haben rekursive Section/Row-Bäume mit Summary-Zeilen.
// Wir rendern sie als verschachtelte HTML-Tabelle.
// ────────────────────────────────────────────────────────────────────
function renderQboReport(report) { function renderQboReport(report) {
if (!report || !report.Header) { if (!report || !report.Header) return `<p class="text-sm text-gray-500">No report data.</p>`;
return `<p class="text-sm text-gray-500">No report data.</p>`;
}
const cols = (report.Columns && report.Columns.Column) || []; const cols = (report.Columns && report.Columns.Column) || [];
const colCount = cols.length; const headerRow = cols.map(c => `<th class="px-3 py-2 text-right font-medium text-gray-700 first:text-left">${escapeHtml(c.ColTitle || '')}</th>`).join('');
const body = report.Rows && report.Rows.Row ? renderReportRows(report.Rows.Row, 0) : '';
let body = '';
if (report.Rows && report.Rows.Row) {
body = renderReportRows(report.Rows.Row, 0, colCount);
}
const headerRow = cols.map(c =>
`<th class="px-3 py-2 text-right font-medium text-gray-700 first:text-left">${escapeHtml(c.ColTitle || '')}</th>`
).join('');
return ` return `
<div class="text-xs text-gray-500 mb-2"> <div class="text-xs text-gray-500 mb-2">
${escapeHtml(report.Header.ReportName || '')} ${escapeHtml(report.Header.ReportName || '')}
@@ -506,72 +461,186 @@ function renderQboReport(report) {
</div> </div>
<div class="overflow-x-auto border border-gray-200 rounded"> <div class="overflow-x-auto border border-gray-200 rounded">
<table class="min-w-full text-sm"> <table class="min-w-full text-sm">
<thead class="bg-gray-50 border-b"> <thead class="bg-gray-50 border-b"><tr>${headerRow}</tr></thead>
<tr>${headerRow}</tr>
</thead>
<tbody>${body}</tbody> <tbody>${body}</tbody>
</table> </table>
</div>`; </div>`;
} }
function renderReportRows(rows, depth, colCount) { function renderReportRows(rows, depth) {
if (!rows) return ''; if (!rows) return '';
const arr = Array.isArray(rows) ? rows : [rows]; const arr = Array.isArray(rows) ? rows : [rows];
let html = ''; let html = '';
for (const row of arr) { for (const row of arr) {
const isSection = row.type === 'Section' || row.Rows || row.Summary; const isSection = row.type === 'Section' || row.Rows || row.Summary;
const indentPx = depth * 16; const indent = depth * 16;
if (row.Header && row.Header.ColData) { if (row.Header && row.Header.ColData) {
// Section header row const cells = row.Header.ColData.map((c, i) =>
const headerCells = row.Header.ColData.map((c, i) => { i === 0
if (i === 0) { ? `<td class="px-3 py-1.5 font-semibold text-gray-800" style="padding-left:${12 + indent}px">${escapeHtml(c.value || '')}</td>`
return `<td class="px-3 py-1.5 font-semibold text-gray-800" style="padding-left:${12 + indentPx}px">${escapeHtml(c.value || '')}</td>`; : `<td class="px-3 py-1.5 text-right text-gray-500"></td>`
} ).join('');
return `<td class="px-3 py-1.5 text-right text-gray-500"></td>`; html += `<tr class="bg-gray-50">${cells}</tr>`;
}).join('');
html += `<tr class="bg-gray-50">${headerCells}</tr>`;
} }
if (isSection && row.Rows && row.Rows.Row) html += renderReportRows(row.Rows.Row, depth + 1);
if (isSection && row.Rows && row.Rows.Row) {
html += renderReportRows(row.Rows.Row, depth + 1, colCount);
}
if (row.Summary && row.Summary.ColData) { if (row.Summary && row.Summary.ColData) {
const sumCells = row.Summary.ColData.map((c, i) => { const cells = row.Summary.ColData.map((c, i) =>
if (i === 0) { i === 0
return `<td class="px-3 py-1.5 font-semibold text-gray-700 border-t" style="padding-left:${12 + indentPx}px">${escapeHtml(c.value || '')}</td>`; ? `<td class="px-3 py-1.5 font-semibold text-gray-700 border-t" style="padding-left:${12 + indent}px">${escapeHtml(c.value || '')}</td>`
} : `<td class="px-3 py-1.5 text-right font-semibold text-gray-900 border-t">${escapeHtml(c.value || '')}</td>`
return `<td class="px-3 py-1.5 text-right font-semibold text-gray-900 border-t">${escapeHtml(c.value || '')}</td>`; ).join('');
}).join(''); html += `<tr>${cells}</tr>`;
html += `<tr>${sumCells}</tr>`;
} }
if (!isSection && row.ColData) { if (!isSection && row.ColData) {
// Plain data row const cells = row.ColData.map((c, i) =>
const cells = row.ColData.map((c, i) => { i === 0
if (i === 0) { ? `<td class="px-3 py-1.5" style="padding-left:${12 + indent}px">${escapeHtml(c.value || '')}</td>`
return `<td class="px-3 py-1.5" style="padding-left:${12 + indentPx}px">${escapeHtml(c.value || '')}</td>`; : `<td class="px-3 py-1.5 text-right">${escapeHtml(c.value || '')}</td>`
} ).join('');
return `<td class="px-3 py-1.5 text-right">${escapeHtml(c.value || '')}</td>`;
}).join('');
html += `<tr>${cells}</tr>`; html += `<tr>${cells}</tr>`;
} }
} }
return html; return html;
} }
// ════════════════════════════════════════════════════════════════════
// Phase 2 Lieferung 2 — Expenses Section
// ════════════════════════════════════════════════════════════════════
export function injectExpensesSection() {
const c = document.getElementById('accounting-expenses');
if (!c) return;
if (!expStartDate) expStartDate = firstOfMonthISO();
if (!expEndDate) expEndDate = todayISO();
c.innerHTML = `
<div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
<div class="px-4 py-3 border-b bg-gray-50 flex flex-wrap items-end gap-3">
<div>
<label class="block text-xs font-medium text-gray-700 mb-1">Start</label>
<input type="date" id="exp-start" value="${expStartDate}" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm">
</div>
<div>
<label class="block text-xs font-medium text-gray-700 mb-1">End</label>
<input type="date" id="exp-end" value="${expEndDate}" class="px-3 py-1.5 border border-gray-300 rounded-md text-sm">
</div>
<div class="flex items-center gap-2 pt-5">
<input type="checkbox" id="exp-only-mine" ${expOnlyMine ? 'checked' : ''}
class="h-4 w-4 text-blue-600 border-gray-300 rounded">
<label for="exp-only-mine" class="text-sm text-gray-700" title="Only show expenses created from this app">Only mine</label>
</div>
<button onclick="window.accountingView.loadExpenses()"
class="px-3 py-1.5 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700">
Load
</button>
<div class="ml-auto">
<button onclick="window.accountingView.openNewExpense()"
class="px-4 py-1.5 bg-green-600 text-white rounded-md text-sm font-semibold hover:bg-green-700">
+ New Expense
</button>
</div>
</div>
<div id="accounting-expenses-table"></div>
</div>`;
}
export async function loadExpenses() {
const startEl = document.getElementById('exp-start');
const endEl = document.getElementById('exp-end');
const onlyEl = document.getElementById('exp-only-mine');
expStartDate = startEl.value;
expEndDate = endEl.value;
expOnlyMine = onlyEl.checked;
const slot = 'accounting-expenses-table';
showLoading(slot, 'Loading expenses from QBO…');
try {
const list = await window.API.accounting.listExpenses(expStartDate, expEndDate, expOnlyMine);
if (list.error) return showError(slot, list.error);
renderExpensesTable(list);
} catch (err) {
showError(slot, err.message || 'Failed to load expenses');
}
}
function renderExpensesTable(expenses) {
const el = document.getElementById('accounting-expenses-table');
if (!el) return;
if (!expenses.length) {
el.innerHTML = `<div class="p-4 text-gray-500 text-sm">No expenses in selected range${expOnlyMine ? ' (created from this app)' : ''}.</div>`;
return;
}
const sorted = expenses.slice().sort((a, b) => (b.txnDate || '').localeCompare(a.txnDate || ''));
const tbody = sorted.map(e => {
const splitsHtml = e.lines && e.lines.length > 1
? `<details><summary class="cursor-pointer text-blue-600 text-xs">${e.lines.length} lines</summary>
<div class="mt-1 space-y-0.5">
${e.lines.map(l => `
<div class="flex justify-between gap-3 text-xs">
<span class="text-gray-700">${escapeHtml(l.accountName || '?')}</span>
<span class="text-gray-600 whitespace-nowrap">${l.amount != null ? fmtMoney(l.amount) : ''}</span>
</div>`).join('')}
</div>
</details>`
: escapeHtml(e.lines[0]?.accountName || '');
return `
<tr class="border-t hover:bg-gray-50 align-top">
<td class="px-3 py-2 text-sm whitespace-nowrap">${escapeHtml(e.txnDate || '')}</td>
<td class="px-3 py-2 text-sm">${escapeHtml(e.vendorName || '')}</td>
<td class="px-3 py-2 text-sm">${escapeHtml(e.accountName || '')}</td>
<td class="px-3 py-2 text-sm text-gray-600">${splitsHtml}</td>
<td class="px-3 py-2 text-sm">${escapeHtml(e.refNo || '')}</td>
<td class="px-3 py-2 text-sm text-gray-500">${escapeHtml(e.memo || '')}</td>
<td class="px-3 py-2 text-sm text-right whitespace-nowrap text-red-600">${fmtMoney(e.totalAmt)}</td>
</tr>`;
}).join('');
el.innerHTML = `
<div class="overflow-x-auto">
<table class="min-w-full text-sm">
<thead class="bg-gray-50">
<tr>
<th class="px-3 py-2 text-left font-medium text-gray-700">Date</th>
<th class="px-3 py-2 text-left font-medium text-gray-700">Vendor</th>
<th class="px-3 py-2 text-left font-medium text-gray-700">Payment Account</th>
<th class="px-3 py-2 text-left font-medium text-gray-700">Category</th>
<th class="px-3 py-2 text-left font-medium text-gray-700">Ref</th>
<th class="px-3 py-2 text-left font-medium text-gray-700">Memo</th>
<th class="px-3 py-2 text-right font-medium text-gray-700">Amount</th>
</tr>
</thead>
<tbody>${tbody}</tbody>
</table>
<div class="px-3 py-2 text-xs text-gray-500 border-t bg-gray-50">${sorted.length} expense${sorted.length === 1 ? '' : 's'}</div>
</div>`;
}
export async function openNewExpense() {
await openExpenseModal({
onSaved: () => loadExpenses()
});
}
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
// Init / Public Entry Points // Init / Public Entry Points
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
export function renderAccountingView() { export function renderAccountingView() {
autoSyncDoneThisOpen = false;
injectToolbar(); injectToolbar();
injectRegisterControls(); injectRegisterControls();
injectReportsControls(); injectReportsControls();
loadAccountsOverview(); injectExpensesSection();
// Sequenz: erst Auto-Sync (wenn nötig), DANN Daten laden,
// damit das Frontend frische Cache-basierte Daten kriegt.
maybeAutoSyncCaches().then(() => {
loadAccountsOverview();
});
} }
export function refreshAll() { export function refreshAll() {
@@ -579,13 +648,15 @@ export function refreshAll() {
if (registerAccountId) loadRegister(); if (registerAccountId) loadRegister();
} }
// Expose for onclick handlers
window.accountingView = { window.accountingView = {
renderAccountingView, renderAccountingView,
refreshAll, refreshAll,
manualSync,
loadAccountsOverview, loadAccountsOverview,
loadRegister, loadRegister,
selectRegisterAccount, selectRegisterAccount,
loadProfitLoss, loadProfitLoss,
loadBalanceSheet loadBalanceSheet,
}; loadExpenses,
openNewExpense
};

View File

@@ -9,10 +9,15 @@ const accountingService = require('../services/accounting-service');
// ──────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────
function handleQboError(err, res, context) { function handleQboError(err, res, context) {
console.error(`❌ Accounting/${context} error:`, err.message); const statusCode = err.statusCode || 500;
if (err.qboFault) console.error(' QBO Fault detail:', JSON.stringify(err.qboFault)); if (statusCode >= 500) {
if (err.stack) console.error(err.stack); console.error(`❌ Accounting/${context} error:`, err.message);
res.status(500).json({ error: err.message || 'QBO request failed', context }); if (err.qboFault) console.error(' QBO Fault:', JSON.stringify(err.qboFault));
if (err.stack) console.error(err.stack);
} else {
console.warn(`⚠️ Accounting/${context} ${statusCode}:`, err.message);
}
res.status(statusCode).json({ error: err.message || 'Request failed', context });
} }
// ════════════════════════════════════════════════════════════════════ // ════════════════════════════════════════════════════════════════════
@@ -166,4 +171,40 @@ router.get('/payment-methods', async (req, res) => {
} catch (err) { handleQboError(err, res, 'payment-methods'); } } catch (err) { handleQboError(err, res, 'payment-methods'); }
}); });
// ─── POST /api/accounting/vendors ───────────────────────────────────
// Erstellt einen neuen Vendor in QBO + Cache.
// Body: { name, email?, phone?, address?: {...}, notes? }
// Status: 200 { id, displayName, ..., existed: false }
// 200 { ..., existed: true } ← Idempotent: Vendor war schon da
// 400 wenn name fehlt
router.post('/vendors', express.json(), async (req, res) => {
try {
const result = await accountingService.createVendor(req.body || {});
res.json(result);
} catch (err) { handleQboError(err, res, 'vendor-create'); }
});
// ─── POST /api/accounting/expenses ──────────────────────────────────
// Erstellt eine QBO Purchase (Expense) mit ein oder mehreren Lines.
// Body: { vendorId, paymentAccountId, txnDate, paymentMethodId?, refNo?, memo?, lines: [...] }
router.post('/expenses', express.json(), async (req, res) => {
try {
const result = await accountingService.createExpense(req.body || {});
res.json(result);
} catch (err) { handleQboError(err, res, 'expense-create'); }
});
// ─── GET /api/accounting/expenses ───────────────────────────────────
// ?startDate=YYYY-MM-DD&endDate=YYYY-MM-DD&onlyMine=true|false
router.get('/expenses', async (req, res) => {
try {
const expenses = await accountingService.listExpenses({
startDate: req.query.startDate,
endDate: req.query.endDate,
onlyMine: req.query.onlyMine === 'true'
});
res.json(expenses);
} catch (err) { handleQboError(err, res, 'expense-list'); }
});
module.exports = router; module.exports = router;

View File

@@ -600,6 +600,389 @@ async function getPaymentMethods({ activeOnly = true } = {}) {
})); }));
} }
// ────────────────────────────────────────────────────────────────────
// Phase 2 Lieferung 2 — Vendor Create
// ────────────────────────────────────────────────────────────────────
/**
* Erstellt einen neuen Vendor in QBO und schreibt ihn in den Cache.
*
* Idempotenz: Wenn ein aktiver Vendor mit gleichem display_name (case-insensitive)
* bereits im Cache existiert, wird KEIN neuer angelegt — stattdessen wird der
* existierende zurückgegeben mit { existed: true }.
*
* @param {Object} data
* @param {string} data.name - Pflicht: DisplayName
* @param {string} [data.email]
* @param {string} [data.phone]
* @param {Object} [data.address] - { line1, line2, city, state, zip, country }
* @param {string} [data.notes]
* @returns {{ id, displayName, email, phone, existed: boolean }}
*/
async function createVendor(data) {
const name = (data.name || '').trim();
if (!name) {
const err = new Error('Vendor name is required');
err.statusCode = 400;
throw err;
}
// ── Idempotenz-Check ──
const existingResult = await pool.query(
`SELECT qbo_id, display_name, primary_email, primary_phone
FROM qbo_vendor_cache
WHERE active = true AND LOWER(display_name) = LOWER($1)
LIMIT 1`,
[name]
);
if (existingResult.rows.length > 0) {
const v = existingResult.rows[0];
return {
id: v.qbo_id,
displayName: v.display_name,
email: v.primary_email,
phone: v.primary_phone,
existed: true
};
}
// ── QBO Create ──
const { companyId, baseUrl } = getClientInfo();
const url = withMinorVersion(`${baseUrl}/v3/company/${companyId}/vendor`);
const payload = {
DisplayName: name,
CompanyName: name,
Active: true
};
if (data.email) payload.PrimaryEmailAddr = { Address: data.email };
if (data.phone) payload.PrimaryPhone = { FreeFormNumber: data.phone };
if (data.notes) payload.Notes = data.notes;
if (data.address && (data.address.line1 || data.address.city)) {
const a = data.address;
const billAddr = {};
if (a.line1) billAddr.Line1 = a.line1;
if (a.line2) billAddr.Line2 = a.line2;
if (a.city) billAddr.City = a.city;
if (a.state) billAddr.CountrySubDivisionCode = a.state;
if (a.zip) billAddr.PostalCode = a.zip;
if (a.country) billAddr.Country = a.country;
payload.BillAddr = billAddr;
}
let qboResponse;
try {
const response = await makeQboApiCall({
url,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
qboResponse = getJson(response);
} catch (err) {
await writeAuditLog({
action: 'vendor.create',
entityType: 'Vendor',
status: 'error',
requestExcerpt: JSON.stringify(payload).slice(0, 1000),
responseExcerpt: err.message
});
throw err;
}
if (qboResponse.Fault) {
const msg = qboResponse.Fault.Error.map(e => `${e.code}: ${e.Message}`).join('; ');
await writeAuditLog({
action: 'vendor.create',
entityType: 'Vendor',
status: 'error',
requestExcerpt: JSON.stringify(payload).slice(0, 1000),
responseExcerpt: msg
});
const err = new Error('QBO Vendor create failed: ' + msg);
err.qboFault = qboResponse.Fault;
throw err;
}
const v = qboResponse.Vendor;
if (!v || !v.Id) {
throw new Error('QBO returned no vendor id');
}
// ── In Cache schreiben ──
const email = v.PrimaryEmailAddr ? v.PrimaryEmailAddr.Address : null;
const phone = v.PrimaryPhone ? v.PrimaryPhone.FreeFormNumber : null;
await pool.query(
`INSERT INTO qbo_vendor_cache
(qbo_id, display_name, company_name, primary_email, primary_phone,
active, sync_token, cached_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, CURRENT_TIMESTAMP)
ON CONFLICT (qbo_id) DO UPDATE SET
display_name = EXCLUDED.display_name,
company_name = EXCLUDED.company_name,
primary_email = EXCLUDED.primary_email,
primary_phone = EXCLUDED.primary_phone,
active = EXCLUDED.active,
sync_token = EXCLUDED.sync_token,
cached_at = CURRENT_TIMESTAMP`,
[v.Id, v.DisplayName, v.CompanyName || null, email, phone, v.Active === true, v.SyncToken || null]
);
await writeAuditLog({
action: 'vendor.create',
entityType: 'Vendor',
entityQboId: v.Id,
status: 'success',
requestExcerpt: JSON.stringify(payload).slice(0, 1000),
responseExcerpt: `Vendor ${v.Id} (${v.DisplayName}) created`
});
console.log(`✅ QBO Vendor created: ${v.Id} (${v.DisplayName})`);
return {
id: v.Id,
displayName: v.DisplayName,
email,
phone,
existed: false
};
}
// ────────────────────────────────────────────────────────────────────
// Phase 2 Lieferung 2 — Expense Create
// ────────────────────────────────────────────────────────────────────
/**
* Erstellt eine QBO Purchase (= "Expense" in QBO-Sprech).
*
* @param {Object} data
* @param {string} data.vendorId - Pflicht
* @param {string} data.paymentAccountId - Pflicht (Bank- oder Credit-Card-Account)
* @param {string} data.txnDate - Pflicht, YYYY-MM-DD
* @param {string} [data.paymentMethodId]
* @param {string} [data.refNo]
* @param {string} [data.memo]
* @param {Array} data.lines - Pflicht, mind. 1 Line
* Line: { accountId, amount, description? }
*
* @returns {{ id, txnDate, totalAmt, lineCount, vendorName, accountName }}
*/
async function createExpense(data) {
// ── Validierung ──
if (!data.vendorId) throw badRequest('vendorId is required');
if (!data.paymentAccountId) throw badRequest('paymentAccountId is required');
if (!data.txnDate) throw badRequest('txnDate is required');
if (!Array.isArray(data.lines) || data.lines.length === 0) {
throw badRequest('At least one line is required');
}
for (const [i, line] of data.lines.entries()) {
if (!line.accountId) throw badRequest(`Line ${i + 1}: accountId is required`);
const amt = Number(line.amount);
if (!isFinite(amt) || amt <= 0) {
throw badRequest(`Line ${i + 1}: amount must be a positive number`);
}
}
// ── Account-Type des Payment-Accounts bestimmen ──
// Bank → PaymentType "Check" (default in QBO)
// Credit Card → PaymentType "CreditCard"
const acctRow = await pool.query(
`SELECT qbo_id, name, account_type FROM qbo_account_cache WHERE qbo_id = $1`,
[data.paymentAccountId]
);
if (acctRow.rows.length === 0) {
throw badRequest(`Payment account ${data.paymentAccountId} not in cache. Run sync first.`);
}
const paymentAcct = acctRow.rows[0];
const paymentType = paymentAcct.account_type === 'Credit Card' ? 'CreditCard' : 'Check';
// ── Vendor-Name aus Cache (für Logging/Response) ──
const vendorRow = await pool.query(
`SELECT display_name FROM qbo_vendor_cache WHERE qbo_id = $1`,
[data.vendorId]
);
const vendorName = vendorRow.rows[0]?.display_name || data.vendorId;
// ── QBO Purchase Payload ──
const totalAmt = data.lines.reduce((sum, l) => sum + Number(l.amount), 0);
const payload = {
AccountRef: { value: paymentAcct.qbo_id, name: paymentAcct.name },
EntityRef: { value: data.vendorId, type: 'Vendor', name: vendorName },
TxnDate: data.txnDate,
PaymentType: paymentType,
Line: data.lines.map(line => ({
DetailType: 'AccountBasedExpenseLineDetail',
Amount: Number(line.amount),
Description: line.description || undefined,
AccountBasedExpenseLineDetail: {
AccountRef: { value: String(line.accountId) }
}
}))
};
if (data.refNo) payload.DocNumber = String(data.refNo).slice(0, 21);
if (data.memo) payload.PrivateNote = String(data.memo);
if (data.paymentMethodId) {
payload.PaymentMethodRef = { value: String(data.paymentMethodId) };
}
// ── QBO POST ──
const { companyId, baseUrl } = getClientInfo();
const url = withMinorVersion(`${baseUrl}/v3/company/${companyId}/purchase`);
const requestSummary = `${vendorName} | ${paymentAcct.name} | ${data.txnDate} | $${totalAmt.toFixed(2)} | ${data.lines.length} line(s)`;
let qboResponse;
try {
const response = await makeQboApiCall({
url,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
qboResponse = getJson(response);
} catch (err) {
await writeAuditLog({
action: 'expense.create',
entityType: 'Purchase',
status: 'error',
requestExcerpt: requestSummary,
responseExcerpt: err.message
});
throw err;
}
if (qboResponse.Fault) {
const msg = qboResponse.Fault.Error.map(e =>
`${e.code}: ${e.Message}${e.Detail ? ' - ' + e.Detail : ''}`
).join('; ');
await writeAuditLog({
action: 'expense.create',
entityType: 'Purchase',
status: 'error',
requestExcerpt: requestSummary,
responseExcerpt: msg
});
const err = new Error('QBO Purchase create failed: ' + msg);
err.qboFault = qboResponse.Fault;
throw err;
}
const purchase = qboResponse.Purchase;
if (!purchase || !purchase.Id) throw new Error('QBO returned no Purchase id');
await writeAuditLog({
action: 'expense.create',
entityType: 'Purchase',
entityQboId: purchase.Id,
status: 'success',
requestExcerpt: requestSummary,
responseExcerpt: `Purchase ${purchase.Id} created, total $${Number(purchase.TotalAmt).toFixed(2)}`
});
console.log(`✅ QBO Expense created: Purchase ${purchase.Id}${requestSummary}`);
return {
id: purchase.Id,
txnDate: purchase.TxnDate,
totalAmt: Number(purchase.TotalAmt),
lineCount: data.lines.length,
vendorName,
accountName: paymentAcct.name
};
}
function badRequest(msg) {
const err = new Error(msg);
err.statusCode = 400;
return err;
}
// ────────────────────────────────────────────────────────────────────
// Phase 2 Lieferung 2 — Expense List (read)
// ────────────────────────────────────────────────────────────────────
/**
* Liefert eine Liste von QBO Purchases (=Expenses) für ein Datums-Intervall.
*
* @param {Object} opts
* @param {string} opts.startDate - Pflicht
* @param {string} opts.endDate - Pflicht
* @param {boolean} [opts.onlyMine] - Wenn true, nur Purchases die in unserem
* accounting_sync_log mit action='expense.create'
* erfolgreich exportiert wurden
* @returns {Array<{ id, txnDate, totalAmt, vendorName, accountName, refNo, memo, lines }>}
*/
async function listExpenses({ startDate, endDate, onlyMine = false } = {}) {
if (!startDate || !endDate) throw badRequest('startDate and endDate are required');
const { companyId, baseUrl } = getClientInfo();
// Wir queryen Purchases in dem Date-Range. PaymentType filtern wir nicht —
// QBO speichert auch Expense-Buchungen mit AccountBasedExpenseLineDetail.
const safeStart = startDate.replace(/'/g, '');
const safeEnd = endDate.replace(/'/g, '');
const sql = `SELECT * FROM Purchase WHERE TxnDate >= '${safeStart}' AND TxnDate <= '${safeEnd}' ORDERBY TxnDate DESC MAXRESULTS 1000`;
const url = withMinorVersion(
`${baseUrl}/v3/company/${companyId}/query?query=${encodeURIComponent(sql)}`
);
const response = await makeQboApiCall({ url, method: 'GET' });
const data = getJson(response);
throwIfFault(data, 'Purchase query');
let purchases = (data.QueryResponse && data.QueryResponse.Purchase) || [];
// Filter: nur App-eigene Expenses
if (onlyMine) {
const r = await pool.query(
`SELECT DISTINCT entity_qbo_id FROM accounting_sync_log
WHERE action = 'expense.create' AND status = 'success' AND entity_qbo_id IS NOT NULL`
);
const myIds = new Set(r.rows.map(row => row.entity_qbo_id));
purchases = purchases.filter(p => myIds.has(p.Id));
}
return purchases.map(p => normalizePurchase(p));
}
function normalizePurchase(p) {
const lines = (p.Line || [])
.filter(l => l.DetailType !== 'SubTotalLineDetail')
.map(l => {
const detail = l.AccountBasedExpenseLineDetail || {};
const acctRef = detail.AccountRef || {};
return {
accountId: acctRef.value || null,
accountName: acctRef.name || null,
amount: l.Amount != null ? Number(l.Amount) : null,
description: l.Description || null
};
});
return {
id: p.Id,
txnDate: p.TxnDate,
totalAmt: p.TotalAmt != null ? Number(p.TotalAmt) : 0,
vendorName: p.EntityRef ? p.EntityRef.name : null,
vendorId: p.EntityRef ? p.EntityRef.value : null,
accountName: p.AccountRef ? p.AccountRef.name : null,
accountId: p.AccountRef ? p.AccountRef.value : null,
paymentType: p.PaymentType,
refNo: p.DocNumber || null,
memo: p.PrivateNote || null,
lines
};
}
// ════════════════════════════════════════════════════════════════════ // ════════════════════════════════════════════════════════════════════
// Exports // Exports
// ════════════════════════════════════════════════════════════════════ // ════════════════════════════════════════════════════════════════════
@@ -624,6 +1007,11 @@ module.exports = {
getPaymentAccountsFromCache, getPaymentAccountsFromCache,
getPaymentMethods, getPaymentMethods,
// Phase 2 Lieferung 2 — Mutations + List
createVendor,
createExpense,
listExpenses,
// Audit // Audit
writeAuditLog writeAuditLog
}; };