Bug 15065: (follow-up) update license header
[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 );
82
83 my $itemtypes = GetItemTypes();
84 my $categoryloop = GetBorrowercategoryList;
85
86 my $ccodes    = GetKohaAuthorisedValues("items.ccode");
87 my $locations = GetKohaAuthorisedValues("items.location");
88 my $authvalue = GetKohaAuthorisedValues("items.authvalue");
89
90 my $Bsort1 = GetAuthorisedValues("Bsort1");
91 my $Bsort2 = GetAuthorisedValues("Bsort2");
92 my ($hassort1,$hassort2);
93 $hassort1=1 if $Bsort1;
94 $hassort2=1 if $Bsort2;
95
96
97 if ($do_it) {
98 # Displaying results
99         my $results = calculate($line, $column,  $calc, $filter_hashref);
100         if ($output eq "screen"){
101 # Printing results to screen
102                 $template->param(mainloop => $results);
103                 output_html_with_http_headers $input, $cookie, $template->output;
104         } else {
105 # Printing to a csv file
106         print $input->header(-type => 'application/vnd.sun.xml.calc',
107                             -encoding    => 'utf-8',
108                             -attachment=>"$basename.csv",
109                             -filename=>"$basename.csv" );
110                 my $cols  = @$results[0]->{loopcol};
111                 my $lines = @$results[0]->{looprow};
112 # header top-right
113                 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
114 # Other header
115                 foreach my $col ( @$cols ) {
116                         print $col->{coltitle}.$sep;
117                 }
118                 print "Total\n";
119 # Table
120                 foreach my $line ( @$lines ) {
121                         my $x = $line->{loopcell};
122                         print $line->{rowtitle}.$sep;
123                         print map {$_->{value}.$sep} @$x;
124                         print $line->{totalrow}, "\n";
125                 }
126 # footer
127         print "TOTAL";
128         $cols = @$results[0]->{loopfooter};
129                 print map {$sep.$_->{totalcol}} @$cols;
130         print $sep.@$results[0]->{total};
131         }
132         exit; # exit either way after $do_it
133 }
134
135 my $dbh = C4::Context->dbh;
136 my @values;
137 my %labels;
138 my %select;
139
140 # create itemtype arrayref for <select>.
141 my @itemtypeloop;
142 for my $itype ( sort {$itemtypes->{$a}->{description} cmp $itemtypes->{$b}->{description}} keys(%$itemtypes)) {
143         push @itemtypeloop, { code => $itype , description => $itemtypes->{$itype}->{description} } ;
144 }
145
146     # location list
147 my @locations;
148 foreach (sort keys %$locations) {
149         push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
150 }
151     
152 my @ccodes;
153 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
154         push @ccodes, { code => $_, description => $ccodes->{$_} };
155 }
156
157 # various
158 my @mime = (C4::Context->preference("MIME"));
159
160 my $CGIextChoice=CGI::scrolling_list(
161         -name     => 'MIME',
162         -id       => 'MIME',
163         -values   => \@mime,
164         -size     => 1,
165         -multiple => 0 );
166     
167 my $CGIsepChoice=GetDelimiterChoices;
168  
169 $template->param(
170         categoryloop => $categoryloop,
171         itemtypeloop => \@itemtypeloop,
172         locationloop => \@locations,
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} =
202           format_date_in_iso( $filters_hashref->{$filter} )
203           if ( $filter =~ /date/ );
204     }
205
206     #display
207     @loopfilter = map {
208         {
209             crit   => $_,
210             filter => (
211                 $_ =~ /date/
212                 ? format_date( $filters_hashref->{$_} )
213                 : $filters_hashref->{$_}
214             )
215         }
216     } sort keys %$filters_hashref;
217
218
219
220
221         my $linesql=changeifreservestatus($linefield);
222         my $colsql=changeifreservestatus($colfield);
223         #Initialization of cell values.....
224
225         # preparing calculation
226     my $strcalc = "(SELECT $linesql line, $colsql col, ";
227         $strcalc .= ($process == 1) ? " COUNT(*)  calculation"                                 :
228                                         ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation"  :
229                                 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation"      : 
230                                 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation"    : '*';
231         $strcalc .= "
232         FROM reserves
233         LEFT JOIN borrowers USING (borrowernumber)
234         ";
235         $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
236         if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
237         $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
238         if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
239
240         my @sqlparams;
241         my @sqlorparams;
242         my @sqlor;
243         my @sqlwhere;
244         ($debug) and print STDERR Dump($filters_hashref);
245         foreach my $filter (keys %$filters_hashref){
246                 my $string;
247                 my $stringfield=$filter;
248                 $stringfield=~s/\_[a-z_]+$//;
249                 if ($filter=~/ /){
250                         $string=$stringfield;
251                 }
252                 elsif ($filter=~/_or/){
253                          push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
254                          push @sqlorparams, $$filters_hashref{$filter};
255                 }
256                 elsif ($filter=~/_endex$/){
257                         $string = " $stringfield < ? ";
258                 }
259                 elsif ($filter=~/_end$/){
260                         $string = " $stringfield <= ? ";
261                 }
262                 elsif ($filter=~/_begin$/){
263                         $string = " $stringfield >= ? ";
264                 }
265                 else {
266                         $string = " $stringfield LIKE ? ";
267                 }
268                 if ($string){
269                         push @sqlwhere, $string;
270                         push @sqlparams, $$filters_hashref{$filter};
271                 }
272         }
273
274         $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
275         $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
276         $strcalc .= " GROUP BY line, col )";
277         my $strcalc_old=$strcalc;
278         $strcalc_old=~s/reserves/old_reserves/g;
279         $strcalc.=qq{ UNION $strcalc_old ORDER BY line, col};
280         ($debug) and print STDERR $strcalc;
281         my $dbcalc = $dbh->prepare($strcalc);
282         push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
283         @sqlparams=(@sqlparams,@sqlorparams);
284         $dbcalc->execute(@sqlparams,@sqlparams);
285         my ($emptycol,$emptyrow); 
286         my $data = $dbcalc->fetchall_hashref([qw(line col)]);
287         my %cols_hash;
288         foreach my $row (keys %$data){
289                 push @loopline, $row;
290                 foreach my $col (keys %{$$data{$row}}){
291                         $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
292                         $grantotal+=$$data{$row}{$col}{calculation};
293                         $cols_hash{$col}=1 ;
294                 }
295         }
296         my $urlbase="do_it=1&amp;".join("&amp;",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
297         foreach my $row (sort @loopline) {
298                 my @loopcell;
299                 #@loopcol ensures the order for columns is common with column titles
300                 # and the number matches the number of columns
301                 foreach my $col (sort keys %cols_hash) {
302                         push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
303         #                                               url_complement=>($urlbase=~/&amp;$/?$urlbase."&amp;":$urlbase)."filter_$linefield=$row&amp;filter_$colfield=$col"
304                                                         }
305                 }
306                 push @looprow, {
307                         'rowtitle_display' => display_value($linefield,$row),
308                         'rowtitle' => $row,
309                         'loopcell' => \@loopcell,
310                         'totalrow' => $$data{$row}{totalrow}
311                 };
312         }
313         for my $col ( sort keys %cols_hash ) {
314                 my $total = 0;
315                 foreach my $row (@loopline) {
316                         $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
317                         $debug and warn "value added ".$$data{$row}{$col}{calculation}. "for line ".$row;
318                 }
319                 push @loopfooter, {'totalcol' => $total};
320                 push @loopcol, {'coltitle' => $col,
321                                                 coltitle_display=>display_value($colfield,$col)};
322         }
323         # the header of the table
324         $globalline{loopfilter}=\@loopfilter;
325         # the core of the table
326         $globalline{looprow} = \@looprow;
327         $globalline{loopcol} = \@loopcol;
328         #       # the foot (totals by borrower type)
329         $globalline{loopfooter} = \@loopfooter;
330         $globalline{total}  = $grantotal;
331         $globalline{line}   = $linefield;
332         $globalline{column} = $colfield;
333         return [(\%globalline)];
334 }
335
336 sub null_to_zzempty ($) {
337         my $string = shift;
338         defined($string)    or  return 'zzEMPTY';
339         ($string eq "NULL") and return 'zzEMPTY';
340         return $string;         # else return the valid value
341 }
342 sub display_value {
343     my ( $crit, $value ) = @_;
344     my $display_value =
345         ( $crit =~ /ccode/ )         ? $ccodes->{$value}
346       : ( $crit =~ /location/ )      ? $locations->{$value}
347       : ( $crit =~ /itemtype/ )      ? $itemtypes->{$value}->{description}
348       : ( $crit =~ /branch/ )        ? GetBranchName($value)
349       : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
350       :                                $value;    # default fallback
351     if ($crit =~ /sort1/) {
352         foreach (@$Bsort1) {
353             ($value eq $_->{authorised_value}) or next;
354             $display_value = $_->{lib} and last;
355         }
356     }
357     elsif ($crit =~ /sort2/) {
358         foreach (@$Bsort2) {
359             ($value eq $_->{authorised_value}) or next;
360             $display_value = $_->{lib} and last;
361         }
362     }
363     elsif ( $crit =~ /category/ ) {
364         foreach (@$categoryloop) {
365             ( $value eq $_->{categorycode} ) or next;
366             $display_value = $_->{description} and last;
367         }
368     }
369     return $display_value;
370 }
371 sub reservestatushuman{
372         my ($val)=@_;
373         my %hashhuman=(
374         1=>"1- placed",
375         2=>"2- processed",
376         3=>"3- pending",
377         4=>"4- satisfied",
378         5=>"5- cancelled",
379         6=>"6- not a status"
380         );
381         $hashhuman{$val};
382 }
383 sub changeifreservestatus{
384         my ($val)=@_;
385         ($val=~/reservestatus/
386                 ?$val=qq{ case 
387                                         when priority>0 then 1 
388                                         when priority=0 then
389                                                 (case 
390                                                    when found='f' then 4
391                                                    when found='w' then 
392                                                    (case 
393                                                     when cancellationdate is null then 3
394                                                         else 5
395                                                         end )
396                                                    else 2 
397                                                  end )
398                                     else 6 
399                                         end }
400                 :$val);
401 }
402 1;