Bug 6934: fix errors pointed out by the QA script
[koha.git] / reports / issues_stats.pl
index 201c676..648efe1 100755 (executable)
@@ -1,57 +1,61 @@
 #!/usr/bin/perl
 
-
 # Copyright 2000-2002 Katipo Communications
 #
 # This file is part of Koha.
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 2 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY 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, see <http://www.gnu.org/licenses>.
 
 use strict;
+use warnings;
 
-use CGI;
+use CGI qw ( -utf8 );
 use Date::Manip;
 
 use C4::Auth;
 use C4::Debug;
 use C4::Context;
-use C4::Branch; # GetBranches
 use C4::Koha;
 use C4::Output;
 use C4::Circulation;
-use C4::Dates qw/format_date format_date_in_iso/;
+use C4::Reports;
 use C4::Members;
 
+use Koha::AuthorisedValues;
+use Koha::DateUtils;
+
 =head1 NAME
 
-plugin that shows circulation stats
+reports/issues_stats.pl
 
 =head1 DESCRIPTION
 
-=over 2
+Plugin that shows circulation stats
 
 =cut
 
 # my $debug = 1;       # override for now.
-my $input = new CGI;
-my $fullreportname = "reports/issues_stats.tmpl";
+my $input = CGI->new;
+my $fullreportname = "reports/issues_stats.tt";
 my $do_it    = $input->param('do_it');
 my $line     = $input->param("Line");
 my $column   = $input->param("Column");
-my @filters  = $input->param("Filter");
-$filters[0]=format_date_in_iso($filters[0]);
-$filters[1]=format_date_in_iso($filters[1]);
+my @filters  = $input->multi_param("Filter");
+$filters[0] = eval { output_pref( { dt => dt_from_string( $filters[0]), dateonly => 1, dateformat => 'iso' } ); }
+    if ( $filters[0] );
+$filters[1] = eval { output_pref( { dt => dt_from_string( $filters[1]), dateonly => 1, dateformat => 'iso' } ); }
+    if ( $filters[1] );
 my $podsp    = $input->param("DisplayBy");
 my $type     = $input->param("PeriodTypeSel");
 my $daysel   = $input->param("PeriodDaySel");
@@ -59,28 +63,27 @@ my $monthsel = $input->param("PeriodMonthSel");
 my $calc     = $input->param("Cellvalue");
 my $output   = $input->param("output");
 my $basename = $input->param("basename");
-my $mime     = $input->param("MIME");
-my $del      = $input->param("sep");
 my ($template, $borrowernumber, $cookie) = get_template_and_user({
        template_name => $fullreportname,
        query => $input,
        type => "intranet",
        authnotrequired => 0,
-       flagsrequired => {reports => 1},
+       flagsrequired => {reports => '*'},
        debug => 0,
 });
+our $sep     = $input->param("sep") // '';
+$sep = "\t" if ($sep eq 'tabulation');
 $template->param(do_it => $do_it,
-       DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
 );
 
-my $itemtypes = GetItemTypes();
-my $categoryloop = GetBorrowercategoryList;
+our $itemtypes = GetItemTypes();
+our @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
 
