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