Bug 7745: Wrong service name for CAS authentification
[koha_gimpoz] / C4 / Budgets.pm
index a07afe8..7c867e0 100644 (file)
@@ -13,13 +13,15 @@ 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 C4::SQLHelper qw<:all>;
 use C4::Debug;
 
 use vars qw($VERSION @ISA @EXPORT);
@@ -38,24 +40,26 @@ BEGIN {
         &ModBudget
         &DelBudget
         &GetBudgetSpent
+        &GetBudgetOrdered
         &GetPeriodsCount
+        &GetChildBudgetsSpent
 
            &GetBudgetPeriod
         &GetBudgetPeriods
         &ModBudgetPeriod
+        &AddBudgetPeriod
            &DelBudgetPeriod
 
-           &GetBudgetPeriodsDropbox
-        &GetBudgetSortDropbox
         &GetAuthvalueDropbox
-        &GetBudgetPermDropbox
 
         &ModBudgetPlan
+
         &GetCurrency
         &GetCurrencies
         &ModCurrencies
         &ConvertCurrency
-        &GetBudgetsPlanCell
+        
+               &GetBudgetsPlanCell
         &AddBudgetPlanValue
         &GetBudgetAuthCats
         &BudgetHasChildren
@@ -70,19 +74,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 
@@ -129,6 +128,10 @@ sub CheckBudgetParentPerm {
     return 0;
 }
 
+sub AddBudgetPeriod {
+    my ($budgetperiod) = @_;
+       return InsertInTable("aqbudgetperiods",$budgetperiod);
+}
 # -------------------------------------------------------------------
 sub GetPeriodsCount {
     my $dbh = C4::Context->dbh;
@@ -173,7 +176,6 @@ sub BudgetHasChildren {
         WHERE budget_parent_id = ?   | );
     $sth->execute( $budget_id );
     my $sum = $sth->fetchrow_hashref;
-    $sth->finish;
     return $sum->{'sum'};
 }
 
@@ -227,7 +229,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'},
@@ -238,7 +239,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
@@ -303,32 +304,31 @@ 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;
+sub GetBudgetOrdered {
+       my ($budget_id) = @_;
+       my $dbh = C4::Context->dbh;
+       my $sth = $dbh->prepare(qq|
+        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;
+       return $sum;
 }
 
 # -------------------------------------------------------------------
@@ -353,84 +353,34 @@ sub GetBudgetAuthCats  {
 
 # -------------------------------------------------------------------
 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,
+    my ( $authcat, $default ) = @_;
+    my $dbh = C4::Context->dbh;
+    my $sth = $dbh->prepare(
+        'SELECT authorised_value,lib FROM authorised_values
+        WHERE category = ? ORDER BY lib'
     );
+    $sth->execute( $authcat );
+    my $option_list = [];
+    my @authorised_values = ( q{} );
+    while (my ($value, $lib) = $sth->fetchrow_array) {
+        push @{$option_list}, {
+            value => $value,
+            label => $lib,
+            default => ($default eq $value),
+        };
+    }
 
-    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;
+    if ( @{$option_list} ) {
+        return $option_list;
+    }
+    return;
 }
 
 # -------------------------------------------------------------------
 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) = @_;
+    return SearchInTable("aqbudgetperiods",$filters, $orderby, undef,undef, undef, "wide");
 }
