How To Sum Multiple Fields of Related Child Records in a Parent Record
I have a module called Pay Periods, and each Pay Period links to multiple Timesheets. Within each Timesheet, there are the following fields that I would like to aggregate in the associated Pay Period record. They are "Approved Hours", "Pay", "Bonus" and "Reward".
Using
this tutorial, I was able to come up with the following Deluge script. When I created the script originally just to sum the "Approved Hours", it worked for a single associated Timesheet. But now I can't seem to get it to work for all 4 of the fields with the related Timesheets.
I'm triggering the Action from a Workflow Rule linked to the Pay Period module, every time the Pay Period record is updated.
Argument: payperiodId = Pay Period ID
- RelatedTimesheets = zoho.crm.getRelatedRecords("Timesheets","Pay_Periods",payperiodId.toLong());
-
//info RelatedTimesheets;
totalHours = 0.0;
totalPay = 0.0;
totalBonus = 0.0;
totalReward = 0.0;
for each ele in RelatedTimesheets
{
tsHours = ifnull(ele.get("Approved_Hours"),"0.0").toDecimal();
totalHours = totalHours + tsHours;
tsPay = ifnull(ele.get("Pay"),"0.0").toDecimal();
totalPay = totalPay + tsPay;
tsBonus = ifnull(ele.get("Bonus"),"0.0").toDecimal();
totalBonus = totalBonus + tsBonus;
tsReward = ifnull(ele.get("Reward"),"0.0").toDecimal();
totalReward = totalReward + tsReward;
}
mp = Map();
mp.put("Total_Hours",totalHours);
mp.put("Total_Pay",totalPay);
mp.put("Total_Bonuses",totalBonus);
mp.put("Total_Rewards",totalReward);
update = zoho.crm.updateRecord("Pay_Periods",payperiodId.toLong(),mp);
info mp;
info update;