Merge remote-tracking branch 'origin/new/bug_8597'
[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;
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 C4::Dates qw/format_date format_date_in_iso/;
35 use C4::Category;
36 use List::MoreUtils qw/any/;
37 use YAML;
38
39 =head1 NAME
40
41 plugin that shows circulation stats
42
43 =head1 DESCRIPTION
44
45 =over 2
46
47 =cut
48
49 # my $debug = 1;        # override for now.
50 my $input = new CGI;
51 my $fullreportname = "reports/reserves_stats.tmpl";
52 my $do_it    = $input->param('do_it');
53 my $line     = $input->param("Line");
54 my $column   = $input->param("Column");
55 my $podsp    = $input->param("DisplayBy");
56 my $type     = $input->param("PeriodTypeSel");
57 my $daysel   = $input->param("PeriodDaySel");
58 my $monthsel = $input->param("PeriodMonthSel");
59 my $calc     = $input->param("Cellvalue");
60 my $output   = $input->param("output");
61 my $basename = $input->param("basename");
62 my $mime     = $input->param("MIME");
63 my $hash_params = $input->Vars;
64 my $filter_hashref;
65 foreach my $filter (grep {$_ =~/^filter/} keys %$hash_params){
66         my $filterstring=$filter;
67         $filterstring=~s/^filter_//g;
68         $$filter_hashref{$filterstring}=$$hash_params{$filter} if (defined $$hash_params{$filter} && $$hash_params{$filter} ne "");
69 }
70 my ($template, $borrowernumber, $cookie) = get_template_and_user({
71         template_name => $fullreportname,
72         query => $input,
73         type => "intranet",
74         authnotrequired => 0,
75         flagsrequired => {reports => '*'},
76         debug => 0,
77 });
78 our $sep     = $input->param("sep") || '';
79 $sep = "\t" if ($sep eq 'tabulation');
80 $template->param(do_it => $do_it,
81         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
82 );
83
84 my $itemtypes = GetItemTypes();
85 my $categoryloop = GetBorrowercategoryList;
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}->{description} cmp $itemtypes->{$b}->{description}} keys(%$itemtypes)) {
144         push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{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 @mime = (C4::Context->preference("MIME"));
160
161 my $CGIextChoice=CGI::scrolling_list(
162         -name     => 'MIME',
163         -id       => 'MIME',
164         -values   => \@mime,
165         -size     => 1,
166         -multiple => 0 );
167     
168 my $CGIsepChoice=GetDelimiterChoices;
169  
170 $template->param(
171         categoryloop => $categoryloop,
172         itemtypeloop => \@itemtypeloop,
173         locationloop => \@locations,
174            ccodeloop => \@ccodes,
175           branchloop => GetBranchesLoop(C4::Context->userenv->{'branch'}),
176         hassort1=> $hassort1,
177         hassort2=> $hassort2,
178         Bsort1 => $Bsort1,
179         Bsort2 => $Bsort2,
180         CGIextChoice => $CGIextChoice,
181         CGIsepChoice => $CGIsepChoice,
182 );
183 output_html_with_http_headers $input, $cookie, $template->output;
184
185 sub calculate {
186         my ($linefield, $colfield, $process, $filters_hashref) = @_;
187         my @loopfooter;
188         my @loopcol;
189         my @loopline;
190         my @looprow;
191         my %globalline;
192         my $grantotal =0;
193 # extract parameters
194         my $dbh = C4::Context->dbh;
195
196 # Filters
197 # Checking filters
198 #
199     my @loopfilter;
200     foreach my $filter ( keys %$filters_hashref ) {
201         $filters_hashref->{$filter} =~ s/\*/%/;
202         $filters_hashref->{$filter} =
203           format_date_in_iso( $filters_hashref->{$filter} )
204           if ( $filter =~ /date/ );
205     }
206
207     #display
208     @loopfilter = map {
209         {
210             crit   => $_,
211             filter => (
212                 $_ =~ /date/
213                 ? format_date( $filters_hashref->{$_} )
214                 : $filters_hashref->{$_}
215             )
216         }
217     } sort keys %$filters_hashref;
218
219
220
221
222         my $linesql=changeifreservestatus($linefield);
223         my $colsql=changeifreservestatus($colfield);
224         #Initialization of cell values.....
225
226         # preparing calculation
227     my $strcalc = "(SELECT $linesql line, $colsql col, ";
228         $strcalc .= ($process == 1) ? " COUNT(*)  calculation"                                 :
229                                         ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation"  :
230                                 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation"      : 
231                                 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation"    : '*';
232         $strcalc .= "
233         FROM reserves
234         LEFT JOIN borrowers USING (borrowernumber)
235         ";
236         $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
237         if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
238         $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
239         if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
240
241         my @sqlparams;
242         my @sqlorparams;
243         my @sqlor;
244         my @sqlwhere;
245         ($debug) and print STDERR Dump($filters_hashref);
246         foreach my $filter (keys %$filters_hashref){
247                 my $string;
248                 my $stringfield=$filter;
249                 $stringfield=~s/\_[a-z_]+$//;
250                 if ($filter=~/ /){
251                         $string=$stringfield;
252                 }
253                 elsif ($filter=~/_or/){
254                          push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
255                          push @sqlorparams, $$filters_hashref{$filter};
256                 }
257                 elsif ($filter=~/_endex$/){
258                         $string = " $stringfield < ? ";
259                 }
260                 elsif ($filter=~/_end$/){
261                         $string = " $stringfield <= ? ";
262                 }
263                 elsif ($filter=~/_begin$/){
264                         $string = " $stringfield >= ? ";
265                 }
266                 else {
267                         $string = " $stringfield LIKE ? ";
268                 }
269                 if ($string){
270                         push @sqlwhere, $string;
271                         push @sqlparams, $$filters_hashref{$filter};
272                 }
273         }
274
275         $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
276         $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
277         $strcalc .= " GROUP BY line, col )";
278         my $strcalc_old=$strcalc;
279         $strcalc_old=~s/reserves/old_reserves/g;
280         $strcalc.=qq{ UNION $strcalc_old ORDER BY line, col};
281         ($debug) and print STDERR $strcalc;
282         my $dbcalc = $dbh->prepare($strcalc);
283         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
284         @sqlparams=(@sqlparams,@sqlorparams);
285         $dbcalc->execute(@sqlparams,@sqlparams);
286         my ($emptycol,$emptyrow); 
287         my $data = $dbcalc->fetchall_hashref([qw(line col)]);
288         my %cols_hash;
289         foreach my $row (keys %$data){
290                 push @loopline, $row;
291                 foreach my $col (keys %{$$data{$row}}){
292                         $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
293                         $grantotal+=$$data{$row}{$col}{calculation};
294                         $cols_hash{$col}=1 ;
295                 }
296         }
297         my $urlbase="do_it=1&amp;".join("&amp;",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
298         foreach my $row (sort @loopline) {
299                 my @loopcell;
300                 #@loopcol ensures the order for columns is common with column titles
301                 # and the number matches the number of columns
302                 foreach my $col (sort keys %cols_hash) {
303                         push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
304         #                                               url_complement=>($urlbase=~/&amp;$/?$urlbase."&amp;":$urlbase)."filter_$linefield=$row&amp;filter_$colfield=$col"
305                                                         }
306                 }
307                 push @looprow, {
308                         'rowtitle_display' => display_value($linefield,$row),
309                         'rowtitle' => $row,
310                         'loopcell' => \@loopcell,
311                         'totalrow' => $$data{$row}{totalrow}
312                 };
313         }
314         for my $col ( sort keys %cols_hash ) {
315                 my $total = 0;
316                 foreach my $row (@loopline) {
317                         $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
318                         $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
319                 }
320                 push @loopfooter, {'totalcol' => $total};
321                 push @loopcol, {'coltitle' => $col,
322                                                 coltitle_display=>display_value($colfield,$col)};
323         }
324         # the header of the table
325         $globalline{loopfilter}=\@loopfilter;
326         # the core of the table
327         $globalline{looprow} = \@looprow;
328         $globalline{loopcol} = \@loopcol;
329         #       # the foot (totals by borrower type)
330         $globalline{loopfooter} = \@loopfooter;
331         $globalline{total}  = $grantotal;
332         $globalline{line}   = $linefield;
333         $globalline{column} = $colfield;
334         return [(\%globalline)];
335 }
336
337 sub null_to_zzempty ($) {
338         my $string = shift;
339         defined($string)    or  return 'zzEMPTY';
340         ($string eq "NULL") and return 'zzEMPTY';
341         return $string;         # else return the valid value
342 }
343 sub display_value {
344     my ( $crit, $value ) = @_;
345     my $display_value =
346         ( $crit =~ /ccode/ )         ? $ccodes->{$value}
347       : ( $crit =~ /location/ )      ? $locations->{$value}
348       : ( $crit =~ /itemtype/ )      ? $itemtypes->{$value}->{description}
349       : ( $crit =~ /branch/ )        ? GetBranchName($value)
350       : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
351       :                                $value;    # default fallback
352     if ($crit =~ /sort1/) {
353         foreach (@$Bsort1) {
354             ($value eq $_->{authorised_value}) or next;
355             $display_value = $_->{lib} and last;
356         }
357     }
358     elsif ($crit =~ /sort2/) {
359         foreach (@$Bsort2) {
360             ($value eq $_->{authorised_value}) or next;
361             $display_value = $_->{lib} and last;
362         }
363     }
364     elsif ( $crit =~ /category/ ) {
365         foreach (@$categoryloop) {
366             ( $value eq $_->{categorycode} ) or next;
367             $display_value = $_->{description} and last;
368         }
369     }
370     return $display_value;
371 }
372 sub reservestatushuman{
373         my ($val)=@_;
374         my %hashhuman=(
375         1=>"1- placed",
376         2=>"2- processed",
377         3=>"3- pending",
378         4=>"4- satisfied",
379         5=>"5- cancelled",
380         6=>"6- not a status"
381         );
382         $hashhuman{$val};
383 }
384 sub changeifreservestatus{
385         my ($val)=@_;
386         ($val=~/reservestatus/
387                 ?$val=qq{ case 
388                                         when priority>0 then 1 
389                                         when priority=0 then
390                                                 (case 
391                                                    when found='f' then 4
392                                                    when found='w' then 
393                                                    (case 
394                                                     when cancellationdate is null then 3
395                                                         else 5
396                                                         end )
397                                                    else 2 
398                                                  end )
399                                     else 6 
400                                         end }
401                 :$val);
402 }
403 1;