-
 # -------------------------------------------------------------------
 sub GetBudgetPeriod {
        my ($budget_period_id) = @_;
@@ -439,7 +389,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
@@ -455,12 +405,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
@@ -476,67 +425,45 @@ sub DelBudgetPeriod() {
 }
 
 # -------------------------------------------------------------------
-sub ModBudgetPeriod() {
+sub ModBudgetPeriod {
        my ($budget_period_information) = @_;
-       my $dbh = C4::Context->dbh ; ## $total = number of records linked to the record that must be deleted       my $total = 0;
-
-       ## get information about the record that will be deleted
-    my $budget_period_id=$$budget_period_information{'budget_period_id'};
-    delete $$budget_period_information{'budget_period_id'};
-    my @values;
-    my @keys;
-
-    while ( my ($k,$v) = each %$budget_period_information ) {
-               next if (not $v and $k!~/sort1|note/);
-               #next if any { $_ eq $k } qw( sort1 note);
-               push @values, $v;
-               push @keys,   "$k=?";
-    }
-
-    my $query = do { local $"=',';
-                                       qq{
-                                               UPDATE aqbudgetperiods
-                                                       SET  @keys
-                                                       WHERE  budget_period_id=?
-                                       }
-                       };
-
-       my $sth=$dbh->prepare($query);
-       my $data = $sth->execute(@values,$budget_period_id);
-       return $data;
+       return UpdateInTable("aqbudgetperiods",$budget_period_information);
 }
 
 # -------------------------------------------------------------------
 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
+                    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({});
@@ -563,8 +490,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) {
@@ -578,9 +505,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;
@@ -592,7 +518,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 {
@@ -609,19 +535,22 @@ sub GetBudgetHierarchy {
 # 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 @subs_arr = ();
+        if ( defined $subs_href ) {
+            @subs_arr = @{$subs_href};
+        }
 
         my $moo = $r->{'budget_code_indent'};
         $moo =~ s/\ /\&nbsp\;/g;
         $r->{'budget_code_indent'} =  $moo;
 
-        my $moo = $r->{'budget_name_indent'};
+        $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'}  ;
+        $r->{'budget_amount_total'} =  $r->{'budget_amount'};
 
         # foreach sub-levels
         my $unalloc_count ;
@@ -630,71 +559,23 @@ sub GetBudgetHierarchy {
                        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'};
+                       $unalloc_count +=   $sub_budget->{'budget_amount'};
                }
-
-           $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;
 }
 
 # -------------------------------------------------------------------
-sub AddBudget {
-my ($budget) = @_;
-my $dbh        = C4::Context->dbh;
-    my @keys; my  @values;
-
-    while ( my ($k,$v) = each %$budget ) {
-               next unless $v;
-               push @values, $v;
-               push @keys  , "$k = ?";
-    }
-
-    my $query = do {
-               local $" = ',';
-               qq{
-                       INSERT INTO aqbudgets
-                       SET @keys 
-               };
-    };
 
-    #warn $query;   
-    my $sth = $dbh->prepare($query);
-    $sth->execute(@values);
-    return $dbh->{'mysql_insertid'};
+sub AddBudget {
+    my ($budget) = @_;
+       return InsertInTable("aqbudgets",$budget);
 }
 
 # -------------------------------------------------------------------
 sub ModBudget {
     my ($budget) = @_;
-    my $dbh      = C4::Context->dbh;
-    my $budgetid=$$budget{'budgetid'};
-    delete $$budget{'budget_id'};
-
-    my @values;
-    my @keys;
-
-    while ( my ($k,$v) = each %$budget ) {
-               next if (not $v and $k!~/sort1|note/);
-               #next if any { $_ eq $k } qw( sort1 note);
-               push @values, $v;
-               push @keys,   "$k=?";
-    }
-
-    my $query = do { local $"=',';
-       qq{
-            UPDATE aqbudgets
-            SET  @keys
-            WHERE  budget_id=?
-           };
-    };
-
-       my $sth = $dbh->prepare($query);
-    $sth->execute( @values,$budgetid);
+       return UpdateInTable("aqbudgets",$budget);
 }
 
 # -------------------------------------------------------------------
@@ -703,35 +584,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
-
-=over 2
-
-=cut
-
-=head3 GetBudget
 
-=over 4
+=head2 GetBudget
 
-&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
@@ -743,47 +611,52 @@ sub GetBudget {
     return $result;
 }
 
-=head3 GetBudgets
+=head2 GetChildBudgetsSpent
 
-=over 4
+  &GetChildBudgetsSpent($budget-id);
 
-&GetBudget($budget_id);
+gets the total spent of the level and sublevels of $budget_id
 
-gets all budgets
+=cut
 
-=back
+# -------------------------------------------------------------------
+sub GetChildBudgetsSpent {
+    my ( $budget_id ) = @_;
+    my $dbh = C4::Context->dbh;
+    my $query = "
+        SELECT *
+        FROM   aqbudgets
+        WHERE  budget_parent_id=?
+        ";
+    my $sth = $dbh->prepare($query);
+    $sth->execute( $budget_id );
+    my $result = $sth->fetchall_arrayref({});
+    my $total_spent = GetBudgetSpent($budget_id);
+    if ($result){
+        $total_spent += GetChildBudgetsSpent($_->{"budget_id"}) foreach @$result;    
+    }
+    return $total_spent;
+}
+
+=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 $results = $sth->fetchall_arrayref( {} );
-    $sth->finish;
-    return $results;
+    my ($filters,$orderby) = @_;
+    return SearchInTable("aqbudgets",$filters, $orderby, undef,undef, undef, "wide");
 }
 
 # -------------------------------------------------------------------
 
-=head3 GetCurrencies
+=head2 GetCurrencies
 
-@currencies = &GetCurrencies;
+  @currencies = &GetCurrencies;
 
 Returns the list of all known currencies.
 
@@ -804,7 +677,6 @@ sub GetCurrencies {
     while ( my $data = $sth->fetchrow_hashref ) {
         push( @results, $data );
     }
-    $sth->finish;
     return @results;
 }
 
@@ -817,11 +689,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);
 
@@ -842,15 +713,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
 
@@ -871,15 +741,44 @@ sub ConvertCurrency {
     return ( $price / $cur );
 }
 
+=head2 _columns
+
+returns an array containing fieldname followed by PRI as value if PRIMARY Key
+
+=cut
+
+sub _columns(;$) {
+       my $tablename=shift||"aqbudgets";
+    return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from $tablename",{Columns=>[1,4]})};
+}
+
+sub _filter_fields{
+       my $budget=shift;
+       my $tablename=shift;
+    my @keys; 
+       my @values;
+       my %columns= _columns($tablename);
+       #Filter Primary Keys of table
+    my $elements=join "|",grep {$columns{$_} ne "PRI"} keys %columns;
+       foreach my $field (grep {/\b($elements)\b/} keys %$budget){
+               $$budget{$field}=format_date_in_iso($$budget{$field}) if ($field=~/date/ && $$budget{$field} !~C4::Dates->regexp("iso"));
+               my $strkeys= " $field = ? ";
+               if ($field=~/branch/){
+                       $strkeys="( $strkeys OR $field='' OR $field IS NULL) ";
+               }
+               push @values, $$budget{$field};
+               push @keys, $strkeys;
+       }
+       return (\@keys,\@values);
+}
+
 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