+ # Get all the budgets totals in as few queries as possible
+ my $hr_budget_spent = $dbh->selectall_hashref(qq|
+ SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
+ SUM( COALESCE(unitprice_tax_included, ecost_tax_included) * quantity ) AS budget_spent
+ FROM aqorders JOIN aqbudgets USING (budget_id)
+ WHERE quantityreceived > 0 AND datecancellationprinted IS NULL
+ GROUP BY budget_id
+ |, 'budget_id');
+ my $hr_budget_ordered = $dbh->selectall_hashref(qq|
+ SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
+ SUM(ecost_tax_included * quantity) AS budget_ordered
+ FROM aqorders JOIN aqbudgets USING (budget_id)
+ WHERE quantityreceived = 0 AND datecancellationprinted IS NULL
+ GROUP BY budget_id
+ |, 'budget_id');
+ my $hr_budget_spent_shipment = $dbh->selectall_hashref(qq|
+ SELECT shipmentcost_budgetid as budget_id,
+ SUM(shipmentcost) as shipmentcost
+ FROM aqinvoices
+ WHERE closedate IS NOT NULL
+ GROUP BY shipmentcost_budgetid
+ |, 'budget_id');
+ my $hr_budget_ordered_shipment = $dbh->selectall_hashref(qq|
+ SELECT shipmentcost_budgetid as budget_id,
+ SUM(shipmentcost) as shipmentcost
+ FROM aqinvoices
+ WHERE closedate IS NULL
+ GROUP BY shipmentcost_budgetid
+ |, 'budget_id');
+
+ my $recursiveAdd;
+ $recursiveAdd = sub {
+ my ($budget, $parent) = @_;
+
+ foreach my $child (@{$budget->{children}}){
+ $recursiveAdd->($child, $budget);
+ }
+
+ $budget->{budget_spent} += $hr_budget_spent->{$budget->{budget_id}}->{budget_spent};
+ $budget->{budget_spent} += $hr_budget_spent_shipment->{$budget->{budget_id}}->{shipmentcost};
+ $budget->{budget_ordered} += $hr_budget_ordered->{$budget->{budget_id}}->{budget_ordered};
+ $budget->{budget_ordered} += $hr_budget_ordered_shipment->{$budget->{budget_id}}->{shipmentcost};
+
+ $budget->{total_spent} += $budget->{budget_spent};
+ $budget->{total_ordered} += $budget->{budget_ordered};
+
+ if ($parent) {
+ $parent->{total_spent} += $budget->{total_spent};
+ $parent->{total_ordered} += $budget->{total_ordered};
+ }
+ };
+