apply deposit to invoice
testtesttest
JavaScript
const invoices = [{
id: 'INV001',
amount: 100
}]
let invoiceTotal = 0
invoices.forEach(ele => {
invoiceTotal += ele.amount
})
console.log('invoice value = ' + invoiceTotal)
const balanceTransactions = [{
id: 'JNL001',
type: 'transaction',
amount: 100
},
{
id: 'JNL002',
type: 'transaction',
amount: -100
},
{
id: 'JNL003',
type: 'transaction',
amount: 100
},
{
id: 'JNL004',
type: 'transaction',
amount: -100
},
//the transaction that bears the invoice
{
id: 'JNL005',
type: 'transaction',
amount: 130
},
//this transaction will be ignored
{
id: 'JNL006',
type: 'transaction',
amount: 100
}
]
//cumsum
let sum = 0;
let cumulativeSum = []
let balance = 0
balanceTransactions.map((e) => {
sum = sum + parseFloat(e.amount);
cumulativeSum.push(parseFloat((parseFloat(sum)).toFixed(2)));
balance += parseFloat(e.amount)
})
if (balance < invoiceTotal) throw 'insufficient balance'
console.log('cumsum result: ' + cumulativeSum)
//find the index of the last applying transaction
function findIndexAfter(arr, n) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= n && arr.slice(i + 1).every((element) => element > n)) {
return i;
}
}
return -1;
}
const tailIndex = findIndexAfter(cumulativeSum, invoiceTotal);
console.log('here is the last transaction that is going to be assigned to the invoice = ' + tailIndex)
//now distribute invoice total to transactions
for (let i = 0; i <= tailIndex; i++) {
let transaction = balanceTransactions[i]
let appliedValue = i === tailIndex ? invoiceTotal : transaction.amount
invoiceTotal -= appliedValue
console.log(`doc ${transaction.id}, before apply ${transaction.amount}, appliedValue ${appliedValue}`)
}