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