Bug 17931: Remove unused vars from reserves_stats
[koha.git] / reports / reserves_stats.pl
1 #!/usr/bin/perl
2
3 # Copyright 2010 BibLibre
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use Modern::Perl;
21
22 use CGI qw ( -utf8 );
23
24 use C4::Auth;
25 use C4::Debug;
26 use C4::Context;
27 use C4::Koha;
28 use C4::Output;
29 use C4::Reports;
30 use C4::Members;
31 use Koha::AuthorisedValues;
32 use Koha::DateUtils;
33 use Koha::Libraries;
34 use Koha::Patron::Categories;
35 use List::MoreUtils qw/any/;
36 use YAML;
37
38 =head1 NAME
39
40     reports/reserve_stats.pl
41
42 =head1 DESCRIPTION
43
44     Plugin that shows circulation stats
45
46 =cut
47
48 # my $debug = 1;        # override for now.
49 my $input = new CGI;
50 my $fullreportname = "reports/reserves_stats.tt";
51 my $do_it    = $input->param('do_it');
52 my $line     = $input->param("Line");
53 my $column   = $input->param("Column");
54 my $calc     = $input->param("Cellvalue");
55 my $output   = $input->param("output");
56 my $basename = $input->param("basename");
57 my $hash_params = $input->Vars;
58 my $filter_hashref;
59 foreach my $filter (grep {$_ =~/^filter/} keys %$hash_params){
60         my $filterstring=$filter;
61         $filterstring=~s/^filter_//g;
62         $$filter_hashref{$filterstring}=$$hash_params{$filter} if (defined $$hash_params{$filter} && $$hash_params{$filter} ne "");
63 }
64 my ($template, $borrowernumber, $cookie) = get_template_and_user({
65         template_name => $fullreportname,
66         query => $input,
67         type => "intranet",
68         authnotrequired => 0,
69         flagsrequired => {reports => '*'},
70         debug => 0,
71 });
72 our $sep     = $input->param("sep") || '';
73 $sep = "\t" if ($sep eq 'tabulation');
74 $template->param(do_it => $do_it,
75 );
76
77 my $itemtypes = GetItemTypes();
78 my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
79
80 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
81 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
82
83 my $Bsort1 = GetAuthorisedValues("Bsort1");
84 my $Bsort2 = GetAuthorisedValues("Bsort2");
85 my ($hassort1,$hassort2);
86 $hassort1=1 if $Bsort1;
87 $hassort2=1 if $Bsort2;
88
89
90 if ($do_it) {
91 # Displaying results
92         my $results = calculate($line, $column,  $calc, $filter_hashref);
93         if ($output eq "screen"){
94 # Printing results to screen
95                 $template->param(mainloop => $results);
96                 output_html_with_http_headers $input, $cookie, $template->output;
97         } else {
98 # Printing to a csv file
99         print $input->header(-type => 'application/vnd.sun.xml.calc',
100                             -encoding    => 'utf-8',
101                             -attachment=>"$basename.csv",
102                             -filename=>"$basename.csv" );
103                 my $cols  = @$results[0]->{loopcol};
104                 my $lines = @$results[0]->{looprow};
105 # header top-right
106                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
107 # Other header
108                 foreach my $col ( @$cols ) {
109                         print $col->{coltitle}.$sep;
110                 }
111                 print "Total\n";
112 # Table
113                 foreach my $line ( @$lines ) {
114                         my $x = $line->{loopcell};
115                         print $line->{rowtitle}.$sep;
116                         print map {$_->{value}.$sep} @$x;
117                         print $line->{totalrow}, "\n";
118                 }
119 # footer
120         print "TOTAL";
121         $cols = @$results[0]->{loopfooter};
122                 print map {$sep.$_->{totalcol}} @$cols;
123         print $sep.@$results[0]->{total};
124         }
125         exit; # exit either way after $do_it
126 }
127
128 my $dbh = C4::Context->dbh;
129 my @values;
130 my %labels;
131 my %select;
132
133 # create itemtype arrayref for <select>.
134 my @itemtypeloop;
135 for my $itype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description}} keys(%$itemtypes)) {
136         push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{translated_description} } ;
137 }
138
139     # location list
140 my @locations;
141 foreach (sort keys %$locations) {
142         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
143 }
144     
145 my @ccodes;
146 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
147         push @ccodes, { code => $_, description => $ccodes->{$_} };
148 }
149
150 # various
151 my $CGIextChoice = ( 'CSV' ); # FIXME translation
152 my $CGIsepChoice=GetDelimiterChoices;
153  
154 $template->param(
155     categoryloop => \@patron_categories,
156         itemtypeloop => \@itemtypeloop,
157         locationloop => \@locations,
158            ccodeloop => \@ccodes,
159         hassort1=> $hassort1,
160         hassort2=> $hassort2,
161         Bsort1 => $Bsort1,
162         Bsort2 => $Bsort2,
163         CGIextChoice => $CGIextChoice,
164         CGIsepChoice => $CGIsepChoice,
165 );
166 output_html_with_http_headers $input, $cookie, $template->output;
167
168 sub calculate {
169         my ($linefield, $colfield, $process, $filters_hashref) = @_;
170         my @loopfooter;
171         my @loopcol;
172         my @loopline;
173         my @looprow;
174         my %globalline;
175         my $grantotal =0;
176 # extract parameters
177         my $dbh = C4::Context->dbh;
178
179 # Filters
180 # Checking filters
181 #
182     my @loopfilter;
183     foreach my $filter ( keys %$filters_hashref ) {
184         $filters_hashref->{$filter} =~ s/\*/%/;
185         if ( $filter =~ /date/ ) {
186             $filters_hashref->{$filter} =
187                 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
188         }
189     }
190
191     #display
192     @loopfilter = map {
193         {
194             crit   => $_,
195             filter => (
196                 $_ =~ /date/
197                 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
198                 : $filters_hashref->{$_}
199             )
200         }
201     } sort keys %$filters_hashref;
202
203
204
205
206         my $linesql=changeifreservestatus($linefield);
207         my $colsql=changeifreservestatus($colfield);
208         #Initialization of cell values.....
209
210         # preparing calculation
211     my $strcalc = "(SELECT $linesql line, $colsql col, ";
212         $strcalc .= ($process == 1) ? " COUNT(*)  calculation"                                 :
213                                         ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation"  :
214                                 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation"      : 
215                                 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation"    : '*';
216         $strcalc .= "
217         FROM (select * from reserves union select * from old_reserves) reserves
218         LEFT JOIN borrowers USING (borrowernumber)
219         ";
220         $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
221         if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
222         $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
223         if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
224
225         my @sqlparams;
226         my @sqlorparams;
227         my @sqlor;
228         my @sqlwhere;
229         ($debug) and print STDERR Dump($filters_hashref);
230         foreach my $filter (keys %$filters_hashref){
231                 my $string;
232                 my $stringfield=$filter;
233                 $stringfield=~s/\_[a-z_]+$//;
234                 if ($filter=~/ /){
235                         $string=$stringfield;
236                 }
237                 elsif ($filter=~/_or/){
238                          push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
239                          push @sqlorparams, $$filters_hashref{$filter};
240                 }
241                 elsif ($filter=~/_endex$/){
242                         $string = " $stringfield < ? ";
243                 }
244                 elsif ($filter=~/_end$/){
245                         $string = " $stringfield <= ? ";
246                 }
247                 elsif ($filter=~/_begin$/){
248                         $string = " $stringfield >= ? ";
249                 }
250                 else {
251                         $string = " $stringfield LIKE ? ";
252                 }
253                 if ($string){
254                         push @sqlwhere, $string;
255                         push @sqlparams, $$filters_hashref{$filter};
256                 }
257         }
258
259         $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
260         $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
261         $strcalc .= " GROUP BY line, col )";
262         ($debug) and print STDERR $strcalc;
263         my $dbcalc = $dbh->prepare($strcalc);
264         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
265         @sqlparams=(@sqlparams,@sqlorparams);
266         $dbcalc->execute(@sqlparams);
267         my ($emptycol,$emptyrow); 
268         my $data = $dbcalc->fetchall_hashref([qw(line col)]);
269         my %cols_hash;
270         foreach my $row (keys %$data){
271                 push @loopline, $row;
272                 foreach my $col (keys %{$$data{$row}}){
273                         $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
274                         $grantotal+=$$data{$row}{$col}{calculation};
275                         $cols_hash{$col}=1 ;
276                 }
277         }
278         my $urlbase="do_it=1&amp;".join("&amp;",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
279         foreach my $row (sort @loopline) {
280                 my @loopcell;
281                 #@loopcol ensures the order for columns is common with column titles
282                 # and the number matches the number of columns
283                 foreach my $col (sort keys %cols_hash) {
284                         push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
285         #                                               url_complement=>($urlbase=~/&amp;$/?$urlbase."&amp;":$urlbase)."filter_$linefield=$row&amp;filter_$colfield=$col"
286                                                         }
287                 }
288                 push @looprow, {
289                         'rowtitle_display' => display_value($linefield,$row),
290                         'rowtitle' => $row,
291                         'loopcell' => \@loopcell,
292                         'totalrow' => $$data{$row}{totalrow}
293                 };
294         }
295         for my $col ( sort keys %cols_hash ) {
296                 my $total = 0;
297                 foreach my $row (@loopline) {
298                         $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
299                         $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
300                 }
301                 push @loopfooter, {'totalcol' => $total};
302                 push @loopcol, {'coltitle' => $col,
303                                                 coltitle_display=>display_value($colfield,$col)};
304         }
305         # the header of the table
306         $globalline{loopfilter}=\@loopfilter;
307         # the core of the table
308         $globalline{looprow} = \@looprow;
309         $globalline{loopcol} = \@loopcol;
310         #       # the foot (totals by borrower type)
311         $globalline{loopfooter} = \@loopfooter;
312         $globalline{total}  = $grantotal;
313         $globalline{line}   = $linefield;
314         $globalline{column} = $colfield;
315         return [(\%globalline)];
316 }
317
318 sub display_value {
319     my ( $crit, $value ) = @_;
320     my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
321     my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
322     my $itemtypes = GetItemTypes();
323     my $Bsort1 = GetAuthorisedValues("Bsort1");
324     my $Bsort2 = GetAuthorisedValues("Bsort2");
325     my $display_value =
326         ( $crit =~ /ccode/ )         ? $ccodes->{$value}
327       : ( $crit =~ /location/ )      ? $locations->{$value}
328       : ( $crit =~ /itemtype/ )      ? $itemtypes->{$value}->{description}
329       : ( $crit =~ /branch/ )        ? Koha::Libraries->find($value)->branchname
330       : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
331       :                                $value;    # default fallback
332     if ($crit =~ /sort1/) {
333         foreach (@$Bsort1) {
334             ($value eq $_->{authorised_value}) or next;
335             $display_value = $_->{lib} and last;
336         }
337     }
338     elsif ($crit =~ /sort2/) {
339         foreach (@$Bsort2) {
340             ($value eq $_->{authorised_value}) or next;
341             $display_value = $_->{lib} and last;
342         }
343     }
344     elsif ( $crit =~ /category/ ) {
345         my @patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['description']});
346         foreach my $patron_category ( @patron_categories ) {
347             ( $value eq $patron_category->categorycode ) or next;
348             $display_value = $patron_category->description and last;
349         }
350     }
351     return $display_value;
352 }
353
354 sub reservestatushuman{
355         my ($val)=@_;
356         my %hashhuman=(
357         1=>"1- placed",
358         2=>"2- processed",
359         3=>"3- pending",
360         4=>"4- satisfied",
361         5=>"5- cancelled",
362         6=>"6- not a status"
363         );
364         $hashhuman{$val};
365 }
366
367 sub changeifreservestatus{
368         my ($val)=@_;
369         ($val=~/reservestatus/
370                 ?$val=qq{ case 
371                                         when priority>0 then 1 
372                                         when priority=0 then
373                                                 (case 
374                                                    when found='f' then 4
375                                                    when found='w' then 
376                                                    (case 
377                                                     when cancellationdate is null then 3
378                                                         else 5
379                                                         end )
380                                                    else 2 
381                                                  end )
382                                     else 6 
383                                         end }
384                 :$val);
385 }