3 # Copyright 2010 BibLibre
5 # This file is part of Koha.
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.
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.
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>.
24 use C4::Auth qw( get_template_and_user );
26 use C4::Koha qw( GetAuthorisedValues );
27 use C4::Output qw( output_html_with_http_headers );
28 use C4::Reports qw( GetDelimiterChoices );
30 use Koha::AuthorisedValues;
31 use Koha::DateUtils qw( dt_from_string output_pref );
34 use Koha::Patron::Categories;
35 use List::MoreUtils qw( any );
39 reports/reserve_stats.pl
43 Plugin that shows reserve stats
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;
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 "");
62 my ($template, $borrowernumber, $cookie) = get_template_and_user({
63 template_name => $fullreportname,
66 flagsrequired => {reports => '*'},
68 our $sep = $input->param("sep") || '';
69 $sep = "\t" if ($sep eq 'tabulation');
70 $template->param(do_it => $do_it,
73 my @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']});
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'] } ) };
78 my $Bsort1 = GetAuthorisedValues("Bsort1");
79 my $Bsort2 = GetAuthorisedValues("Bsort2");
80 my ($hassort1,$hassort2);
81 $hassort1=1 if $Bsort1;
82 $hassort2=1 if $Bsort2;
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;
93 # Printing to a csv file
94 print $input->header(-type => 'application/vnd.sun.xml.calc',
96 -attachment=>"$basename.csv",
97 -filename=>"$basename.csv" );
98 my $cols = @$results[0]->{loopcol};
99 my $lines = @$results[0]->{looprow};
101 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
103 foreach my $col ( @$cols ) {
104 print $col->{coltitle}.$sep;
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";
116 $cols = @$results[0]->{loopfooter};
117 print map {$sep.$_->{totalcol}} @$cols;
118 print $sep.@$results[0]->{total};
120 exit; # exit either way after $do_it
123 my $dbh = C4::Context->dbh;
125 my $itemtypes = Koha::ItemTypes->search_with_localization;
129 foreach (sort keys %$locations) {
130 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
134 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
135 push @ccodes, { code => $_, description => $ccodes->{$_} };
139 my $CGIextChoice = ( 'CSV' ); # FIXME translation
140 my $CGIsepChoice=GetDelimiterChoices;
143 categoryloop => \@patron_categories,
144 itemtypes => $itemtypes,
145 locationloop => \@locations,
146 ccodeloop => \@ccodes,
147 hassort1=> $hassort1,
148 hassort2=> $hassort2,
151 CGIextChoice => $CGIextChoice,
152 CGIsepChoice => $CGIsepChoice,
154 output_html_with_http_headers $input, $cookie, $template->output;
157 my ($linefield, $colfield, $process, $filters_hashref) = @_;
165 my $dbh = C4::Context->dbh;
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' }); };
185 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
186 : $filters_hashref->{$_}
189 } sort keys %$filters_hashref;
194 my $linesql=changeifreservestatus($linefield);
195 my $colsql=changeifreservestatus($colfield);
196 #Initialization of cell values.....
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" : '*';
205 FROM (select * from reserves union select * from old_reserves) reserves
206 LEFT JOIN borrowers USING (borrowernumber)
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);
217 foreach my $filter (keys %$filters_hashref){
219 my $stringfield=$filter;
220 $stringfield=~s/\_[a-z_]+$//;
222 $string=$stringfield;
224 elsif ($filter=~/_or/){
225 push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
226 push @sqlorparams, $$filters_hashref{$filter};
228 elsif ($filter=~/_endex$/){
229 $string = " $stringfield < ? ";
231 elsif ($filter=~/_end$/){
232 $string = " $stringfield <= ? ";
234 elsif ($filter=~/_begin$/){
235 $string = " $stringfield >= ? ";
238 $string = " $stringfield LIKE ? ";
241 push @sqlwhere, $string;
242 push @sqlparams, $$filters_hashref{$filter};
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)]);
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};
263 my $urlbase="do_it=1&".join("&",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
264 foreach my $row (sort @loopline) {
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=~/&$/?$urlbase."&":$urlbase)."filter_$linefield=$row&filter_$colfield=$col"
274 'rowtitle_display' => display_value($linefield,$row),
276 'loopcell' => \@loopcell,
277 'totalrow' => $$data{$row}{totalrow}
280 for my $col ( sort keys %cols_hash ) {
282 foreach my $row (@loopline) {
283 $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
285 push @loopfooter, {'totalcol' => $total};
286 push @loopcol, {'coltitle' => $col,
287 coltitle_display=>display_value($colfield,$col)};
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)];
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");
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/) {
317 ($value eq $_->{authorised_value}) or next;
318 $display_value = $_->{lib} and last;
321 elsif ($crit =~ /sort2/) {
323 ($value eq $_->{authorised_value}) or next;
324 $display_value = $_->{lib} and last;
327 elsif ( $crit =~ /category/ ) {
328 my @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']});
329 foreach my $patron_category ( @patron_categories ) {
330 ( $value eq $patron_category->categorycode ) or next;
331 $display_value = $patron_category->description and last;
334 return $display_value;
337 sub reservestatushuman{
350 sub changeifreservestatus{
352 ($val=~/reservestatus/
354 when priority>0 then 1
357 when found='f' then 4
360 when cancellationdate is null then 3