-my $ccodes    = GetKohaAuthorisedValues("items.ccode");
-my $locations = GetKohaAuthorisedValues("items.location");
+my $locations = { map { ( $_->authorised_value => $_->lib ) } Koha::AuthorisedValues->search_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
+my $ccodes = { map { ( $_->authorised_value => $_->lib ) } Koha::AuthorisedValues->search_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
 
-my $Bsort1 = GetAuthorisedValues("Bsort1");
-my $Bsort2 = GetAuthorisedValues("Bsort2");
+our $Bsort1 = GetAuthorisedValues("Bsort1");
+our $Bsort2 = GetAuthorisedValues("Bsort2");
 my ($hassort1,$hassort2);
 $hassort1=1 if $Bsort1;
 $hassort2=1 if $Bsort2;
@@ -101,7 +104,6 @@ if ($do_it) {
                             -filename=>"$basename.csv" );
                my $cols  = @$results[0]->{loopcol};
                my $lines = @$results[0]->{looprow};
-               my $sep = C4::Context->preference("delimiter");
 # header top-right
                print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
 # Other header
@@ -122,7 +124,7 @@ if ($do_it) {
                print map {$sep.$_->{totalcol}} @$cols;
         print $sep.@$results[0]->{total};
        }
-       exit(1); # exit either way after $do_it
+       exit; # exit either way after $do_it
 }
 
 my $dbh = C4::Context->dbh;
@@ -132,21 +134,8 @@ my %select;
 
 # create itemtype arrayref for <select>.
 my @itemtypeloop;
-for my $itype ( keys(%$itemtypes)) {
-       push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{description} } ;
-}
-
-my $branches=GetBranches();
-my @branchloop;
-foreach (keys %$branches) {
-       my $thisbranch = ''; # FIXME 
-       my %row = (
-               branchcode => $_,
-               selected => ($thisbranch eq $_ ? 1 : 0),
-               code => $branches->{$_}->{'branchcode'},
-               description => $branches->{$_}->{'branchname'},
-       );
-       push @branchloop, \%row;
+for my $itype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description}} keys(%$itemtypes)) {
+    push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{translated_description} } ;
 }
 
     # location list
@@ -156,34 +145,18 @@ foreach (sort keys %$locations) {
 }
     
 my @ccodes;
-foreach (keys %$ccodes) {
+foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
        push @ccodes, { code => $_, description => $ccodes->{$_} };
 }
 
