refund
This commit is contained in:
282
public/js/modals/refund-modal.js
Normal file
282
public/js/modals/refund-modal.js
Normal file
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* refund-modal.js — Record Vendor Refund
|
||||
*
|
||||
* Erzeugt einen QBO Deposit gegen die ursprüngliche Expense-Kategorie.
|
||||
* Für den Fall: Geld kam tatsächlich zurück aufs Bank-/Kreditkartenkonto.
|
||||
*/
|
||||
|
||||
import '../utils/api.js';
|
||||
|
||||
let modalEl = null;
|
||||
let onSavedCb = null;
|
||||
|
||||
let vendors = [];
|
||||
let expenseAccounts = [];
|
||||
let paymentAccounts = [];
|
||||
|
||||
let selectedVendorId = null;
|
||||
let selectedVendorName = '';
|
||||
let isSaving = false;
|
||||
|
||||
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, '"').replace(/'/g, ''');
|
||||
}
|
||||
function escapeAttr(s) {
|
||||
return String(s || '')
|
||||
.replace(/&/g, '&').replace(/"/g, '"')
|
||||
.replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
export async function openRefundModal({ onSaved } = {}) {
|
||||
onSavedCb = onSaved || null;
|
||||
selectedVendorId = null;
|
||||
selectedVendorName = '';
|
||||
isSaving = false;
|
||||
|
||||
try {
|
||||
[vendors, expenseAccounts, paymentAccounts] = await Promise.all([
|
||||
window.API.accounting.getVendors('', 1000),
|
||||
window.API.accounting.getExpenseAccounts(),
|
||||
window.API.accounting.getPaymentAccounts()
|
||||
]);
|
||||
for (const [name, data] of [['vendors', vendors], ['expenseAccounts', expenseAccounts], ['paymentAccounts', paymentAccounts]]) {
|
||||
if (data && data.error) {
|
||||
alert(`Failed to load ${name}: ${data.error}\n\nTry "Sync from QBO" first.`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Failed to load refund modal data: ' + err.message);
|
||||
return;
|
||||
}
|
||||
|
||||
renderModal();
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
if (modalEl) { modalEl.remove(); modalEl = null; }
|
||||
}
|
||||
|
||||
function renderModal() {
|
||||
closeModal();
|
||||
|
||||
const html = `
|
||||
<div id="refund-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-2xl 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">↩️ Record Refund</h3>
|
||||
<button onclick="window.refundModal.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>
|
||||
|
||||
<p class="text-sm text-gray-500 mb-4">
|
||||
Money refunded by a vendor that was returned to your bank or credit card.
|
||||
Booked against the original expense category.
|
||||
</p>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4 mb-4">
|
||||
<div class="relative">
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Vendor *</label>
|
||||
<input type="text" id="ref-vendor-search" autocomplete="off"
|
||||
oninput="window.refundModal.onVendorInput()"
|
||||
onfocus="window.refundModal.onVendorInput()"
|
||||
placeholder="Type to search…"
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-md">
|
||||
<input type="hidden" id="ref-vendor-id">
|
||||
<div id="ref-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">Date *</label>
|
||||
<input type="date" id="ref-date" value="${todayISO()}"
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-md">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4 mb-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Deposit To *</label>
|
||||
<select id="ref-deposit-account" class="w-full px-3 py-2 border border-gray-300 rounded-md">
|
||||
<option value="">— Select account —</option>
|
||||
${paymentAccounts.map(a => `
|
||||
<option value="${a.id}">${escapeHtml(a.name)} (${escapeHtml(a.accountType)})</option>`).join('')}
|
||||
</select>
|
||||
<p class="text-xs text-gray-400 mt-1">Where the money came back to.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Original Category *</label>
|
||||
<select id="ref-category" class="w-full px-3 py-2 border border-gray-300 rounded-md">
|
||||
<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>
|
||||
<p class="text-xs text-gray-400 mt-1">Same category as the original expense.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-4 mb-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Refund Amount *</label>
|
||||
<input type="number" step="0.01" min="0" id="ref-amount"
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-md text-right"
|
||||
placeholder="0.00">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Ref No.</label>
|
||||
<input type="text" id="ref-ref-no" maxlength="21"
|
||||
class="w-full px-3 py-2 border border-gray-300 rounded-md"
|
||||
placeholder="e.g. eBay refund ID">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Memo</label>
|
||||
<textarea id="ref-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="ref-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.refundModal.close()"
|
||||
class="px-5 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-md">Cancel</button>
|
||||
<button type="button" id="ref-save-btn" onclick="window.refundModal.save()"
|
||||
class="px-5 py-2 bg-green-600 hover:bg-green-700 text-white rounded-md font-medium">
|
||||
Record Refund
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
document.body.insertAdjacentHTML('beforeend', html);
|
||||
modalEl = document.getElementById('refund-modal');
|
||||
}
|
||||
|
||||
function onVendorInput() {
|
||||
const inputEl = document.getElementById('ref-vendor-search');
|
||||
const dropdownEl = document.getElementById('ref-vendor-dropdown');
|
||||
const q = (inputEl.value || '').trim().toLowerCase();
|
||||
|
||||
if (selectedVendorName && inputEl.value !== selectedVendorName) {
|
||||
selectedVendorId = null;
|
||||
selectedVendorName = '';
|
||||
document.getElementById('ref-vendor-id').value = '';
|
||||
}
|
||||
|
||||
const filtered = q
|
||||
? vendors.filter(v => v.displayName.toLowerCase().includes(q)).slice(0, 50)
|
||||
: vendors.slice(0, 50);
|
||||
|
||||
let html = '';
|
||||
if (filtered.length === 0) {
|
||||
html = `<div class="px-3 py-2 text-gray-500 text-sm">No vendor found.</div>`;
|
||||
} else {
|
||||
html = filtered.map(v => `
|
||||
<div class="px-3 py-2 cursor-pointer hover:bg-gray-100 text-sm"
|
||||
onclick="window.refundModal.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');
|
||||
|
||||
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('ref-vendor-search').value = name;
|
||||
document.getElementById('ref-vendor-id').value = id;
|
||||
document.getElementById('ref-vendor-dropdown').classList.add('hidden');
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (isSaving) return;
|
||||
hideError();
|
||||
|
||||
if (!selectedVendorId) return showError('Please select a vendor.');
|
||||
|
||||
const depositAccountId = document.getElementById('ref-deposit-account').value;
|
||||
if (!depositAccountId) return showError('Please select the deposit account.');
|
||||
|
||||
const categoryAccountId = document.getElementById('ref-category').value;
|
||||
if (!categoryAccountId) return showError('Please select the original expense category.');
|
||||
|
||||
const txnDate = document.getElementById('ref-date').value;
|
||||
if (!txnDate) return showError('Please enter a date.');
|
||||
|
||||
const amount = parseFloat(document.getElementById('ref-amount').value);
|
||||
if (!isFinite(amount) || amount <= 0) {
|
||||
return showError('Please enter a positive refund amount.');
|
||||
}
|
||||
|
||||
const payload = {
|
||||
vendorId: selectedVendorId,
|
||||
depositAccountId,
|
||||
categoryAccountId,
|
||||
txnDate,
|
||||
amount,
|
||||
refNo: document.getElementById('ref-ref-no').value.trim() || null,
|
||||
memo: document.getElementById('ref-memo').value.trim() || null
|
||||
};
|
||||
|
||||
isSaving = true;
|
||||
const btn = document.getElementById('ref-save-btn');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Saving…';
|
||||
|
||||
try {
|
||||
const result = await window.API.accounting.createRefund(payload);
|
||||
if (result.error) {
|
||||
showError(result.error);
|
||||
return;
|
||||
}
|
||||
if (typeof onSavedCb === 'function') {
|
||||
try { onSavedCb(result); } catch (e) { console.warn('onSaved cb threw:', e); }
|
||||
}
|
||||
closeModal();
|
||||
} catch (err) {
|
||||
showError(err.message || 'Save failed');
|
||||
} finally {
|
||||
isSaving = false;
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Record Refund'; }
|
||||
}
|
||||
}
|
||||
|
||||
function showError(msg) {
|
||||
const el = document.getElementById('ref-error');
|
||||
if (el) { el.textContent = msg; el.classList.remove('hidden'); }
|
||||
}
|
||||
function hideError() {
|
||||
const el = document.getElementById('ref-error');
|
||||
if (el) el.classList.add('hidden');
|
||||
}
|
||||
|
||||
window.refundModal = {
|
||||
open: openRefundModal,
|
||||
close: closeModal,
|
||||
onVendorInput,
|
||||
selectVendor,
|
||||
save
|
||||
};
|
||||
@@ -169,6 +169,12 @@ const API = {
|
||||
body: JSON.stringify(data)
|
||||
}).then(r => r.json()),
|
||||
|
||||
createRefund: (data) => fetch('/api/accounting/refunds', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
}).then(r => r.json()),
|
||||
|
||||
updateExpense: (id, data) => fetch(`/api/accounting/expenses/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import '../utils/api.js';
|
||||
import { formatDate } from '../utils/helpers.js';
|
||||
import { openExpenseModal } from '../modals/expense-modal.js';
|
||||
import { openRefundModal } from '../modals/refund-modal.js';
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────
|
||||
// State (modul-lokal)
|
||||
@@ -568,7 +569,11 @@ export function injectExpensesSection() {
|
||||
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">
|
||||
<div class="ml-auto flex gap-2">
|
||||
<button onclick="window.accountingView.openNewRefund()"
|
||||
class="px-4 py-1.5 bg-amber-600 text-white rounded-md text-sm font-semibold hover:bg-amber-700">
|
||||
↩️ Record Refund
|
||||
</button>
|
||||
<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
|
||||
@@ -703,17 +708,26 @@ export async function editExpense(expenseJson) {
|
||||
onSaved: () => loadExpenses()
|
||||
});
|
||||
}
|
||||
export async function openNewRefund() {
|
||||
await openRefundModal({
|
||||
onSaved: (result) => {
|
||||
alert(`✅ Refund recorded: ${fmtMoney(result.totalAmt)} from ${result.vendorName}\nDeposit #${result.id} — booked to ${result.categoryName}`);
|
||||
loadExpenses();
|
||||
}
|
||||
});
|
||||
}
|
||||
window.accountingView = {
|
||||
renderAccountingView,
|
||||
refreshAll,
|
||||
manualSync,
|
||||
loadAccountsOverview,
|
||||
loadRegister,
|
||||
selectRegisterAccount,
|
||||
loadProfitLoss,
|
||||
loadBalanceSheet,
|
||||
loadExpenses,
|
||||
openNewExpense,
|
||||
openNewRefund,
|
||||
editExpense,
|
||||
selectRegisterAccount,
|
||||
toggleSection
|
||||
};
|
||||
Reference in New Issue
Block a user