BUG: fix patron search
[koha.git] / C4 / Budgets.pm
index 79012ba..9c53236 100644 (file)
@@ -21,12 +21,13 @@ use strict;
 #use warnings; FIXME - Bug 2505
 use C4::Context;
 use Koha::Database;
+use Koha::Patrons;
+use Koha::Acquisition::Invoice::Adjustments;
 use C4::Debug;
-use vars qw($VERSION @ISA @EXPORT);
+use C4::Acquisition;
+use vars qw(@ISA @EXPORT);
 
 BEGIN {
-       # set the version for version checking
-    $VERSION = 3.07.00.049;
        require Exporter;
        @ISA    = qw(Exporter);
        @EXPORT = qw(
@@ -35,6 +36,9 @@ BEGIN {
         &GetBudgetByOrderNumber
         &GetBudgetByCode
         &GetBudgets
+        &BudgetsByActivity
+        &GetBudgetsReport
+        &GetBudgetReport
         &GetBudgetHierarchy
            &AddBudget
         &ModBudget
@@ -59,10 +63,6 @@ BEGIN {
 
         &ModBudgetPlan
 
-        &GetCurrency
-        &GetCurrencies
-        &ConvertCurrency
-        
                &GetBudgetsPlanCell
         &AddBudgetPlanValue
         &GetBudgetAuthCats
@@ -77,7 +77,6 @@ BEGIN {
 
 # ----------------------------BUDGETS.PM-----------------------------";
 
-
 =head1 FUNCTIONS ABOUT BUDGETS
 
 =cut
@@ -136,6 +135,7 @@ sub AddBudgetPeriod {
     my ($budgetperiod) = @_;
     return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate});
 
+    undef $budgetperiod->{budget_period_id};
     my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod');
     return $resultset->create($budgetperiod)->id;
 }
@@ -209,23 +209,26 @@ sub SetOwnerToFundHierarchy {
 
 # -------------------------------------------------------------------
 sub GetBudgetsPlanCell {
-    my ( $cell, $period, $budget ) = @_;
+    my ( $cell, $period, $budget ) = @_; #FIXME we don't use $period
     my ($actual, $sth);
     my $dbh = C4::Context->dbh;
+    my $roundsql = C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|);
     if ( $cell->{'authcat'} eq 'MONTHS' ) {
         # get the actual amount
+        # FIXME we should consider quantity
         $sth = $dbh->prepare( qq|
 
-            SELECT SUM(ecost) AS actual FROM aqorders
+            SELECT SUM(| .  $roundsql . qq|) AS actual FROM aqorders
                 WHERE    budget_id = ? AND
                 entrydate like "$cell->{'authvalue'}%"  |
         );
         $sth->execute( $cell->{'budget_id'} );
     } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) {
         # get the actual amount
+        # FIXME we should consider quantity
         $sth = $dbh->prepare( qq|
 
-            SELECT SUM(ecost) FROM aqorders
+            SELECT SUM(| . $roundsql . qq|) FROM aqorders
                 LEFT JOIN aqorders_items
                 ON (aqorders.ordernumber = aqorders_items.ordernumber)
                 LEFT JOIN items
@@ -237,7 +240,7 @@ sub GetBudgetsPlanCell {
         # get the actual amount
         $sth = $dbh->prepare(  qq|
 
-            SELECT SUM( ecost *  quantity) AS actual
+            SELECT SUM( | . $roundsql . qq| *  quantity) AS actual
                 FROM aqorders JOIN biblioitems
                 ON (biblioitems.biblionumber = aqorders.biblionumber )
                 WHERE aqorders.budget_id = ? and itemtype  = ? |
@@ -250,7 +253,7 @@ sub GetBudgetsPlanCell {
         # get the actual amount
         $sth = $dbh->prepare( qq|
 
-        SELECT  SUM(ecost * quantity) AS actual
+        SELECT  SUM(| . $roundsql . qq| * quantity) AS actual
             FROM aqorders
             JOIN aqbudgets ON (aqbudgets.budget_id = aqorders.budget_id )
             WHERE  aqorders.budget_id = ? AND
@@ -329,27 +332,34 @@ sub ModBudgetPlan {
 
 # -------------------------------------------------------------------
 sub GetBudgetSpent {
-       my ($budget_id) = @_;
-       my $dbh = C4::Context->dbh;
-       my $sth = $dbh->prepare(qq|
-        SELECT SUM( COALESCE(unitprice, ecost) * quantity ) AS sum FROM aqorders
+    my ($budget_id) = @_;
+    my $dbh = C4::Context->dbh;
+    # unitprice_tax_included should always been set here
+    # we should not need to retrieve ecost_tax_included
+    my $sth = $dbh->prepare(qq|
+        SELECT SUM( | . C4::Acquisition::get_rounding_sql("COALESCE(unitprice_tax_included, ecost_tax_included)") . qq| * quantity ) AS sum FROM aqorders
             WHERE budget_id = ? AND
             quantityreceived > 0 AND
             datecancellationprinted IS NULL
     |);
        $sth->execute($budget_id);
-       my $sum =  $sth->fetchrow_array;
+    my $sum = 0 + $sth->fetchrow_array;
 
     $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;
 
+    my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, closedate => { '!=' => undef } },{ join => 'invoiceid' });
+    while ( my $adj = $adjustments->next ){
+        $sum += $adj->adjustment;
+    }
+
        return $sum;
 }
 
@@ -358,23 +368,18 @@ sub GetBudgetOrdered {
        my ($budget_id) = @_;
        my $dbh = C4::Context->dbh;
        my $sth = $dbh->prepare(qq|
-        SELECT SUM(ecost *  quantity) AS sum FROM aqorders
+        SELECT SUM(| . C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|) . qq| *  quantity) AS sum FROM aqorders
             WHERE budget_id = ? AND
             quantityreceived = 0 AND
             datecancellationprinted IS NULL
     |);
        $sth->execute($budget_id);
-       my $sum =  $sth->fetchrow_array;
+    my $sum =  0 + $sth->fetchrow_array;
 
-    $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 $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, encumber_open => 1, closedate => undef},{ join => 'invoiceid' });
+    while ( my $adj = $adjustments->next ){
+        $sum += $adj->adjustment;
+    }
 
        return $sum;
 }
@@ -401,7 +406,14 @@ sub GetBudgetName {
     return $sth->fetchrow_array;
 }
 
-# -------------------------------------------------------------------
+=head2 GetBudgetAuthCats
+
+  my $auth_cats = &GetBudgetAuthCats($budget_period_id);
+
+Return the list of authcat for a given budget_period_id
+
+=cut
+
 sub GetBudgetAuthCats  {
     my ($budget_period_id) = shift;
     # now, populate the auth_cats_loop used in the budget planning button
@@ -411,14 +423,10 @@ sub GetBudgetAuthCats  {
     $sth->execute($budget_period_id);
     my %authcats;
     while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) {
-        $authcats{$sort1_authcat}=1;
-        $authcats{$sort2_authcat}=1;
-    }
-    my @auth_cats_loop;
-    foreach (sort keys %authcats) {
-        push @auth_cats_loop,{ authcat => $_ };
+        $authcats{$sort1_authcat}=1 if $sort1_authcat;
+        $authcats{$sort2_authcat}=1 if $sort2_authcat;
     }
-    return \@auth_cats_loop;
+    return [ sort keys %authcats ];
 }
 
 # -------------------------------------------------------------------
@@ -457,7 +465,6 @@ sub GetBudgetPeriod {
        return $data;
 }
 
-# -------------------------------------------------------------------
 sub DelBudgetPeriod{
        my ($budget_period_id) = @_;
        my $dbh = C4::Context->dbh;
@@ -489,10 +496,12 @@ sub GetBudgetHierarchy {
     my @bind_params;
     my $dbh   = C4::Context->dbh;
     my $query = qq|
-                    SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description
+                    SELECT aqbudgets.*, aqbudgetperiods.budget_period_active, aqbudgetperiods.budget_period_description,
+                           b.firstname as budget_owner_firstname, b.surname as budget_owner_surname, b.borrowernumber as budget_owner_borrowernumber
                     FROM aqbudgets 
+                    LEFT JOIN borrowers b on b.borrowernumber = aqbudgets.budget_owner_id
                     JOIN aqbudgetperiods USING (budget_period_id)|;
-                        
+
        my @where_strings;
     # show only period X if requested
     if ($budget_period_id) {
@@ -511,7 +520,7 @@ sub GetBudgetHierarchy {
         }
     } else {
         if ($branchcode) {
-            push @where_strings," (budget_branchcode =? or budget_branchcode is NULL)";
+            push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')";
             push @bind_params, $branchcode;
         }
     }
@@ -547,27 +556,97 @@ sub GetBudgetHierarchy {
 
     my @sort = ();
     foreach my $first_parent (@first_parents) {
-        _add_budget_children(\@sort, $first_parent);
+        _add_budget_children(\@sort, $first_parent, 0);
     }
 
+    # Get all the budgets totals in as few queries as possible
+    my $hr_budget_spent = $dbh->selectall_hashref(q|
+        SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
+               SUM( | . C4::Acquisition::get_rounding_sql(qq|COALESCE(unitprice_tax_included, ecost_tax_included)|) . q| * quantity ) AS budget_spent
+        FROM aqorders JOIN aqbudgets USING (budget_id)
+        WHERE quantityreceived > 0 AND datecancellationprinted IS NULL
+        GROUP BY budget_id, budget_parent_id
+        |, 'budget_id');
+    my $hr_budget_ordered = $dbh->selectall_hashref(q|
+        SELECT aqorders.budget_id, aqbudgets.budget_parent_id,
+               SUM( | . C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|) . q| *  quantity) AS budget_ordered
+        FROM aqorders JOIN aqbudgets USING (budget_id)
+        WHERE quantityreceived = 0 AND datecancellationprinted IS NULL
+        GROUP BY budget_id, budget_parent_id
+        |, 'budget_id');
+    my $hr_budget_spent_shipment = $dbh->selectall_hashref(q|
+        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(q|
+        SELECT shipmentcost_budgetid as budget_id,
+               SUM(shipmentcost) as shipmentcost
+        FROM aqinvoices
+        WHERE closedate IS NULL
+        GROUP BY shipmentcost_budgetid
+        |, 'budget_id');
+    my $hr_budget_spent_adjustment = $dbh->selectall_hashref(q|
+        SELECT budget_id,
+               SUM(adjustment) as adjustments
+        FROM aqinvoice_adjustments
+        JOIN aqinvoices USING (invoiceid)
+        WHERE closedate IS NOT NULL
+        GROUP BY budget_id
+        |, 'budget_id');
+    my $hr_budget_ordered_adjustment = $dbh->selectall_hashref(q|
+        SELECT budget_id,
+               SUM(adjustment) as adjustments
+        FROM aqinvoice_adjustments
+        JOIN aqinvoices USING (invoiceid)
+        WHERE closedate IS NULL AND encumber_open = 1
+        GROUP BY budget_id
+        |, 'budget_id');
+
+
     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} );
+        if ( not defined $budget->{budget_parent_id} ) {
+            _recursiveAdd( $budget, undef, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment );
+        }
     }
     return \@sort;
 }
 
+sub _recursiveAdd {
+    my ($budget, $parent, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment ) = @_;
+
+    foreach my $child (@{$budget->{children}}){
+        _recursiveAdd($child, $budget, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_ordered_shipment, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment );
+    }
+
+    $budget->{budget_spent} += $hr_budget_spent->{$budget->{budget_id}}->{budget_spent};
+    $budget->{budget_spent} += $hr_budget_spent_shipment->{$budget->{budget_id}}->{shipmentcost};
+    $budget->{budget_spent} += $hr_budget_spent_adjustment->{$budget->{budget_id}}->{adjustments};
+    $budget->{budget_ordered} += $hr_budget_ordered->{$budget->{budget_id}}->{budget_ordered};
+    $budget->{budget_ordered} += $hr_budget_ordered_shipment->{$budget->{budget_id}}->{shipmentcost};
+    $budget->{budget_ordered} += $hr_budget_ordered_adjustment->{$budget->{budget_id}}->{adjustments};
+
+    $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};
+    }
+}
+
 # Recursive method to add a budget and its chidren to an array
 sub _add_budget_children {
     my $res = shift;
     my $budget = shift;
+    $budget->{budget_level} = shift;
     push @$res, $budget;
     my $children = $budget->{'children'} || [];
     return unless @$children; # break recursivity
     foreach my $child (@$children) {
-        _add_budget_children($res, $child);
+        _add_budget_children($res, $child, $budget->{budget_level} + 1);
     }
 }
 
@@ -577,6 +656,8 @@ sub AddBudget {
     my ($budget) = @_;
     return unless ($budget);
 
+    undef $budget->{budget_encumb} if $budget->{budget_encumb} eq '';
+    undef $budget->{budget_owner_id} if $budget->{budget_owner_id} eq '';
     my $resultset = Koha::Database->new()->schema->resultset('Aqbudget');
     return $resultset->create($budget)->id;
 }
@@ -587,6 +668,8 @@ sub ModBudget {
     my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget);
     return unless($result);
 
+    undef $budget->{budget_encumb} if $budget->{budget_encumb} eq '';
+    undef $budget->{budget_owner_id} if $budget->{budget_owner_id} eq '';
     $result = $result->update($budget);
     return $result->in_storage;
 }
@@ -601,6 +684,8 @@ sub DelBudget {
 }
 
 
+# -------------------------------------------------------------------
+
 =head2 GetBudget
 
   &GetBudget($budget_id);
@@ -609,7 +694,6 @@ get a specific budget
 
 =cut
 
-# -------------------------------------------------------------------
 sub GetBudget {
     my ( $budget_id ) = @_;
     my $dbh = C4::Context->dbh;
@@ -624,6 +708,8 @@ sub GetBudget {
     return $result;
 }
 
+# -------------------------------------------------------------------
+
 =head2 GetBudgetByOrderNumber
 
   &GetBudgetByOrderNumber($ordernumber);
@@ -632,7 +718,6 @@ get a specific budget by order number
 
 =cut
 
-# -------------------------------------------------------------------
 sub GetBudgetByOrderNumber {
     my ( $ordernumber ) = @_;
     my $dbh = C4::Context->dbh;
@@ -648,6 +733,117 @@ sub GetBudgetByOrderNumber {
     return $result;
 }
 
+=head2 GetBudgetReport
+
+  &GetBudgetReport( [$budget_id] );
+
+Get all orders for a specific budget, without cancelled orders.
+
+Returns an array of hashrefs.
+
+=cut
+
+# --------------------------------------------------------------------
+sub GetBudgetReport {
+    my ( $budget_id ) = @_;
+    my $dbh = C4::Context->dbh;
+    my $query = '
+        SELECT o.*, b.budget_name
+        FROM   aqbudgets b
+        INNER JOIN aqorders o
+        ON b.budget_id = o.budget_id
+        WHERE  b.budget_id=?
+        AND (o.orderstatus != "cancelled")
+        ORDER BY b.budget_name';
+
+    my $sth = $dbh->prepare($query);
+    $sth->execute( $budget_id );
+
+    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);
@@ -662,10 +858,11 @@ sub GetBudgetByCode {
 
     my $dbh = C4::Context->dbh;
     my $query = qq{
-        SELECT *
+        SELECT aqbudgets.*
         FROM aqbudgets
+        JOIN aqbudgetperiods USING (budget_period_id)
         WHERE budget_code = ?
-        ORDER BY budget_id DESC
+        ORDER BY budget_period_active DESC, budget_id DESC
         LIMIT 1
     };
     my $sth = $dbh->prepare( $query );
@@ -801,7 +998,9 @@ sub CanUserUseBudget {
     my ($borrower, $budget, $userflags) = @_;
 
     if (not ref $borrower) {
-        $borrower = C4::Members::GetMember(borrowernumber => $borrower);
+        $borrower = Koha::Patrons->find( $borrower );
+        return 0 unless $borrower;
+        $borrower = $borrower->unblessed;
     }
     if (not ref $budget) {
         $budget = GetBudget($budget);
@@ -884,7 +1083,9 @@ sub CanUserModifyBudget {
     my ($borrower, $budget, $userflags) = @_;
 
     if (not ref $borrower) {
-        $borrower = C4::Members::GetMember(borrowernumber => $borrower);
+        $borrower = Koha::Patrons->find( $borrower );
+        return 0 unless $borrower;
+        $borrower = $borrower->unblessed;
     }
     if (not ref $budget) {
         $budget = GetBudget($budget);
@@ -915,77 +1116,16 @@ sub CanUserModifyBudget {
     return 1;
 }
 
-# -------------------------------------------------------------------
-
-=head2 GetCurrencies
-
-  @currencies = &GetCurrencies;
-
-Returns the list of all known currencies.
-
-C<$currencies> is a array; its elements are references-to-hash, whose
-keys are the fields from the currency table in the Koha database.
-
-=cut
+sub _round {
+    my ($value, $increment) = @_;
 
-sub GetCurrencies {
-    my $dbh   = C4::Context->dbh;
-    my $query = "
-        SELECT *
-        FROM   currency
-    ";
-    my $sth = $dbh->prepare($query);
-    $sth->execute;
-    my @results = ();
-    while ( my $data = $sth->fetchrow_hashref ) {
-        push( @results, $data );
+    if ($increment && $increment != 0) {
+        $value = int($value / $increment) * $increment;
     }
-    return @results;
-}
 
-# -------------------------------------------------------------------
-
-sub GetCurrency {
-    my $dbh   = C4::Context->dbh;
-    my $query = "
-        SELECT * FROM currency where active = '1'    ";
-    my $sth = $dbh->prepare($query);
-    $sth->execute;
-    my $r = $sth->fetchrow_hashref;
-    return $r;
+    return $value;
 }
 
-# -------------------------------------------------------------------
-
-=head2 ConvertCurrency
-
-  $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.
-
-=cut
-
-sub ConvertCurrency {
-    my ( $currency, $price ) = @_;
-    my $dbh   = C4::Context->dbh;
-    my $query = "
-        SELECT rate
-        FROM   currency
-        WHERE  currency=?
-    ";
-    my $sth = $dbh->prepare($query);
-    $sth->execute($currency);
-    my $cur = ( $sth->fetchrow_array() )[0];
-    unless ($cur) {
-        $cur = 1;
-    }
-    return ( $price / $cur );
-}
-
-
 =head2 CloneBudgetPeriod
 
   my $new_budget_period_id = CloneBudgetPeriod({
@@ -1011,6 +1151,8 @@ sub CloneBudgetPeriod {
     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 $amount_change_percentage  = $params->{amount_change_percentage};
+    my $amount_change_round_increment = $params->{amount_change_round_increment};
     my $mark_original_budget_as_inactive =
       $params->{mark_original_budget_as_inactive} || 0;
     my $reset_all_budgets = $params->{reset_all_budgets} || 0;
@@ -1022,6 +1164,14 @@ sub CloneBudgetPeriod {
     $budget_period->{budget_period_description} = $budget_period_description;
     # The new budget (budget_period) should be active by default
     $budget_period->{budget_period_active}    = 1;
+
+    if ($amount_change_percentage) {
+        my $total = $budget_period->{budget_period_total};
+        $total += $total * $amount_change_percentage / 100;
+        $total = _round($total, $amount_change_round_increment);
+        $budget_period->{budget_period_total} = $total;
+    }
+
     my $original_budget_period_id = $budget_period->{budget_period_id};
     delete $budget_period->{budget_period_id};
     my $new_budget_period_id = AddBudgetPeriod( $budget_period );
@@ -1049,6 +1199,15 @@ sub CloneBudgetPeriod {
             $budget->{budget_amount} = 0;
             ModBudget( $budget );
         }
+    } elsif ($amount_change_percentage) {
+        my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id });
+        for my $budget ( @$budgets ) {
+            my $amount = $budget->{budget_amount};
+            $amount += $amount * $amount_change_percentage / 100;
+            $amount = _round($amount, $amount_change_round_increment);
+            $budget->{budget_amount} = $amount;
+            ModBudget( $budget );
+        }
     }
 
     return $new_budget_period_id;
@@ -1089,6 +1248,7 @@ sub CloneBudgetHierarchy {
         my $tidy_budget =
           { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () }
               keys %$budget };
+        delete $tidy_budget->{timestamp};
         my $new_budget_id = AddBudget(
             {
                 %$tidy_budget,