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