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 = C4::Context->csv_delimiter(scalar $input->param("sep"));
69 $template->param(do_it => $do_it,
72 my @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']})->as_list;
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'] } ) };
77 my $Bsort1 = GetAuthorisedValues("Bsort1");
78 my $Bsort2 = GetAuthorisedValues("Bsort2");
79 my ($hassort1,$hassort2);
80 $hassort1=1 if $Bsort1;
81 $hassort2=1 if $Bsort2;
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;
92 # Printing to a csv file
93 print $input->header(-type => 'application/vnd.sun.xml.calc',
95 -attachment=>"$basename.csv",
96 -filename=>"$basename.csv" );
97 my $cols = @$results[0]->{loopcol};
98 my $lines = @$results[0]->{looprow};
100 print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
102 foreach my $col ( @$cols ) {
103 print $col->{coltitle}.$sep;
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";
115 $cols = @$results[0]->{loopfooter};
116 print map {$sep.$_->{totalcol}} @$cols;
117 print $sep.@$results[0]->{total};
119 exit; # exit either way after $do_it
122 my $dbh = C4::Context->dbh;
124 my $itemtypes = Koha::ItemTypes->search_with_localization;
128 foreach (sort keys %$locations) {
129 push @locations, { code => $_, description => "$_ - " . $locations->{$_} };
133 foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) {
134 push @ccodes, { code => $_, description => $ccodes->{$_} };
138 my $CGIextChoice = ( 'CSV' ); # FIXME translation
139 my $CGIsepChoice=GetDelimiterChoices;
142 categoryloop => \@patron_categories,
143 itemtypes => $itemtypes,
144 locationloop => \@locations,
145 ccodeloop => \@ccodes,
146 hassort1=> $hassort1,
147 hassort2=> $hassort2,
150 CGIextChoice => $CGIextChoice,
151 CGIsepChoice => $CGIsepChoice,
153 output_html_with_http_headers $input, $cookie, $template->output;
156 my ($linefield, $colfield, $process, $filters_hashref) = @_;
164 my $dbh = C4::Context->dbh;
170 foreach my $filter ( keys %$filters_hashref ) {
171 $filters_hashref->{$filter} =~ s/\*/%/;
172 if ( $filter =~ /date/ ) {
173 $filters_hashref->{$filter} =
174 eval { output_pref( { dt => dt_from_string( $filters_hashref->{$filter} ), dateonly => 1, dateformat => 'iso' }); };
184 ? eval { output_pref( { dt => dt_from_string( $filters_hashref->{$_} ), dateonly => 1 }); }
185 : $filters_hashref->{$_}
188 } sort keys %$filters_hashref;
193 my $linesql=changeifreservestatus($linefield);
194 my $colsql=changeifreservestatus($colfield);
195 #Initialization of cell values.....
197 # preparing calculation
198 my $strcalc = "(SELECT $linesql line, $colsql col, ";
199 $strcalc .= ($process == 1) ? " COUNT(*) calculation" :
200 ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation" :
201 ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation" :
202 ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation" : '*';
204 FROM (select * from reserves union select * from old_reserves) reserves
205 LEFT JOIN borrowers USING (borrowernumber)
207 $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber "
208 if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref);
209 $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber "
210 if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref);
216 foreach my $filter (keys %$filters_hashref){
218 my $stringfield=$filter;
219 $stringfield=~s/\_[a-z_]+$//;
221 $string=$stringfield;
223 elsif ($filter=~/_or/){
224 push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) ";
225 push @sqlorparams, $$filters_hashref{$filter};
227 elsif ($filter=~/_endex$/){
228 $string = " $stringfield < ? ";
230 elsif ($filter=~/_end$/){
231 $string = " $stringfield <= ? ";
233 elsif ($filter=~/_begin$/){
234 $string = " $stringfield >= ? ";
237 $string = " $stringfield LIKE ? ";
240 push @sqlwhere, $string;
241 push @sqlparams, $$filters_hashref{$filter};
245 $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere);
246 $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor);
247 $strcalc .= " GROUP BY line, col )";
248 my $dbcalc = $dbh->prepare($strcalc);
249 push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc};
250 @sqlparams=(@sqlparams,@sqlorparams);
251 $dbcalc->execute(@sqlparams);
252 my $data = $dbcalc->fetchall_hashref([qw(line col)]);
254 foreach my $row (keys %$data){
255 push @loopline, $row;
256 foreach my $col (keys %{$$data{$row}}){
257 $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation};
258 $grantotal+=$$data{$row}{$col}{calculation};
262 my $urlbase="do_it=1&".join("&",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref);
263 foreach my $row (sort @loopline) {
265 #@loopcol ensures the order for columns is common with column titles
266 # and the number matches the number of columns
267 foreach my $col (sort keys %cols_hash) {
268 push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""),
269 # url_complement=>($urlbase=~/&$/?$urlbase."&":$urlbase)."filter_$linefield=$row&filter_$colfield=$col"
273 'rowtitle_display' => display_value($linefield,$row),
275 'loopcell' => \@loopcell,
276 'totalrow' => $$data{$row}{totalrow}
279 for my $col ( sort keys %cols_hash ) {
281 foreach my $row (@loopline) {
282 $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation};
284 push @loopfooter, {'totalcol' => $total};
285 push @loopcol, {'coltitle' => $col,
286 coltitle_display=>display_value($colfield,$col)};
288 # the header of the table
289 $globalline{loopfilter}=\@loopfilter;
290 # the core of the table
291 $globalline{looprow} = \@looprow;
292 $globalline{loopcol} = \@loopcol;
293 # # the foot (totals by borrower type)
294 $globalline{loopfooter} = \@loopfooter;
295 $globalline{total} = $grantotal;
296 $globalline{line} = $linefield;
297 $globalline{column} = $colfield;
298 return [(\%globalline)];
302 my ( $crit, $value ) = @_;
303 my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) };
304 my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) };
305 my $Bsort1 = GetAuthorisedValues("Bsort1");
306 my $Bsort2 = GetAuthorisedValues("Bsort2");
308 ( $crit =~ /ccode/ ) ? $ccodes->{$value}
309 : ( $crit =~ /location/ ) ? $locations->{$value}
310 : ( $crit =~ /itemtype/ ) ? Koha::ItemTypes->find( $value )->translated_description
311 : ( $crit =~ /branch/ ) ? Koha::Libraries->find($value)->branchname
312 : ( $crit =~ /reservestatus/ ) ? reservestatushuman($value)
313 : $value; # default fallback
314 if ($crit =~ /sort1/) {
316 ($value eq $_->{authorised_value}) or next;
317 $display_value = $_->{lib} and last;
320 elsif ($crit =~ /sort2/) {
322 ($value eq $_->{authorised_value}) or next;
323 $display_value = $_->{lib} and last;
326 elsif ( $crit =~ /category/ ) {
327 my @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']})->as_list;
328 foreach my $patron_category ( @patron_categories ) {
329 ( $value eq $patron_category->categorycode ) or next;
330 $display_value = $patron_category->description and last;
333 return $display_value;
336 sub reservestatushuman{
349 sub changeifreservestatus{
351 ($val=~/reservestatus/
353 when priority>0 then 1
356 when found='f' then 4
359 when cancellationdate is null then 3