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