🌊 Automate field population and total calculation when when an item is set or changed.
1. Overview
This Interaction is used to auto-populate fields, calculate subrecord totals, and update record totals on setting or changing of Item.
2. Example
In the following example, the function automates the process of populating subrecord fields, performing subrecord-level total calculations, and updating record-level totals when an "Item" is set or changed within the context of recurring- services.
"recurring-services" - subrecord internalId
463908 - Items recordId
34148 - Xero Tax Rate recodId (default)
async function handler(C) {
const index = C.getEventPayload().index;
const value = C.getSubValueBasedOnIndex("recurring-services", index);
const itemId = value.item[0];
const quantity = value.quantity;
const rate = value.rate;
function getParentUpdates({ net, tax, total }) {
const lineValues = C.state.subValues["recurring-services"];
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) {
const entry = await C.api.getEntry({
id: [itemId],
responseType: "iov",
recordId: 463908,
});
// console.log("items entry: ", entry);
let effectiveTax = 0;
let taxRateSelectValue = [];
try {
taxRateSelectValue = JSON.parse(entry["tax-rate"]);
const taxRateEntryId = taxRateSelectValue[0];
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 {}
const net = (quantity || 0) * +(entry.rate || 0);
const tax = (effectiveTax / 100) * net;
const total = net + tax;
const updatedLineValues = C.updateSubValueBasedOnIndex(
"recurring-services",
index,
{
description: entry.description,
rate: +entry.rate,
"tax-rate": taxRateSelectValue,
net,
tax,
total,
}
);
// merged return value
const returnValue = C.mergeAll(
updatedLineValues,
getParentUpdates({ net, tax, total })
);
// console.log("return value:", returnValue);
return returnValue;
}
const updatedValues = C.updateSubValueBasedOnIndex(
"recurring-services",
index,
{
description: "",
rate: null,
frequency: [],
"tax-rate": [],
quantity: 1,
net: null,
tax: null,
total: null,
}
);
const returnValue = C.mergeAll(
updatedValues,
getParentUpdates({ net: 0, tax: 0, total: 0 })
);
return returnValue;
}📌 Need Help?
