Bug 7162; Factorize code for order cancellation (QA fixes)
[koha.git] / C4 / Budgets.pm
index ddb65cc..1a7f7e4 100644 (file)
@@ -13,50 +13,58 @@ package C4::Budgets;
 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along with
-# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
-# Suite 330, Boston, MA  02111-1307 USA
+# You should have received a copy of the GNU General Public License along
+# with Koha; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
 use strict;
+#use warnings; FIXME - Bug 2505
 use C4::Context;
-use C4::Dates qw(format_date format_date_in_iso);
+use Koha::Database;
 use C4::Debug;
-
 use vars qw($VERSION @ISA @EXPORT);
 
 BEGIN {
        # set the version for version checking
-       $VERSION = 3.01;
+    $VERSION = 3.07.00.049;
        require Exporter;
        @ISA    = qw(Exporter);
        @EXPORT = qw(
 
         &GetBudget
+        &GetBudgetByOrderNumber
+        &GetBudgetByCode
         &GetBudgets
         &GetBudgetHierarchy
            &AddBudget
         &ModBudget
         &DelBudget
         &GetBudgetSpent
+        &GetBudgetOrdered
+        &GetBudgetName
         &GetPeriodsCount
+        GetBudgetHierarchySpent
+        GetBudgetHierarchyOrdered
+
+        &GetBudgetUsers
+        &ModBudgetUsers
+        &CanUserUseBudget
+        &CanUserModifyBudget
 
            &GetBudgetPeriod
         &GetBudgetPeriods
         &ModBudgetPeriod
+        &AddBudgetPeriod
            &DelBudgetPeriod
 
-           &GetBudgetPeriodsDropbox
-        &GetBudgetSortDropbox
-           &GetAuthcatDropbox
-        &GetAuthvalueDropbox
-        &GetBudgetPermDropbox
-
         &ModBudgetPlan
+
         &GetCurrency
         &GetCurrencies
         &ModCurrencies
         &ConvertCurrency
-        &GetBudgetsPlanCell
+        
+               &GetBudgetsPlanCell
         &AddBudgetPlanValue
         &GetBudgetAuthCats
         &BudgetHasChildren
@@ -71,19 +79,14 @@ BEGIN {
 # ----------------------------BUDGETS.PM-----------------------------";
 
 
+=head1 FUNCTIONS ABOUT BUDGETS
+
+=cut
+
 sub HideCols {
     my ( $authcat, @hide_cols ) = @_;
     my $dbh = C4::Context->dbh;
 
-=c
-    my $sth = $dbh->prepare(
-        qq|
-        UPDATE aqbudgets_planning
-        SET display = 1 where authcat =  ? |
-    );
-    $sth->execute( $authcat );
-=cut
-
     my $sth1 = $dbh->prepare(
         qq|
         UPDATE aqbudgets_planning SET display = 0 
@@ -130,6 +133,13 @@ sub CheckBudgetParentPerm {
     return 0;
 }
 
+sub AddBudgetPeriod {
+    my ($budgetperiod) = @_;
+    return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
+
+    my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
+    return $resultset->create($budgetperiod)->id;
+}
 # -------------------------------------------------------------------
 sub GetPeriodsCount {
     my $dbh = C4::Context->dbh;
@@ -174,7 +184,6 @@ sub BudgetHasChildren {
         WHERE budget_parent_id = ?   | );
     $sth->execute( $budget_id );
     my $sum = $sth->fetchrow_hashref;
-    $sth->finish;
     return $sum->{'sum'};
 }
 
@@ -228,7 +237,6 @@ sub GetBudgetsPlanCell {
                 ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR
                 (aqbudgets.sort2_authcat = ? AND sort2 =?))    |
         );
-        $sth->{TraceLevel} = 2;
         $sth->execute(  $cell->{'budget_id'},
                         $budget->{'sort1_authcat'},
                         $cell->{'authvalue'},
@@ -239,7 +247,7 @@ sub GetBudgetsPlanCell {
     $actual = $sth->fetchrow_array;
 
     # get the estimated amount
-    my $sth = $dbh->prepare( qq|
+    $sth = $dbh->prepare( qq|
 
         SELECT estimated_amount AS estimated, display FROM aqbudgets_planning
             WHERE budget_period_id = ? AND
@@ -304,63 +312,73 @@ sub GetBudgetSpent {
        my ($budget_id) = @_;
        my $dbh = C4::Context->dbh;
        my $sth = $dbh->prepare(qq|
-        SELECT SUM(ecost *  quantity  ) AS sum FROM aqorders
+        SELECT SUM( COALESCE(unitprice, ecost) * quantity ) AS sum FROM aqorders
             WHERE budget_id = ? AND
-            datecancellationprinted IS NULL 
+            quantityreceived > 0 AND
+            datecancellationprinted IS NULL
     |);
-
        $sth->execute($budget_id);
        my $sum =  $sth->fetchrow_array;
-#      $sum =  sprintf  "%.2f", $sum;
-       return $sum;
-}
 
-# -------------------------------------------------------------------
-sub GetBudgetPermDropbox {
-       my ($perm) = @_;
-       my %labels;
-       $labels{'0'} = 'None';
-       $labels{'1'} = 'Owner';
-       $labels{'2'} = 'Library';
-       my $radio = CGI::scrolling_list(
-               -name      => 'budget_permission',
-               -values    => [ '0', '1', '2' ],
-               -default   => $perm,
-               -labels    => \%labels,
-               -size    => 1,
-       );
-       return $radio;
+    $sth = $dbh->prepare(qq|
+        SELECT SUM(shipmentcost) AS sum
+        FROM aqinvoices
+        WHERE shipmentcost_budgetid = ?
+          AND closedate IS NOT NULL
+    |);
+    $sth->execute($budget_id);
+    my ($shipmentcost_sum) = $sth->fetchrow_array;
+    $sum += $shipmentcost_sum;
+
+       return $sum;
 }
 
 # -------------------------------------------------------------------
-sub GetAuthcatDropbox  {
-       my ($name, $default ) = @_;
-       my @authorised_values;
-       my $value;
+sub GetBudgetOrdered {
+       my ($budget_id) = @_;
        my $dbh = C4::Context->dbh;
        my $sth = $dbh->prepare(qq|
-               SELECT distinct(category)
-            FROM authorised_values WHERE category LIKE 'Asort%'
-            ORDER BY lib |
-       );
-       $sth->execute();
+        SELECT SUM(ecost *  quantity) AS sum FROM aqorders
+            WHERE budget_id = ? AND
+            quantityreceived = 0 AND
+            datecancellationprinted IS NULL
+    |);
+       $sth->execute($budget_id);
+       my $sum =  $sth->fetchrow_array;
 
-       push @authorised_values, '';
-       while (my $value = $sth->fetchrow_array) {
-               push @authorised_values, $value;
-       }
+    $sth = $dbh->prepare(qq|
+        SELECT SUM(shipmentcost) AS sum
+        FROM aqinvoices
+        WHERE shipmentcost_budgetid = ?
+          AND closedate IS NULL
+    |);
+    $sth->execute($budget_id);
+    my ($shipmentcost_sum) = $sth->fetchrow_array;
+    $sum += $shipmentcost_sum;
 
-    my $budget_authcat_dropbox = CGI::scrolling_list(
-        -name     => $name,
-        -values   => \@authorised_values,
-        -override => 1,
-        -size     => 1,
-        -default  => $default,
-        -multiple => 0,
-        -tabindex => 1,
-        -id       => $name,
-    );
-       return $budget_authcat_dropbox;
+       return $sum;
+}
+
+=head2 GetBudgetName
+
+  my $budget_name = &GetBudgetName($budget_id);
+
+get the budget_name for a given budget_id
+
+=cut
+
+sub GetBudgetName {
+    my ( $budget_id ) = @_;
+    my $dbh         = C4::Context->dbh;
+    my $sth         = $dbh->prepare(
+        qq|
+        SELECT budget_name
+        FROM aqbudgets
+        WHERE budget_id = ?
+    |);
+
+    $sth->execute($budget_id);
+    return $sth->fetchrow_array;
 }
 
 # -------------------------------------------------------------------
@@ -383,86 +401,15 @@ sub GetBudgetAuthCats  {
     return \@auth_cats_loop;
 }
 
-# -------------------------------------------------------------------
-sub GetAuthvalueDropbox {
-       my ( $name, $authcat, $default ) = @_;
-       my @authorised_values;
-       my %authorised_lib;
-       my $value;
-       my $dbh = C4::Context->dbh;
-       my $sth = $dbh->prepare(
-               "SELECT authorised_value,lib
-            FROM authorised_values
-            WHERE category = ?
-            ORDER BY  lib"
-       );
-       $sth->execute( $authcat );
-
-       push @authorised_values, '';
-       while (my ($value, $lib) = $sth->fetchrow_array) {
-               push @authorised_values, $value;
-               $authorised_lib{$value} = $lib;
-       }
-
-    return 0 if keys(%authorised_lib) == 0;
-
-    my $budget_authvalue_dropbox = CGI::scrolling_list(
-        -values   => \@authorised_values,
-        -labels   => \%authorised_lib,
-        -default  => $default,
-        -override => 1,
-        -size     => 1,
-        -multiple => 0,
-        -name     => $name,
-        -id       => $name,
-    );
-
-    return $budget_authvalue_dropbox
-}
-
-# -------------------------------------------------------------------
-sub GetBudgetPeriodsDropbox {
-    my ($budget_period_id) = @_;
-       my %labels;
-       my @values;
-       my ($active, $periods) = GetBudgetPeriods();
-       foreach my $r (@$periods) {
-               $labels{"$r->{budget_period_id}"} = $r->{budget_period_description};
-               push @values, $r->{budget_period_id};
-       }
-
-       # if no buget_id is passed then its an add
-       my $budget_period_dropbox = CGI::scrolling_list(
-               -name    => 'budget_period_id',
-               -values  => \@values,
-               -default => $budget_period_id ? $budget_period_id :  $active,
-               -size    => 1,
-               -labels  => \%labels,
-       );
-       return $budget_period_dropbox;
-}
-
 # -------------------------------------------------------------------
 sub GetBudgetPeriods {
-       my $dbh = C4::Context->dbh;
-       my $sth = $dbh->prepare(qq|
-        SELECT *
-         FROM aqbudgetperiods
-         ORDER BY budget_period_startdate, budget_period_enddate |
-       );
-       $sth->execute();
-       my @results;
-       my $active;
-       while (my $data = $sth->fetchrow_hashref) {
-               if ($data->{'budget_period_active'} == 1) {
-                       $active = $data->{'budget_period_id'};
-               }
-               push(@results, $data);
-       }
-       $sth->finish;
-       return ($active, \@results);
-}
+       my ($filters,$orderby) = @_;
 
+    my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
+    $rs = $rs->search( $filters, { order_by => $orderby } );
+    $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
+    return [ $rs->all ];
+}
 # -------------------------------------------------------------------
 sub GetBudgetPeriod {
        my ($budget_period_id) = @_;
@@ -471,7 +418,7 @@ sub GetBudgetPeriod {
        my $total = 0;
        ## get information about the record that will be deleted
        my $sth;
-       if ($budget_period_id gt 0) {
+       if ($budget_period_id) {
                $sth = $dbh->prepare( qq|
               SELECT      *
                 FROM aqbudgetperiods
@@ -487,12 +434,11 @@ sub GetBudgetPeriod {
                $sth->execute();
        }
        my $data = $sth->fetchrow_hashref;
-       $sth->finish;
        return $data;
 }
 
 # -------------------------------------------------------------------
-sub DelBudgetPeriod() {
+sub DelBudgetPeriod{
        my ($budget_period_id) = @_;
        my $dbh = C4::Context->dbh;
          ; ## $total = number of records linked to the record that must be deleted
@@ -500,73 +446,57 @@ sub DelBudgetPeriod() {
 
        ## get information about the record that will be deleted
        my $sth = $dbh->prepare(qq|
-               SELECT     budget_period_id
-                 , budget_period_startdate
-                 , budget_period_enddate
-                 , budget_period_amount
-                 , budget_period_ref
-                 , budget_period_description
+               DELETE 
          FROM aqbudgetperiods
          WHERE budget_period_id=? |
        );
-       $sth->execute($budget_period_id);
-       my $data = $sth->fetchrow_hashref;
-       $sth->finish;
+       return $sth->execute($budget_period_id);
 }
 
 # -------------------------------------------------------------------
-sub ModBudgetPeriod() {
-       my ($budget_period_id) = @_;
-       my $dbh = C4::Context->dbh
-         ; ## $total = number of records linked to the record that must be deleted       my $total = 0;
+sub ModBudgetPeriod {
+    my ($budget_period) = @_;
+    my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period);
+    return unless($result);
 
-       ## get information about the record that will be deleted
-       my $sth = $dbh->prepare("
-           SELECT     budget_period_id
-                 , budget_period_startdate
-                 , budget_period_enddate
-                 , budget_period_amount
-                 , budget_period_ref
-                 , budget_period_description
-        FROM aqbudgetperiods
-        WHERE budget_period_id=?;"
-       );
-       $sth->execute($budget_period_id);
-       my $data = $sth->fetchrow_hashref;
-       $sth->finish;
+    $result = $result->update($budget_period);
+    return $result->in_storage;
 }
 
 # -------------------------------------------------------------------
 sub GetBudgetHierarchy {
-       my ($budget_period_id, $branchcode, $owner) = @_;
-       my @bind_params;
-       my $dbh   = C4::Context->dbh;
-       my $query = qq|
-                    SELECT aqbudgets.*
-                    FROM aqbudgets
-                    JOIN aqbudgetperiods USING (budget_period_id)
-                    WHERE budget_period_active=1 |;
+    my ( $budget_period_id, $branchcode, $owner ) = @_;
+    my @bind_params;
+    my $dbh   = C4::Context->dbh;
+    my $query = qq|
+                    SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description
+                    FROM aqbudgets 
+                    JOIN aqbudgetperiods USING (budget_period_id)|;
+                        
+       my @where_strings;
     # show only period X if requested
     if ($budget_period_id) {
-        $query .= "AND aqbudgets.budget_period_id = ?";
+        push @where_strings," aqbudgets.budget_period_id = ?";
         push @bind_params, $budget_period_id;
     }
        # show only budgets owned by me, my branch or everyone
     if ($owner) {
         if ($branchcode) {
-            $query .= " AND (budget_owner_id = ? OR budget_branchcode = ? OR (budget_branchcode IS NULL AND budget_owner_id IS NULL))";
-            push @bind_params, $owner;
-            push @bind_params, $branchcode;
+            push @where_strings,
+            qq{ (budget_owner_id = ? OR budget_branchcode = ? OR ((budget_branchcode IS NULL or budget_branchcode="") AND (budget_owner_id IS NULL OR budget_owner_id="")))};
+            push @bind_params, ( $owner, $branchcode );
         } else {
-            $query .= ' AND budget_owner_id = ? OR budget_owner_id IS NULL';
+            push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") ';
             push @bind_params, $owner;
         }
     } else {
         if ($branchcode) {
-            $query .= " AND (budget_branchcode =? or budget_branchcode is NULL)";
+            push @where_strings," (budget_branchcode =? or budget_branchcode is NULL)";
             push @bind_params, $branchcode;
         }
     }
+       $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings;
+       $debug && warn $query,join(",",@bind_params);
        my $sth = $dbh->prepare($query);
        $sth->execute(@bind_params);
        my $results = $sth->fetchall_arrayref({});
@@ -593,8 +523,8 @@ sub GetBudgetHierarchy {
        }
 
        # look for top parents 1st
-       my @sort;
-       my ($i, $depth_count) = 0;
+       my (@sort, $depth_count);
+       ($i, $depth_count) = 0;
        while (1) {
                my $children = 0;
                foreach my $r (@res) {
@@ -608,9 +538,8 @@ sub GetBudgetHierarchy {
 
                                        # add indent
                                        my $depth = $r->{depth} * 2;
-                                       my $space = pack "A[$depth]";
-                                       $r->{budget_code_indent} = $space . $r->{budget_code};
-                                       $r->{budget_name_indent} = $space . $r->{budget_name};
+                                       $r->{budget_code_indent} = $r->{budget_code};
+                                       $r->{budget_name_indent} = $r->{budget_name};
                                        foreach my $r3 (@sort) {
                                                if ($r3->{budget_id} == $r->{budget_parent_id}) {
                                                        $parent = $i2;
@@ -622,7 +551,7 @@ sub GetBudgetHierarchy {
                                        $r->{budget_code_indent} = $r->{budget_code};
                                        $r->{budget_name_indent} = $r->{budget_name};
                                }
-
+                
                                if (defined $parent) {
                                        splice @sort, ($parent + 1), 0, $r;
                                } else {
@@ -636,125 +565,34 @@ sub GetBudgetHierarchy {
                last if $children == 0;
        }
 
-# add budget-percent and allocation, and flags for html-template
-       foreach my $r (@sort) {
-               my $subs_href = $r->{'child'};
-        my @subs_arr = @$subs_href if defined $subs_href;
-
-        my $moo = $r->{'budget_code_indent'};
-        $moo =~ s/\ /\&nbsp\;/g;
-        $r->{'budget_code_indent'} =  $moo;
-
-        my $moo = $r->{'budget_name_indent'};
-        $moo =~ s/\ /\&nbsp\;/g;
-        $r->{'budget_name_indent'} = $moo;
-
-        $r->{'budget_spent'}       = GetBudgetSpent( $r->{'budget_id'} );
 
-        $r->{'budget_amount_total'} =  $r->{'budget_amount'} + $r->{'budget_amount_sublevel'}  ;
-
-        # foreach sub-levels
-        my $unalloc_count ;
-
-               foreach my $sub (@subs_arr) {
-                       my $sub_budget = GetBudget($sub);
-
-                       $r->{budget_spent_sublevel} +=    GetBudgetSpent( $sub_budget->{'budget_id'} );
-                       $unalloc_count +=   $sub_budget->{'budget_amount'} + $sub_budget->{'budget_amount_sublevel'};
-               }
-
-           $r->{budget_unalloc_sublevel} =  $r->{'budget_amount_sublevel'}   -   $unalloc_count;
-
-        if ( scalar  @subs_arr == 0  && $r->{budget_amount_sublevel} > 0 ) {
-            $r->{warn_no_subs} = 1;
-        }
-       }
-       return \@sort;
+    foreach my $budget (@sort) {
+        $budget->{budget_spent}   = GetBudgetSpent( $budget->{budget_id} );
+        $budget->{budget_ordered} = GetBudgetOrdered( $budget->{budget_id} );
+        $budget->{total_spent} = GetBudgetHierarchySpent( $budget->{budget_id} );
+        $budget->{total_ordered} = GetBudgetHierarchyOrdered( $budget->{budget_id} );
+    }
+    return \@sort;
 }
 
 # -------------------------------------------------------------------
+
 sub AddBudget {
-my ($budget) = @_;
-my $dbh        = C4::Context->dbh;
-       my $query = qq|
-    INSERT INTO aqbudgets
-    SET budget_code         = ?,
-        budget_period_id    = ?,
-        budget_parent_id    = ?,
-        budget_name         = ?,
-        budget_branchcode   = ?,
-        budget_amount       = ?,
-        budget_amount_sublevel       = ?,
-        budget_encumb       = ?,
-        budget_expend       = ?,
-        budget_notes        = ?,
-        sort1_authcat       = ?,
-        sort2_authcat       = ?,
-        budget_owner_id     = ?,
-        budget_permission   = ?
-    |;
-       my $sth = $dbh->prepare($query);
-       $sth->execute(
-        $budget->{'budget_code'}        ? $budget->{'budget_code'} : undef,
-        $budget->{'budget_period_id'}   ? $budget->{'budget_period_id'} : undef,
-        $budget->{'budget_parent_id'}   ? $budget->{'budget_parent_id'} : undef,
-        $budget->{'budget_name'}        ? $budget->{'budget_name'} : undef,
-        $budget->{'budget_branchcode'}  ? $budget->{'budget_branchcode'} : undef,
-        $budget->{'budget_amount'}      ? $budget->{'budget_amount'} : undef,
-        $budget->{'budget_amount_sublevel'}      ? $budget->{'budget_amount_sublevel'} : undef,
-        $budget->{'budget_encumb'}      ? $budget->{'budget_encumb'} : undef,
-        $budget->{'budget_expend'}      ? $budget->{'budget_expend'} : undef,
-        $budget->{'budget_notes'}       ? $budget->{'budget_notes'} : undef,
-        $budget->{'sort1_authcat'}      ? $budget->{'sort1_authcat'} : undef,
-        $budget->{'sort2_authcat'}      ? $budget->{'sort2_authcat'} : undef,
-        $budget->{'budget_owner_id'}    ? $budget->{'budget_owner_id'} : undef,
-        $budget->{'budget_permission'}  ? $budget->{'budget_permission'} : undef,
-       );
-       $sth->finish;
+    my ($budget) = @_;
+    return unless ($budget);
+
+    my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
+    return $resultset->create($budget)->id;
 }
 
 # -------------------------------------------------------------------
 sub ModBudget {
     my ($budget) = @_;
-    my $dbh      = C4::Context->dbh;
-       my $query = qq|
-    UPDATE aqbudgets
-    SET budget_code         = ?,
-        budget_period_id    = ?,
-        budget_parent_id    = ?,
-        budget_name         = ?,
-        budget_branchcode   = ?,
-        budget_amount       = ?,
-        budget_amount_sublevel       = ?,
-        budget_encumb       = ?,
-        budget_expend       = ?,
-        budget_notes        = ?,
-        sort1_authcat       = ?,
-        sort2_authcat       = ?,
-        budget_owner_id     = ?,
-        budget_permission   = ?
-    WHERE budget_id = ?
-    |;
+    my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
+    return unless($result);
 
-       my $sth = $dbh->prepare($query);
-    $sth->execute(
-        $budget->{'budget_code'}        ? $budget->{'budget_code'} : undef,
-        $budget->{'budget_period_id'}   ? $budget->{'budget_period_id'} : undef,
-        $budget->{'budget_parent_id'}   ? $budget->{'budget_parent_id'} : undef,
-        $budget->{'budget_name'}        ? $budget->{'budget_name'} : undef,
-        $budget->{'budget_branchcode'}  ? $budget->{'budget_branchcode'} : undef,
-        $budget->{'budget_amount'}      ? $budget->{'budget_amount'} : undef,
-        $budget->{'budget_amount_sublevel'}      ? $budget->{'budget_amount_sublevel'} : undef,
-        $budget->{'budget_encumb'}      ? $budget->{'budget_encumb'} : undef,
-        $budget->{'budget_expend'}      ? $budget->{'budget_expend'} : undef,
-        $budget->{'budget_notes'}       ? $budget->{'budget_notes'} : undef,
-        $budget->{'sort1_authcat'}      ? $budget->{'sort1_authcat'} : undef,
-        $budget->{'sort2_authcat'}      ? $budget->{'sort2_authcat'} : undef,
-        $budget->{'budget_owner_id'}    ? $budget->{'budget_owner_id'} : undef,
-        $budget->{'budget_permission'}  ? $budget->{'budget_permission'} : undef,
-        $budget->{'budget_id'},
-    );
-    $sth->finish;
+    $result = $result->update($budget);
+    return $result->in_storage;
 }
 
 # -------------------------------------------------------------------
@@ -763,35 +601,22 @@ sub DelBudget {
        my $dbh         = C4::Context->dbh;
        my $sth         = $dbh->prepare("delete from aqbudgets where budget_id=?");
        my $rc          = $sth->execute($budget_id);
-       $sth->finish;
        return $rc;
 }
 
-=back
 
-=head2 FUNCTIONS ABOUT BUDGETS
+=head2 GetBudget
 
-=over 2
-
-=cut
-
-=head3 GetBudget
-
-=over 4
-
-&GetBudget($budget_id);
+  &GetBudget($budget_id);
 
 get a specific budget
 
-=back
-
 =cut
 
 # -------------------------------------------------------------------
 sub GetBudget {
     my ( $budget_id ) = @_;
     my $dbh = C4::Context->dbh;
-    my $query;
     my $query = "
         SELECT *
         FROM   aqbudgets
@@ -803,47 +628,302 @@ sub GetBudget {
     return $result;
 }
 
-=head3 GetBudgets
+=head2 GetBudgetByOrderNumber
 
-=over 4
+  &GetBudgetByOrderNumber($ordernumber);
 
-&GetBudget($budget_id);
+get a specific budget by order number
 
-gets all budgets
+=cut
+
+# -------------------------------------------------------------------
+sub GetBudgetByOrderNumber {
+    my ( $ordernumber ) = @_;
+    my $dbh = C4::Context->dbh;
+    my $query = "
+        SELECT aqbudgets.*
+        FROM   aqbudgets, aqorders
+        WHERE  ordernumber=?
+        AND    aqorders.budget_id = aqbudgets.budget_id
+        ";
+    my $sth = $dbh->prepare($query);
+    $sth->execute( $ordernumber );
+    my $result = $sth->fetchrow_hashref;
+    return $result;
+}
+
+=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 *
+        FROM aqbudgets
+        WHERE budget_code = ?
+        ORDER BY 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 );
 
-=back
+    my $total_spent = GetBudgetSpent( $budget_id );
+    for my $child_id ( @$children_ids ) {
+        $total_spent += GetBudgetHierarchySpent( $child_id );
+    }
+    return $total_spent;
+}
+
+=head2 GetBudgetHierarchyOrdered
+
+  my $ordered = GetBudgetHierarchyOrdered( $budget_id );
+
+Gets the total ordered of the level and sublevels of $budget_id
+
+=cut
+
+sub GetBudgetHierarchyOrdered {
+    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_ordered = GetBudgetOrdered( $budget_id );
+    for my $child_id ( @$children_ids ) {
+        $total_ordered += GetBudgetHierarchyOrdered( $child_id );
+    }
+    return $total_ordered;
+}
+
+=head2 GetBudgets
+
+  &GetBudgets($filter, $order_by);
+
+gets all budgets
 
 =cut
 
 # -------------------------------------------------------------------
 sub GetBudgets {
-    my ($active) = @_;
-    my $dbh      = C4::Context->dbh;
-    my $q        = "SELECT * from aqbudgets";
-    my $row;
-    my $sth;
-    unless ($active) {
-        $sth = $dbh->prepare($q);
-        $sth->execute();
-    } else {
-        $q   = "select budget_period_id from aqbudgetperiods where budget_period_active = 1 ";
-        $sth = $dbh->prepare($q);
-        $sth->execute();
-        $row = $sth->fetchrow_hashref();
-        $q   = "select * from aqbudgets  WHERE budget_period_id =? ";
-        $sth = $dbh->prepare($q);
-        $sth->execute( $row->{'budget_period_id'} );
+    my ($filters, $orderby) = @_;
+    $orderby = 'budget_name' unless($orderby);
+
+    my $rs = Koha::Database->new()->schema->resultset('Aqbudget');
+    $rs = $rs->search( $filters, { order_by => $orderby } );
+    $rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
+    return [ $rs->all  ];
+}
+
+=head2 GetBudgetUsers
+
+    my @borrowernumbers = &GetBudgetUsers($budget_id);
+
+Return the list of borrowernumbers linked to a budget
+
+=cut
+
+sub GetBudgetUsers {
+    my ($budget_id) = @_;
+
+    my $dbh = C4::Context->dbh;
+    my $query = qq{
+        SELECT borrowernumber
+        FROM aqbudgetborrowers
+        WHERE budget_id = ?
+    };
+    my $sth = $dbh->prepare($query);
+    $sth->execute($budget_id);
+
+    my @borrowernumbers;
+    while (my ($borrowernumber) = $sth->fetchrow_array) {
+        push @borrowernumbers, $borrowernumber
+    }
+
+    return @borrowernumbers;
+}
+
+=head2 ModBudgetUsers
+
+    &ModBudgetUsers($budget_id, @borrowernumbers);
+
+Modify the list of borrowernumbers linked to a budget
+
+=cut
+
+sub ModBudgetUsers {
+    my ($budget_id, @budget_users_id) = @_;
+
+    return unless $budget_id;
+
+    my $dbh = C4::Context->dbh;
+    my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?";
+    my $sth = $dbh->prepare($query);
+    $sth->execute($budget_id);
+
+    $query = qq{
+        INSERT INTO aqbudgetborrowers (budget_id, borrowernumber)
+        VALUES (?,?)
+    };
+    $sth = $dbh->prepare($query);
+    foreach my $borrowernumber (@budget_users_id) {
+        next unless $borrowernumber;
+        $sth->execute($budget_id, $borrowernumber);
+    }
+}
+
+sub CanUserUseBudget {
+    my ($borrower, $budget, $userflags) = @_;
+
+    if (not ref $borrower) {
+        $borrower = C4::Members::GetMember(borrowernumber => $borrower);
+    }
+    if (not ref $budget) {
+        $budget = GetBudget($budget);
+    }
+
+    return 0 unless ($borrower and $budget);
+
+    if (not defined $userflags) {
+        $userflags = C4::Auth::getuserflags($borrower->{flags},
+            $borrower->{userid});
+    }
+
+    unless ($userflags->{superlibrarian}
+    || (ref $userflags->{acquisition}
+        && $userflags->{acquisition}->{budget_manage_all})
+    || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
+    {
+        if (not exists $userflags->{acquisition}) {
+            return 0;
+        }
+
+        if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) {
+            return 0;
+        }
+
+        # Budget restricted to owner
+        if ( $budget->{budget_permission} == 1 ) {
+            if (    $budget->{budget_owner_id}
+                and $budget->{budget_owner_id} != $borrower->{borrowernumber} )
+            {
+                return 0;
+            }
+        }
+
+        # Budget restricted to owner, users and library
+        elsif ( $budget->{budget_permission} == 2 ) {
+            my @budget_users = GetBudgetUsers( $budget->{budget_id} );
+
+            if (
+                (
+                        $budget->{budget_owner_id}
+                    and $budget->{budget_owner_id} !=
+                    $borrower->{borrowernumber}
+                    or not $budget->{budget_owner_id}
+                )
+                and ( 0 == grep { $borrower->{borrowernumber} == $_ }
+                    @budget_users )
+                and defined $budget->{budget_branchcode}
+                and $budget->{budget_branchcode} ne
+                C4::Context->userenv->{branch}
+              )
+            {
+                return 0;
+            }
+        }
+
+        # Budget restricted to owner and users
+        elsif ( $budget->{budget_permission} == 3 ) {
+            my @budget_users = GetBudgetUsers( $budget->{budget_id} );
+            if (
+                (
+                        $budget->{budget_owner_id}
+                    and $budget->{budget_owner_id} !=
+                    $borrower->{borrowernumber}
+                    or not $budget->{budget_owner_id}
+                )
+                and ( 0 == grep { $borrower->{borrowernumber} == $_ }
+                    @budget_users )
+              )
+            {
+                return 0;
+            }
+        }
     }
-    my $results = $sth->fetchall_arrayref( {} );
-    $sth->finish;
-    return $results;
+
+    return 1;
+}
+
+sub CanUserModifyBudget {
+    my ($borrower, $budget, $userflags) = @_;
+
+    if (not ref $borrower) {
+        $borrower = C4::Members::GetMember(borrowernumber => $borrower);
+    }
+    if (not ref $budget) {
+        $budget = GetBudget($budget);
+    }
+
+    return 0 unless ($borrower and $budget);
+
+    if (not defined $userflags) {
+        $userflags = C4::Auth::getuserflags($borrower->{flags},
+            $borrower->{userid});
+    }
+
+    unless ($userflags->{superlibrarian}
+    || (ref $userflags->{acquisition}
+        && $userflags->{acquisition}->{budget_manage_all})
+    || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
+    {
+        if (!CanUserUseBudget($borrower, $budget, $userflags)) {
+            return 0;
+        }
+
+        if (ref $userflags->{acquisition}
+        && !$userflags->{acquisition}->{budget_modify}) {
+            return 0;
+        }
+    }
+
+    return 1;
 }
 
 # -------------------------------------------------------------------
 
-=head3 GetCurrencies
+=head2 GetCurrencies
 
-@currencies = &GetCurrencies;
+  @currencies = &GetCurrencies;
 
 Returns the list of all known currencies.
 
@@ -864,7 +944,6 @@ sub GetCurrencies {
     while ( my $data = $sth->fetchrow_hashref ) {
         push( @results, $data );
     }
-    $sth->finish;
     return @results;
 }
 
@@ -877,11 +956,10 @@ sub GetCurrency {
     my $sth = $dbh->prepare($query);
     $sth->execute;
     my $r = $sth->fetchrow_hashref;
-    $sth->finish;
     return $r;
 }
 
-=head3 ModCurrencies
+=head2 ModCurrencies
 
 &ModCurrencies($currency, $newrate);
 
@@ -902,15 +980,14 @@ sub ModCurrencies {
 
 # -------------------------------------------------------------------
 
-=head3 ConvertCurrency
+=head2 ConvertCurrency
 
-$foreignprice = &ConvertCurrency($currency, $localprice);
+  $foreignprice = &ConvertCurrency($currency, $localprice);
 
 Converts the price C<$localprice> to foreign currency C<$currency> by
 dividing by the exchange rate, and returns the result.
 
-If no exchange rate is found,e is one
-to one.
+If no exchange rate is found, e is one to one.
 
 =cut
 
@@ -931,15 +1008,236 @@ sub ConvertCurrency {
     return ( $price / $cur );
 }
 
+
+=head2 CloneBudgetPeriod
+
+  my $new_budget_period_id = CloneBudgetPeriod({
+    budget_period_id => $budget_period_id,
+    budget_period_startdate => $budget_period_startdate,
+    budget_period_enddate   => $budget_period_enddate,
+    mark_original_budget_as_inactive => 1n
+    reset_all_budgets => 1,
+  });
+
+Clone a budget period with all budgets.
+If the mark_origin_budget_as_inactive is set (0 by default),
+the original budget will be marked as inactive.
+
+If the reset_all_budgets is set (0 by default), all budget (fund)
+amounts will be reset.
+
+=cut
+
+sub CloneBudgetPeriod {
+    my ($params)                  = @_;
+    my $budget_period_id          = $params->{budget_period_id};
+    my $budget_period_startdate   = $params->{budget_period_startdate};
+    my $budget_period_enddate     = $params->{budget_period_enddate};
+    my $budget_period_description = $params->{budget_period_description};
+    my $mark_original_budget_as_inactive =
+      $params->{mark_original_budget_as_inactive} || 0;
+    my $reset_all_budgets = $params->{reset_all_budgets} || 0;
+
+    my $budget_period = GetBudgetPeriod($budget_period_id);
+
+    $budget_period->{budget_period_startdate}   = $budget_period_startdate;
+    $budget_period->{budget_period_enddate}     = $budget_period_enddate;
+    $budget_period->{budget_period_description} = $budget_period_description;
+    # The new budget (budget_period) should be active by default
+    $budget_period->{budget_period_active}    = 1;
+    my $original_budget_period_id = $budget_period->{budget_period_id};
+    delete $budget_period->{budget_period_id};
+    my $new_budget_period_id = AddBudgetPeriod( $budget_period );
+
+    my $budgets = GetBudgetHierarchy($budget_period_id);
+    CloneBudgetHierarchy(
+        {
+            budgets              => $budgets,
+            new_budget_period_id => $new_budget_period_id
+        }
+    );
+
+    if ($mark_original_budget_as_inactive) {
+        ModBudgetPeriod(
+            {
+                budget_period_id     => $budget_period_id,
+                budget_period_active => 0,
+            }
+        );
+    }
+
+    if ( $reset_all_budgets ) {
+        my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
+        for my $budget ( @$budgets ) {
+            $budget->{budget_amount} = 0;
+            ModBudget( $budget );
+        }
+    }
+
+    return $new_budget_period_id;
+}
+
+=head2 CloneBudgetHierarchy
+
+  CloneBudgetHierarchy({
+    budgets => $budgets,
+    new_budget_period_id => $new_budget_period_id;
+  });
+
+Clone a budget hierarchy.
+
+=cut
+
+sub CloneBudgetHierarchy {
+    my ($params)             = @_;
+    my $budgets              = $params->{budgets};
+    my $new_budget_period_id = $params->{new_budget_period_id};
+    next unless @$budgets or $new_budget_period_id;
+
+    my $children_of   = $params->{children_of};
+    my $new_parent_id = $params->{new_parent_id};
+
+    my @first_level_budgets =
+      ( not defined $children_of )
+      ? map { ( not $_->{budget_parent_id} )             ? $_ : () } @$budgets
+      : map { ( $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets;
+
+    # get only the columns of aqbudgets
+    my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns;
+
+    for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} }
+        @first_level_budgets )
+    {
+
+        my $tidy_budget =
+          { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
+              keys %$budget };
+        my $new_budget_id = AddBudget(
+            {
+                %$tidy_budget,
+                budget_id        => undef,
+                budget_parent_id => $new_parent_id,
+                budget_period_id => $new_budget_period_id
+            }
+        );
+        CloneBudgetHierarchy(
+            {
+                budgets              => $budgets,
+                new_budget_period_id => $new_budget_period_id,
+                children_of          => $budget->{budget_id},
+                new_parent_id        => $new_budget_id
+            }
+        );
+    }
+}
+
+=head2 MoveOrders
+
+  my $report = MoveOrders({
+    from_budget_period_id => $from_budget_period_id,
+    to_budget_period_id   => $to_budget_period_id,
+  });
+
+Move orders from one budget period to another.
+
+=cut
+
+sub MoveOrders {
+    my ($params)              = @_;
+    my $from_budget_period_id = $params->{from_budget_period_id};
+    my $to_budget_period_id   = $params->{to_budget_period_id};
+    my $move_remaining_unspent = $params->{move_remaining_unspent};
+    return
+      if not $from_budget_period_id
+          or not $to_budget_period_id
+          or $from_budget_period_id == $to_budget_period_id;
+
+    # Can't move orders to an inactive budget (budgetperiod)
+    my $budget_period = GetBudgetPeriod($to_budget_period_id);
+    return unless $budget_period->{budget_period_active};
+
+    my @report;
+    my $dbh     = C4::Context->dbh;
+    my $sth_update_aqorders = $dbh->prepare(
+        q|
+            UPDATE aqorders
+            SET budget_id = ?
+            WHERE ordernumber = ?
+        |
+    );
+    my $sth_update_budget_amount = $dbh->prepare(
+        q|
+            UPDATE aqbudgets
+            SET budget_amount = ?
+            WHERE budget_id = ?
+        |
+    );
+    my $from_budgets = GetBudgetHierarchy($from_budget_period_id);
+    for my $from_budget (@$from_budgets) {
+        my $new_budget_id = $dbh->selectcol_arrayref(
+            q|
+                SELECT budget_id
+                FROM aqbudgets
+                WHERE budget_period_id = ?
+                    AND budget_code = ?
+            |, {}, $to_budget_period_id, $from_budget->{budget_code}
+        );
+        $new_budget_id = $new_budget_id->[0];
+        my $new_budget = GetBudget( $new_budget_id );
+        unless ( $new_budget ) {
+            push @report,
+              {
+                moved       => 0,
+                budget      => $from_budget,
+                error       => 'budget_code_not_exists',
+              };
+            next;
+        }
+        my $orders_to_move = C4::Acquisition::SearchOrders(
+            {
+                budget_id => $from_budget->{budget_id},
+                pending   => 1,
+            }
+        );
+
+        my @orders_moved;
+        for my $order (@$orders_to_move) {
+            $sth_update_aqorders->execute( $new_budget->{budget_id}, $order->{ordernumber} );
+            push @orders_moved, $order;
+        }
+
+        my $unspent_moved = 0;
+        if ($move_remaining_unspent) {
+            my $spent   = GetBudgetHierarchySpent( $from_budget->{budget_id} );
+            my $unspent = $from_budget->{budget_amount} - $spent;
+            my $new_budget_amount = $new_budget->{budget_amount};
+            if ( $unspent > 0 ) {
+                $new_budget_amount += $unspent;
+                $unspent_moved = $unspent;
+            }
+            $new_budget->{budget_amount} = $new_budget_amount;
+            $sth_update_budget_amount->execute( $new_budget_amount,
+                $new_budget->{budget_id} );
+        }
+
+        push @report,
+          {
+            budget        => $new_budget,
+            orders_moved  => \@orders_moved,
+            moved         => 1,
+            unspent_moved => $unspent_moved,
+          };
+    }
+    return \@report;
+}
+
 END { }    # module clean-up code here (global destructor)
 
 1;
 __END__
 
-=back
-
 =head1 AUTHOR
 
-Koha Developement team <info@koha.org>
+Koha Development Team <http://koha-community.org/>
 
 =cut