+
+ my @results = ();
+ while ( my $data = $sth->fetchrow_hashref ) {
+ push( @results, $data );
+ }
+ return @results;
+}
+
+=head2 GetBudgetsByActivity
+
+ &GetBudgetsByActivity( $budget_period_active );
+
+Get all active or inactive budgets, depending of the value
+of the parameter.
+
+1 = active
+0 = inactive
+
+=cut
+
+# --------------------------------------------------------------------
+sub GetBudgetsByActivity {
+ my ( $budget_period_active ) = @_;
+ my $dbh = C4::Context->dbh;
+ my $query = "
+ SELECT DISTINCT b.*
+ FROM aqbudgetperiods bp
+ INNER JOIN aqbudgets b
+ ON bp.budget_period_id = b.budget_period_id
+ WHERE bp.budget_period_active=?
+ ";
+ my $sth = $dbh->prepare($query);
+ $sth->execute( $budget_period_active );
+ my @results = ();
+ while ( my $data = $sth->fetchrow_hashref ) {
+ push( @results, $data );
+ }
+ return @results;
+}
+# --------------------------------------------------------------------
+
+=head2 GetBudgetsReport
+
+ &GetBudgetsReport( [$activity] );
+
+Get all but cancelled orders for all funds.
+
+If the optionnal activity parameter is passed, returns orders for active/inactive budgets only.
+
+active = 1
+inactive = 0
+
+Returns an array of hashrefs.
+
+=cut
+
+sub GetBudgetsReport {
+ my ($activity) = @_;
+ my $dbh = C4::Context->dbh;
+ my $query = '
+ SELECT o.*, b.budget_name
+ FROM aqbudgetperiods bp
+ INNER JOIN aqbudgets b
+ ON bp.budget_period_id = b.budget_period_id
+ INNER JOIN aqorders o
+ ON b.budget_id = o.budget_id ';
+ if($activity ne ''){
+ $query .= 'WHERE bp.budget_period_active=? ';
+ }
+ $query .= 'AND (o.orderstatus != "cancelled")
+ ORDER BY b.budget_name';
+
+ my $sth = $dbh->prepare($query);
+ if($activity ne ''){
+ $sth->execute($activity);
+ }
+ else{
+ $sth->execute;
+ }
+ my @results = ();
+ while ( my $data = $sth->fetchrow_hashref ) {
+ push( @results, $data );
+ }
+ return @results;
+}
+
+=head2 GetBudgetByCode
+
+ my $budget = &GetBudgetByCode($budget_code);
+
+Retrieve all aqbudgets fields as a hashref for the budget that has
+given budget_code
+
+=cut
+
+sub GetBudgetByCode {
+ my ( $budget_code ) = @_;
+
+ my $dbh = C4::Context->dbh;
+ my $query = qq{
+ SELECT aqbudgets.*
+ FROM aqbudgets
+ JOIN aqbudgetperiods USING (budget_period_id)
+ WHERE budget_code = ?
+ ORDER BY budget_period_active DESC, budget_id DESC
+ LIMIT 1
+ };
+ my $sth = $dbh->prepare( $query );
+ $sth->execute( $budget_code );
+ return $sth->fetchrow_hashref;
+}
+
+=head2 GetBudgetHierarchySpent
+
+ my $spent = GetBudgetHierarchySpent( $budget_id );
+
+Gets the total spent of the level and sublevels of $budget_id
+
+=cut
+
+sub GetBudgetHierarchySpent {
+ my ( $budget_id ) = @_;
+ my $dbh = C4::Context->dbh;
+ my $children_ids = $dbh->selectcol_arrayref(q|
+ SELECT budget_id
+ FROM aqbudgets
+ WHERE budget_parent_id = ?
+ |, {}, $budget_id );
+
+ my $total_spent = GetBudgetSpent( $budget_id );
+ for my $child_id ( @$children_ids ) {
+ $total_spent += GetBudgetHierarchySpent( $child_id );