How To Sum Multiple Fields of Related Child Records in a Parent Record

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

  1. RelatedTimesheets = zoho.crm.getRelatedRecords("Timesheets","Pay_Periods",payperiodId.toLong());
  2. //info RelatedTimesheets;

  3. totalHours = 0.0;

  4. totalPay = 0.0;

  5. totalBonus = 0.0;

  6. totalReward = 0.0;

  7. for each  ele in RelatedTimesheets

  8. {

  9. tsHours = ifnull(ele.get("Approved_Hours"),"0.0").toDecimal();

  10. totalHours = totalHours + tsHours;

  11. tsPay = ifnull(ele.get("Pay"),"0.0").toDecimal();

  12. totalPay = totalPay + tsPay;

  13. tsBonus = ifnull(ele.get("Bonus"),"0.0").toDecimal();

  14. totalBonus = totalBonus + tsBonus;

  15. tsReward = ifnull(ele.get("Reward"),"0.0").toDecimal();

  16. totalReward = totalReward + tsReward;

  17. }

  18. mp = Map();

  19. mp.put("Total_Hours",totalHours);

  20. mp.put("Total_Pay",totalPay);

  21. mp.put("Total_Bonuses",totalBonus);

  22. mp.put("Total_Rewards",totalReward);

  23. update = zoho.crm.updateRecord("Pay_Periods",payperiodId.toLong(),mp);

  24. info mp;

  25. info update;