🔀 Update parents records on change in subrecords easily.
1. Overview
This interaction calculates subrecord net total, tax total, and total, and updates parent record totals on changes in quantity, rate, or tax rate.
2. Example
This example demonstrates how on change of an item within the 'xero-order-items' subrecord, the function calculates the net, tax, and total values based on the selected 'Tax Rate.' It then updates these values in the subrecord and recalculates the parent record's 'Net Total,' 'Tax Total,' and 'Total.'"
async function handler(C) {
const index = C.getEventPayload().index;
const value = C.getSubValueBasedOnIndex("xero-order-items", index);
const itemId = value.item[0];
const quantity = value.quantity;
const rate = value.rate;
function getParentUpdates({ net, tax, total }) {
const lineValues = C.state.subValues["xero-order-items"];
const newNet =
lineValues
.map((v, i) => (i === index ? 0 : +v.net))
.reduce((agg, v) => v + agg, 0) + net;
const newTaxTotal =
lineValues
.map((v, i) => (i === index ? 0 : +v.tax))
.reduce((agg, v) => v + agg, 0) + tax;
const newTotal =
lineValues
.map((v, i) => (i === index ? 0 : +v.total))
.reduce((agg, v) => v + agg, 0) + total;
return C.mergeAll(
C.setValue("net-total", newNet),
C.setValue("tax-total", newTaxTotal),
C.setValue("total", newTotal)
);
}
if (itemId !== undefined && itemId !== null) {
let effectiveTax = 0;
try {
const taxRateEntryId = value["tax-rate"][0];
// console.log("tax rate id:", taxRateEntryId)
if (taxRateEntryId) {
const taxRateEntry = await C.api.getEntry({
id: [taxRateEntryId],
responseType: "iov",
recordId: 34148,
});
// console.log("tax rate entry id:", taxRateEntry);
effectiveTax = +taxRateEntry["effective-tax-rate"];
}
} catch {}
console.log("effective tax:", effectiveTax)
const net = quantity * rate;
const tax = (effectiveTax / 100) * net;
const total = net + tax;
const updatedValues = C.updateSubValueBasedOnIndex(
"xero-order-items",
index,
{
net,
tax,
total,
}
);
const returnValue = C.mergeAll(
updatedValues,
getParentUpdates({ net, tax, total })
);
// console.log("return value:", returnValue)
return returnValue;
}
const updatedValues = C.updateSubValueBasedOnIndex(
"xero-order-items",
index,
{
net: null,
}
);
const returnValue = C.mergeAll(
updatedValues,
getParentUpdates({ net: 0, tax: 0, total: 0 })
);
// console.log("return value:", returnValue)
return returnValue;
}📌 Need Help?