-# various
-my @mime = (C4::Context->preference("MIME"));
-
-my $CGIextChoice=CGI::scrolling_list(
-       -name     => 'MIME',
-       -id       => 'MIME',
-       -values   => \@mime,
-       -size     => 1,
-       -multiple => 0 );
-    
-my @dels = ( C4::Context->preference("delimiter") );
-my $CGIsepChoice=CGI::scrolling_list(
-       -name     => 'sep',
-       -id       => 'sep',
-       -values   => \@dels,
-       -size     => 1,
-       -multiple => 0 );
+my $CGIextChoice = ( 'CSV' ); # FIXME translation
+my $CGIsepChoice=GetDelimiterChoices;
  
 $template->param(
-       categoryloop => $categoryloop,
+    categoryloop => \@patron_categories,
        itemtypeloop => \@itemtypeloop,
        locationloop => \@locations,
           ccodeloop => \@ccodes,
-         branchloop => \@branchloop,
        hassort1=> $hassort1,
        hassort2=> $hassort2,
        Bsort1 => $Bsort1,
@@ -208,7 +181,7 @@ sub calculate {
 # Checking filters
 #
        my @loopfilter;
-       for (my $i=0;$i<=10;$i++) {
+       for (my $i=0;$i<=12;$i++) {
                my %cell;
                (@$filters[$i]) or next;
         if (($i==1) and (@$filters[$i-1])) {
@@ -218,20 +191,25 @@ sub calculate {
         if ($i>=2) {
                $cell{filter} = @$filters[$i];
         } else {
-               $cell{filter} = format_date(@$filters[$i]);
+                $cell{filter} = eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
+                   if ( @$filters[$i] );
                }
                $cell{crit} = 
-               ($i==0) ? "Period From"        :
-               ($i==1) ? "Period To"          :
-               ($i==2) ? "Patron Category ="  :
-               ($i==3) ? "Item Type ="        :
-               ($i==4) ? "Library ="          :
-               ($i==5) ? "Collection ="       :
-               ($i==6) ? "Location ="         :
-               ($i==7) ? "Item callnumber >=" :
-               ($i==8) ? "Item callnumber <"  :
-               ($i==9) ? "sort1 ="            :
-               ($i==10)? "sort2 ="            : "UNKNOWN FILTER ($i)";
+            ( $i == 0 )  ? "Period From"
+          : ( $i == 1 )  ? "Period To"
+          : ( $i == 2 )  ? "Patron Category ="
+          : ( $i == 3 )  ? "Item Type ="
+          : ( $i == 4 )  ? "Library ="
+          : ( $i == 5 )  ? "Collection ="
+          : ( $i == 6 )  ? "Location ="
+          : ( $i == 7 )  ? "Item callnumber >="
+          : ( $i == 8 )  ? "Item callnumber <"
+          : ( $i == 9 )  ? "sort1 ="
+          : ( $i == 10 ) ? "sort2 ="
+          : ( $i == 11 ) ? "Home library ="
+          : ( $i == 12 )? "Holding library ="
+          :                "UNKNOWN FILTER ($i)";
+
                # FIXME - no translation mechanism !
                push @loopfilter, \%cell;
     }
@@ -241,32 +219,42 @@ sub calculate {
        push @loopfilter,{crit=>"Select Month",filter=>$monthsel} if ($monthsel);
 
        my @linefilter;
-       $debug and warn "filtres ". join "|", @filters;
-       my ($colsource, $linesource);
+       $debug and warn "filtres ". join "|", @$filters;
+       my ($colsource, $linesource) = ('', '');
        $linefilter[1] = @$filters[1] if ($line =~ /datetime/);
-       $linefilter[0] = ($line =~ /datetime/) ? @$filters[0]  :
-                                        ($line =~ /category/) ? @$filters[2]  :
-                                        ($line =~ /itemtype/) ? @$filters[3]  :
-                                        ($line =~ /branch/  ) ? @$filters[4]  :
-                                        ($line =~ /ccode/   ) ? @$filters[5]  :
-                                        ($line =~ /location/) ? @$filters[6]  :
-                                        ($line =~ /sort1/   ) ? @$filters[9]  :
-                                        ($line =~ /sort2/   ) ? @$filters[10] : undef ;
-       if ($line =~ /ccode/ or $line =~ /location/) {
+       $linefilter[0] = 
+           ( $line =~ /datetime/ ) ? @$filters[0]
+      : ( $line =~ /category/ ) ? @$filters[2]
+      : ( $line =~ /itemtype/ ) ? @$filters[3]
+      : ( $line =~ /^branch/ )   ? @$filters[4]
+      : ( $line =~ /ccode/ )    ? @$filters[5]
+      : ( $line =~ /location/ ) ? @$filters[6]
+      : ( $line =~ /sort1/ )    ? @$filters[9]
+      : ( $line =~ /sort2/ )    ? @$filters[10]
+      : ( $line =~ /homebranch/)    ? @$filters[11]
+      : ( $line =~ /holdingbranch/) ? @$filters[12]
+      :                           undef;
+
+    if ( $line =~ /ccode/ or $line =~ /location/ or $line =~ /homebranch/ or $line =~ /holdingbranch/ ) {
                $linesource = 'items';
        }
 
        my @colfilter;
        $colfilter[1] = @$filters[1] if ($column =~ /datetime/);
-       $colfilter[0] = ($column =~ /datetime/) ? @$filters[0]  :
-                                       ($column =~ /category/) ? @$filters[2]  :
-                                       ($column =~ /itemtype/) ? @$filters[3]  :
-                                       ($column =~ /branch/  ) ? @$filters[4]  :
-                                       ($column =~ /ccode/   ) ? @$filters[5]  :
-                                       ($column =~ /location/) ? @$filters[6]  :
-                                       ($column =~ /sort1/   ) ? @$filters[9]  :
-                                       ($column =~ /sort1/   ) ? @$filters[10] : undef ;
-       if ($column =~ /ccode/ or $column =~ /location/) {
+       $colfilter[0] = 
+        ( $column =~ /datetime/ ) ? @$filters[0]
+      : ( $column =~ /category/ ) ? @$filters[2]
+      : ( $column =~ /itemtype/ ) ? @$filters[3]
+      : ( $column =~ /^branch/ )   ? @$filters[4]
+      : ( $column =~ /ccode/ )    ? @$filters[5]
+      : ( $column =~ /location/ ) ? @$filters[6]
+      : ( $column =~ /sort1/ )    ? @$filters[9]
+      : ( $column =~ /sort1/ )    ? @$filters[10]
+      : ( $column =~ /homebranch/)    ? @$filters[11]
+      : ( $column =~ /holdingbranch/) ? @$filters[12]
+      :                             undef;
+
+    if ( $column =~ /ccode/ or $column =~ /location/ or $column =~ /homebranch/ or $column =~ /holdingbranch/ ) {
                $colsource = 'items';
        }
 # 1st, loop rows.
@@ -276,7 +264,7 @@ sub calculate {
                $linefield = ($dsp == 1) ? "  dayname($line)" :
                                         ($dsp == 2) ? "monthname($line)" :
                                         ($dsp == 3) ? "     Year($line)" :
-                                       'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
+                                         'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::DateUtils
        } else {
                $linefield = $line;
        }
@@ -334,12 +322,12 @@ sub calculate {
                                ($celvalue eq $_->{authorised_value}) or next;
                                $cell{rowtitle_display} = $_->{lib} and last;
                        }
-               } elsif ($line =~ /category/) {
-                       foreach (@$categoryloop) {
-                               ($celvalue eq $_->{categorycode}) or next;
-                               $cell{rowtitle_display} = $_->{description} and last;
-                       }
-               }
+        } elsif ($line =~ /category/) {
+            foreach my $patron_category ( @patron_categories ) {
+                ($celvalue eq $patron_category->categorycode) or next;
+                $cell{rowtitle_display} = $patron_category->description and last;
+            }
+        }
                push @loopline, \%cell;
        }
 
@@ -351,12 +339,12 @@ sub calculate {
                $colfield = ($dsp == 1) ? "  dayname($column)" :
                                        ($dsp == 2) ? "monthname($column)" :
                                        ($dsp == 3) ? "     Year($column)" :
-                                       'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through C4::Dates
+                                        'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::DateUtils
        } else {
                $colfield = $column;
        }
-       $colorder = ($colfield =~ /dayname/) ? "weekday($line)" :
-                               ($colfield =~ /^month/ ) ? "  month($line)" : $colfield;
+       $colorder = ($colfield =~ /dayname/) ? "weekday($column)" :
+                               ($colfield =~ /^month/ ) ? "  month($column)" : $colfield;
        my $strsth2 = "SELECT distinctrow $colfield FROM statistics, ";
        # get stats on items if ccode or location, otherwise borrowers.
        $strsth2 .= ($colsource eq 'items' ) ?
@@ -408,12 +396,12 @@ sub calculate {
                                ($celvalue eq $_->{authorised_value}) or next;
                                $cell{coltitle_display} = $_->{lib} and last;
                        }
-               } elsif ($column =~ /category/) {
-                       foreach (@$categoryloop) {
-                               ($celvalue eq $_->{categorycode}) or next;
-                               $cell{coltitle_display} = $_->{description} and last;
-                       }
-               }
+        } elsif ($column =~ /category/) {
+            foreach my $patron_category ( @patron_categories ) {
+                ($celvalue eq $patron_category->categorycode) or next;
+                $cell{coltitle_display} = $patron_category->description and last;
+            }
+        }
                push @loopcol, \%cell;
        }
 
@@ -431,12 +419,12 @@ sub calculate {
     my $strcalc = "SELECT $linefield, $colfield, ";
         $strcalc .= ($process == 1) ? " COUNT(*) "                                 :
                                        ($process == 2) ? "(COUNT(DISTINCT borrowers.borrowernumber))" :
-                               ($process == 3) ? "(COUNT(DISTINCT issues.itemnumber))"        : '';
+                               ($process == 3) ? "(COUNT(DISTINCT statistics.itemnumber))"        : '';
        if ($process == 4) {
                my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
                $rqbookcount->execute;
                my ($bookcount) = $rqbookcount->fetchrow;
-               $strcalc .= "100*(COUNT(DISTINCT issues.itemnumber))/ $bookcount " ;
+               $strcalc .= "100*(COUNT(DISTINCT statistics.itemnumber))/ $bookcount " ;
        }
        $strcalc .= "
         FROM statistics