This commit is contained in:
2026-05-25 14:29:24 -05:00
parent f535f35eee
commit 7e490dbc93
5 changed files with 452 additions and 2 deletions

View 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, '&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;');
}
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
};