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)
|
body: JSON.stringify(data)
|
||||||
}).then(r => r.json()),
|
}).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}`, {
|
updateExpense: (id, data) => fetch(`/api/accounting/expenses/${id}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
import '../utils/api.js';
|
import '../utils/api.js';
|
||||||
import { formatDate } from '../utils/helpers.js';
|
import { formatDate } from '../utils/helpers.js';
|
||||||
import { openExpenseModal } from '../modals/expense-modal.js';
|
import { openExpenseModal } from '../modals/expense-modal.js';
|
||||||
|
import { openRefundModal } from '../modals/refund-modal.js';
|
||||||
|
|
||||||
// ────────────────────────────────────────────────────────────────────
|
// ────────────────────────────────────────────────────────────────────
|
||||||
// State (modul-lokal)
|
// 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">
|
class="px-3 py-1.5 bg-blue-600 text-white rounded-md text-sm font-medium hover:bg-blue-700">
|
||||||
Load
|
Load
|
||||||
</button>
|
</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()"
|
<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">
|
class="px-4 py-1.5 bg-green-600 text-white rounded-md text-sm font-semibold hover:bg-green-700">
|
||||||
+ New Expense
|
+ New Expense
|
||||||
@@ -703,17 +708,26 @@ export async function editExpense(expenseJson) {
|
|||||||
onSaved: () => loadExpenses()
|
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 = {
|
window.accountingView = {
|
||||||
renderAccountingView,
|
renderAccountingView,
|
||||||
refreshAll,
|
refreshAll,
|
||||||
manualSync,
|
manualSync,
|
||||||
loadAccountsOverview,
|
loadAccountsOverview,
|
||||||
loadRegister,
|
loadRegister,
|
||||||
selectRegisterAccount,
|
|
||||||
loadProfitLoss,
|
loadProfitLoss,
|
||||||
loadBalanceSheet,
|
loadBalanceSheet,
|
||||||
loadExpenses,
|
loadExpenses,
|
||||||
openNewExpense,
|
openNewExpense,
|
||||||
|
openNewRefund,
|
||||||
editExpense,
|
editExpense,
|
||||||
|
selectRegisterAccount,
|
||||||
toggleSection
|
toggleSection
|
||||||
};
|
};
|
||||||
@@ -277,6 +277,15 @@ router.put('/expenses/:id', express.json(), async (req, res) => {
|
|||||||
res.json(result);
|
res.json(result);
|
||||||
} catch (err) { handleQboError(err, res, 'expense-update'); }
|
} catch (err) { handleQboError(err, res, 'expense-update'); }
|
||||||
});
|
});
|
||||||
|
// ─── POST /api/accounting/refunds ───────────────────────────────────
|
||||||
|
// Erstellt einen QBO Deposit für einen Vendor-Refund (Geld kam zurück).
|
||||||
|
// Body: { vendorId, depositAccountId, categoryAccountId, txnDate, amount, refNo?, memo? }
|
||||||
|
router.post('/refunds', express.json(), async (req, res) => {
|
||||||
|
try {
|
||||||
|
const result = await accountingService.createRefund(req.body || {});
|
||||||
|
res.json(result);
|
||||||
|
} catch (err) { handleQboError(err, res, 'refund-create'); }
|
||||||
|
});
|
||||||
router.get('/attachments/limits', (req, res) => {
|
router.get('/attachments/limits', (req, res) => {
|
||||||
res.json({
|
res.json({
|
||||||
maxBytes: ATTACHMENT_MAX_BYTES,
|
maxBytes: ATTACHMENT_MAX_BYTES,
|
||||||
|
|||||||
@@ -898,6 +898,144 @@ async function createExpense(data) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erstellt einen QBO Deposit für einen Vendor-Refund (Geld kam zurück aufs Konto).
|
||||||
|
*
|
||||||
|
* Buchhalterisch: Der Refund wird gegen die ursprüngliche Expense-Kategorie
|
||||||
|
* gebucht, wodurch sich der Aufwand in dieser Kategorie reduziert.
|
||||||
|
*
|
||||||
|
* @param {Object} data
|
||||||
|
* @param {string} data.vendorId - Pflicht (von wem kam der Refund)
|
||||||
|
* @param {string} data.depositAccountId - Pflicht (Bank/CC-Konto, wo das Geld ankam)
|
||||||
|
* @param {string} data.txnDate - Pflicht, YYYY-MM-DD
|
||||||
|
* @param {string} data.categoryAccountId - Pflicht (ursprüngliche Expense-Kategorie)
|
||||||
|
* @param {number} data.amount - Pflicht, positiver Betrag
|
||||||
|
* @param {string} [data.refNo]
|
||||||
|
* @param {string} [data.memo]
|
||||||
|
* @returns {{ id, txnDate, totalAmt, vendorName, depositAccountName, categoryName }}
|
||||||
|
*/
|
||||||
|
async function createRefund(data) {
|
||||||
|
if (!data.vendorId) throw badRequest('vendorId is required');
|
||||||
|
if (!data.depositAccountId) throw badRequest('depositAccountId is required');
|
||||||
|
if (!data.categoryAccountId) throw badRequest('categoryAccountId is required');
|
||||||
|
if (!data.txnDate) throw badRequest('txnDate is required');
|
||||||
|
|
||||||
|
const amount = Number(data.amount);
|
||||||
|
if (!isFinite(amount) || amount <= 0) {
|
||||||
|
throw badRequest('amount must be a positive number (the refund value)');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Deposit-Konto aus Cache ──
|
||||||
|
const depRow = await pool.query(
|
||||||
|
`SELECT qbo_id, name, account_type FROM qbo_account_cache WHERE qbo_id = $1`,
|
||||||
|
[data.depositAccountId]
|
||||||
|
);
|
||||||
|
if (depRow.rows.length === 0) {
|
||||||
|
throw badRequest(`Deposit account ${data.depositAccountId} not in cache. Run sync first.`);
|
||||||
|
}
|
||||||
|
const depositAcct = depRow.rows[0];
|
||||||
|
|
||||||
|
// ── Kategorie-Konto aus Cache ──
|
||||||
|
const catRow = await pool.query(
|
||||||
|
`SELECT qbo_id, name FROM qbo_account_cache WHERE qbo_id = $1`,
|
||||||
|
[data.categoryAccountId]
|
||||||
|
);
|
||||||
|
if (catRow.rows.length === 0) {
|
||||||
|
throw badRequest(`Category account ${data.categoryAccountId} not in cache. Run sync first.`);
|
||||||
|
}
|
||||||
|
const categoryAcct = catRow.rows[0];
|
||||||
|
|
||||||
|
// ── Vendor-Name aus Cache ──
|
||||||
|
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 Deposit Payload ──
|
||||||
|
const payload = {
|
||||||
|
DepositToAccountRef: { value: depositAcct.qbo_id, name: depositAcct.name },
|
||||||
|
TxnDate: data.txnDate,
|
||||||
|
Line: [{
|
||||||
|
DetailType: 'DepositLineDetail',
|
||||||
|
Amount: amount,
|
||||||
|
Description: data.memo || `Refund from ${vendorName}`,
|
||||||
|
DepositLineDetail: {
|
||||||
|
AccountRef: { value: categoryAcct.qbo_id, name: categoryAcct.name },
|
||||||
|
Entity: { value: data.vendorId, type: 'Vendor' }
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
};
|
||||||
|
|
||||||
|
if (data.refNo) payload.Line[0].DepositLineDetail.CheckNum = String(data.refNo).slice(0, 21);
|
||||||
|
if (data.memo) payload.PrivateNote = String(data.memo);
|
||||||
|
|
||||||
|
const { companyId, baseUrl } = getClientInfo();
|
||||||
|
const url = withMinorVersion(`${baseUrl}/v3/company/${companyId}/deposit`);
|
||||||
|
|
||||||
|
const requestSummary = `REFUND | ${vendorName} → ${depositAcct.name} | ${categoryAcct.name} | ${data.txnDate} | $${amount.toFixed(2)}`;
|
||||||
|
|
||||||
|
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: 'refund.create',
|
||||||
|
entityType: 'Deposit',
|
||||||
|
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: 'refund.create',
|
||||||
|
entityType: 'Deposit',
|
||||||
|
status: 'error',
|
||||||
|
requestExcerpt: requestSummary,
|
||||||
|
responseExcerpt: msg
|
||||||
|
});
|
||||||
|
const err = new Error('QBO Deposit (refund) create failed: ' + msg);
|
||||||
|
err.qboFault = qboResponse.Fault;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
const deposit = qboResponse.Deposit;
|
||||||
|
if (!deposit || !deposit.Id) throw new Error('QBO returned no Deposit id');
|
||||||
|
|
||||||
|
await writeAuditLog({
|
||||||
|
action: 'refund.create',
|
||||||
|
entityType: 'Deposit',
|
||||||
|
entityQboId: deposit.Id,
|
||||||
|
status: 'success',
|
||||||
|
requestExcerpt: requestSummary,
|
||||||
|
responseExcerpt: `Deposit ${deposit.Id} created, total $${Number(deposit.TotalAmt).toFixed(2)}`
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`✅ QBO Refund recorded: Deposit ${deposit.Id} — ${requestSummary}`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: deposit.Id,
|
||||||
|
txnDate: deposit.TxnDate,
|
||||||
|
totalAmt: Number(deposit.TotalAmt),
|
||||||
|
vendorName,
|
||||||
|
depositAccountName: depositAcct.name,
|
||||||
|
categoryName: categoryAcct.name
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Aktualisiert eine bestehende QBO Purchase (Expense).
|
* Aktualisiert eine bestehende QBO Purchase (Expense).
|
||||||
* QBO erfordert ein VOLLSTÄNDIGES Update — die komplette Line-Liste muss
|
* QBO erfordert ein VOLLSTÄNDIGES Update — die komplette Line-Liste muss
|
||||||
@@ -1268,6 +1406,7 @@ module.exports = {
|
|||||||
createVendor,
|
createVendor,
|
||||||
createExpense,
|
createExpense,
|
||||||
updateExpense,
|
updateExpense,
|
||||||
|
createRefund,
|
||||||
listExpenses,
|
listExpenses,
|
||||||
|
|
||||||
// Phase 2 Lieferung 3
|
// Phase 2 Lieferung 3
|
||||||
|
|||||||
Reference in New Issue
Block a user