Bug 5869 - Follow up patch, fixing copyring and s/reserves/holds/
[koha.git] / reports / reserves_stats.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2010 Biblibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21
22 use strict;
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(1); # 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            ccodeloop => \@ccodes,
174           branchloop => GetBranchesLoop(C4::Context->userenv->{'branch'}),
175         hassort1=> $hassort1,
176         hassort2=> $hassort2,
177         Bsort1 => $Bsort1,
178         Bsort2 => $Bsort2,
179         CGIextChoice => $CGIextChoice,
180         CGIsepChoice => $CGIsepChoice,
181 );
182 output_html_with_http_headers $input, $cookie, $template->output;
183
184 sub calculate {
185         my ($linefield, $colfield, $process, $filters_hashref) = @_;
186         my @loopfooter;
187         my @loopcol;
188         my @loopline;
189         my @looprow;
190         my %globalline;
191         my $grantotal =0;
192 # extract parameters
193         my $dbh = C4::Context->dbh;
194
195 # Filters
196 # Checking filters
197 #
198         my @loopfilter;
199         foreach my $filter (keys %$filters_hashref){
200                 $$filters_hashref{$filter} =~s/\*/%/;
201                 $$filters_hashref{$filter} = format_date_in_iso($$filters_hashref{$_}) if ($_=~/date/);
202         }
203         #display
204         @loopfilter= map{{ crit=>$_ ,filter=>($_=~/date/?
205                                                                                         format_date($$filters_hashref{$_})
206                                                                                         :$$filters_hashref{$_}
207                                                                                   )
208                                           }
209                                         } sort keys %$filters_hashref;
210
211
212
213
214         my $linesql=changeifreservestatus($linefield);
215         my $colsql=changeifreservestatus($colfield);
216         #Initialization of cell values.....
217
218         # preparing calculation
219     my $strcalc = "(SELECT $linesql line, $colsql col, ";
220         $strcalc .= ($process == 1) ? " COUNT(*)  calculation"                                 :
221                                         ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation"  :
222                                 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation"      : 
223                                 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation"    : '*';
224         $strcalc .= "
225         FROM reserves
226         LEFT JOIN borrowers USING (borrowernumber)
227         ";
228         $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
229         if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
230         $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
231         if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
232         
233         my @sqlparams;
234         my @sqlorparams;
235         my @sqlor;
236         my @sqlwhere;
237         ($debug) and print STDERR Dump($filters_hashref);
238         foreach my $filter (keys %$filters_hashref){
239                 my $string;
240                 my $stringfield=$filter;
241                 $stringfield=~s/\_[a-z_]+$//;
242                 warn $stringfield;
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=~/_end$/){
251                         $string = " $stringfield <= ? ";
252                 }
253                 elsif ($filter=~/_begin$/){
254                         $string = " $stringfield >= ? ";
255                 }
256                 else {
257                         $string = " $stringfield LIKE ? ";
258                 }
259                 if ($string){
260                         push @sqlwhere, $string;
261                         push @sqlparams, $$filters_hashref{$filter};
262                 }
263         }
264
265         $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
266         $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
267         $strcalc .= " GROUP BY line, col )";
268         my $strcalc_old=$strcalc;
269         $strcalc_old=~s/reserves/old_reserves/g;
270         $strcalc.=qq{ UNION $strcalc_old ORDER BY line, col};
271         ($debug) and print STDERR $strcalc;
272         my $dbcalc = $dbh->prepare($strcalc);
273         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
274         @sqlparams=(@sqlparams,@sqlorparams);
275         $dbcalc->execute(@sqlparams,@sqlparams);
276         my ($emptycol,$emptyrow); 
277         my $data = $dbcalc->fetchall_hashref([qw(line col)]);
278         my @loopline;
279         my %cols_hash;
280         foreach my $row (keys %$data){
281                 push @loopline, $row;
282                 foreach my $col (keys %{$$data{$row}}){
283                         $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
284                         $grantotal+=$$data{$row}{$col}{calculation};
285                         $cols_hash{$col}=1 ;
286                 }
287         }
288         my $urlbase="do_it=1&amp;".join("&amp;",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
289         foreach my $row (sort @loopline) {
290                 my @loopcell;
291                 #@loopcol ensures the order for columns is common with column titles
292                 # and the number matches the number of columns
293                 foreach my $col (sort keys %cols_hash) {
294                         push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
295         #                                               url_complement=>($urlbase=~/&amp;$/?$urlbase."&amp;":$urlbase)."filter_$linefield=$row&amp;filter_$colfield=$col"
296                                                         }
297                 }
298                 push @looprow, {
299                         'rowtitle_display' => display_value($linefield,$row),
300                         'rowtitle' => $row,
301                         'loopcell' => \@loopcell,
302                         'totalrow' => $$data{$row}{totalrow}
303                 };
304         }
305         for my $col ( sort keys %cols_hash ) {
306                 my $total = 0;
307                 foreach my $row (@loopline) {
308                         $total += $$data{$row}{$col}{calculation};
309                         $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
310                 }
311                 push @loopfooter, {'totalcol' => $total};
312                 push @loopcol, {'coltitle' => $col,
313                                                 coltitle_display=>display_value($colfield,$col)};
314         }
315
316         # the header of the table
317         $globalline{loopfilter}=\@loopfilter;
318         # the core of the table
319         $globalline{looprow} = \@looprow;
320         $globalline{loopcol} = \@loopcol;
321         #       # the foot (totals by borrower type)
322         $globalline{loopfooter} = \@loopfooter;
323         $globalline{total}  = $grantotal;
324         $globalline{line}   = $linefield;
325         $globalline{column} = $colfield;
326         return [(\%globalline)];
327 }
328
329 sub null_to_zzempty ($) {
330         my $string = shift;
331         defined($string)    or  return 'zzEMPTY';
332         ($string eq "NULL") and return 'zzEMPTY';
333         return $string;         # else return the valid value
334 }
335 sub display_value{
336         my ($crit,$value)=@_;
337         my $display_value =
338                 ($crit =~ /ccode/   ) ? $ccodes->{$value}    :
339                 ($crit =~ /location/) ? $locations->{$value} :
340                 ($crit =~ /itemtype/) ? $itemtypes->{$value}->{description} :
341                 ($crit =~ /branch/) ? GetBranchName($value):
342                 ($crit =~ /reservestatus/) ? reservestatushuman($value):
343                 $value; # default fallback
344         if ($crit =~ /(sort1|sort2)/) {
345                 $display_value=GetAuthorisedValues("B$_",$value);
346         } elsif ($crit =~ /category/) {
347                 my $element=any{$value eq $_->{categorycode}} @$categoryloop;
348                 $display_value=$$element{description};
349         }
350         return $display_value;
351 }
352 sub reservestatushuman{
353         my ($val)=@_;
354         my %hashhuman=(
355         1=>"1- placed",
356         2=>"2- processed",
357         3=>"3- pending",
358         4=>"4- satisfied",
359         5=>"5- cancelled",
360         6=>"6- not a status"
361         );
362         $hashhuman{$val};
363 }
364 sub changeifreservestatus{
365         my ($val)=@_;
366         ($val=~/reservestatus/
367                 ?$val=qq{ case 
368                                         when priority>0 then 1 
369                                         when priority=0 then
370                                                 (case 
371                                                    when found='f' then 4
372                                                    when found='w' then 
373                                                    (case 
374                                                     when cancellationdate is null then 3
375                                                         else 5
376                                                         end )
377                                                    else 2 
378                                                  end )
379                                     else 6 
380                                         end }
381                 :$val);
382 }
383 1;