53 lines
1.5 KiB
JavaScript
53 lines
1.5 KiB
JavaScript
import Dinero from "dinero.js";
|
|
import { logImEXEvent } from "../../firebase/firebase.utils";
|
|
|
|
export const CalculateInvoiceTotal = (invoice) => {
|
|
logImEXEvent("invoice_calculate_total");
|
|
|
|
const {
|
|
total,
|
|
|
|
invoicelines,
|
|
federal_tax_rate,
|
|
local_tax_rate,
|
|
state_tax_rate,
|
|
} = invoice;
|
|
//TODO Determine why this recalculates so many times.
|
|
let subtotal = Dinero({ amount: 0 });
|
|
let federalTax = Dinero({ amount: 0 });
|
|
let stateTax = Dinero({ amount: 0 });
|
|
let localTax = Dinero({ amount: 0 });
|
|
if (!!!invoicelines) return null;
|
|
invoicelines.forEach((i) => {
|
|
if (!!i) {
|
|
const itemTotal = Dinero({
|
|
amount: Math.round((i.actual_cost || 0) * 100) || 0,
|
|
}).multiply(i.quantity || 1);
|
|
subtotal = subtotal.add(itemTotal);
|
|
if (i.applicable_taxes.federal) {
|
|
federalTax = federalTax.add(
|
|
itemTotal.percentage(federal_tax_rate || 0)
|
|
);
|
|
}
|
|
if (i.applicable_taxes.state)
|
|
stateTax = stateTax.add(itemTotal.percentage(state_tax_rate || 0));
|
|
if (i.applicable_taxes.local)
|
|
localTax = localTax.add(itemTotal.percentage(local_tax_rate || 0));
|
|
}
|
|
});
|
|
|
|
const invoiceTotal = Dinero({ amount: Math.round((total || 0) * 100) });
|
|
const enteredTotal = subtotal.add(federalTax).add(stateTax).add(localTax);
|
|
const discrepancy = enteredTotal.subtract(invoiceTotal);
|
|
|
|
return {
|
|
subtotal,
|
|
federalTax,
|
|
stateTax,
|
|
localTax,
|
|
enteredTotal,
|
|
invoiceTotal,
|
|
discrepancy,
|
|
};
|
|
};
|