Bug 28523: Escape 'rank' in bor_issues_top.pl
[koha.git] / reports / bor_issues_top.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
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 use C4::Auth;
24 use C4::Output;
25 use C4::Context;
26 use C4::Koha;
27 use C4::Circulation;
28 use C4::Members;
29 use C4::Reports;
30
31 use Koha::DateUtils;
32 use Koha::ItemTypes;
33 use Koha::Patron::Categories;
34
35 =head1 NAME
36
37 plugin that shows a stats on borrowers
38
39 =head1 DESCRIPTION
40
41 =cut
42
43 my $input = CGI->new;
44 my $fullreportname = "reports/bor_issues_top.tt";
45 my $do_it   = $input->param('do_it');
46 my $limit   = $input->param("Limit");
47 my $column  = $input->param("Criteria");
48 my @filters = $input->multi_param("Filter");
49 foreach ( @filters[0..3] ) {
50     $_ and $_ = eval { output_pref( { dt => dt_from_string ( $_ ), dateonly => 1, dateformat => 'iso' }); };
51 }
52 my $output   = $input->param("output");
53 my $basename = $input->param("basename");
54 my ($template, $borrowernumber, $cookie)
55     = get_template_and_user({template_name => $fullreportname,
56                 query => $input,
57                 type => "intranet",
58                 flagsrequired => {reports => '*'},
59                 });
60 our $sep     = $input->param("sep") || C4::Context->preference('CSVDelimiter') || ',';
61 $sep = "\t" if ($sep eq 'tabulation');
62 $template->param(do_it => $do_it,
63         );
64 if ($do_it) {
65 # Displaying results
66     my $results = calculate($limit, $column, \@filters);
67     if ($output eq "screen"){
68 # Printing results to screen
69         $template->param(mainloop => $results, limit=>$limit);
70         output_html_with_http_headers $input, $cookie, $template->output;
71     } else {
72 # Printing to a csv file
73         print $input->header(-type => 'application/vnd.sun.xml.calc',
74                             -encoding    => 'utf-8',
75                             -attachment=>"$basename.csv",
76                             -filename=>"$basename.csv" );
77         my $cols  = @$results[0]->{loopcol};
78         my $lines = @$results[0]->{looprow};
79 # header top-right
80         print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
81 # Other header
82                 print join($sep, map {$_->{coltitle}} @$cols);
83         print $sep . "Total\n";
84 # Table
85         foreach my $line ( @$lines ) {
86             my $x = $line->{loopcell};
87             print $line->{rowtitle}.$sep;
88                         print join($sep, map {$_->{value}} @$x);
89             print $sep,$line->{totalrow};
90             print "\n";
91         }
92 # footer
93         print "TOTAL";
94         $cols = @$results[0]->{loopfooter};
95                 print join($sep, map {$_->{totalcol}} @$cols);
96         print $sep.@$results[0]->{total};
97     }
98     exit;
99 }
100
101 my $dbh = C4::Context->dbh;
102
103 # here each element returned by map is a hashref, get it?
104 my @mime  = ( map { {type =>$_} } (split /[;:]/, 'CSV') ); # FIXME translation
105 my $delims = GetDelimiterChoices;
106
107 my $patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['categorycode']});
108 my $itemtypes = Koha::ItemTypes->search_with_localization;
109 $template->param(
110             mimeloop => \@mime,
111           CGIseplist => $delims,
112       itemtypes => $itemtypes,
113 patron_categories => $patron_categories,
114 );
115 output_html_with_http_headers $input, $cookie, $template->output;
116
117
118 sub calculate {
119     my ($limit, $column, $filters) = @_;
120
121     my @loopcol;
122     my @looprow;
123     my %globalline;
124         my %columns;
125     my $grantotal =0;
126     my $dbh = C4::Context->dbh;
127
128
129 # Checking filters
130     my @loopfilter;
131         my @cellmap = (
132                 "Issue From",
133                 "Issue To",
134                 "Return From",
135                 "Return To",
136                 "Branch",
137                 "Doc Type",
138                 "Bor Cat",
139                 "Day",
140                 "Month",
141                 "Year"
142         );
143     for (my $i=0;$i<=6;$i++) {
144         my %cell;
145         if ( @$filters[$i] ) {
146             if (($i==1) and (@$filters[$i-1])) {
147                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
148             }
149             # format the dates filters, otherwise just fill as is
150             $cell{filter} .= @$filters[$i];
151                         defined ($cellmap[$i]) and
152                                 $cell{crit} .= $cellmap[$i];
153             push @loopfilter, \%cell;
154         }
155     }
156     my $colfield;
157     my $colorder;
158     if ($column){
159         $column = "old_issues." .$column if (($column=~/branchcode/) or ($column=~/timestamp/));
160         $column = "biblioitems.".$column if $column=~/itemtype/;
161         $column = "borrowers."  .$column if $column=~/categorycode/;
162         my @colfilter ;
163                 if ($column =~ /timestamp/) {
164                 $colfilter[0] = @$filters[0];
165                 $colfilter[1] = @$filters[1];
166                 } elsif ($column =~ /returndate/) {
167                 $colfilter[0] = @$filters[2];
168                 $colfilter[1] = @$filters[3];
169                 } elsif ($column =~ /branchcode/) {
170                         $colfilter[0] = @$filters[4];
171                 } elsif ($column =~ /itemtype/) {
172                         $colfilter[0] = @$filters[5];
173                 } elsif ($column =~ /category/) {
174                         $colfilter[0] = @$filters[6];
175                 } elsif ($column =~ /sort2/   ) {
176                         # $colfilter[0] = @$filters[11];
177                 }
178                                                 
179     # loop cols.
180         if ($column eq "Day") {
181             #Display by day
182             $column = "old_issues.timestamp";
183             $colfield .="dayname($column)";  
184             $colorder .="weekday($column)";
185         } elsif ($column eq "Month") {
186             #Display by Month
187             $column = "old_issues.timestamp";
188             $colfield .="monthname($column)";  
189             $colorder .="month($column)";  
190         } elsif ($column eq "Year") {
191             #Display by Year
192             $column = "old_issues.timestamp";
193             $colfield .="Year($column)";
194             $colorder .= $column;
195         } else {
196             $colfield .= $column;
197             $colorder .= $column;
198         }  
199
200         my $strsth2;
201         $strsth2 .= "SELECT DISTINCTROW $colfield 
202                      FROM `old_issues` 
203                      LEFT JOIN borrowers   ON old_issues.borrowernumber=borrowers.borrowernumber 
204                      LEFT JOIN items       ON old_issues.itemnumber=items.itemnumber 
205                      LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
206                      WHERE 1";
207         if (($column=~/timestamp/) or ($column=~/returndate/)){
208             if ($colfilter[1] and $colfilter[0]){
209                 $strsth2 .= " AND $column between '$colfilter[0]' AND '$colfilter[1]' " ;
210             } elsif ($colfilter[1]) {
211                 $strsth2 .= " AND $column < '$colfilter[1]' " ;
212             } elsif ($colfilter[0]) {
213                 $strsth2 .= " AND $column > '$colfilter[0]' " ;
214             }
215         } elsif ($colfilter[0]) {
216             $colfilter[0] =~ s/\*/%/g;
217             $strsth2 .= " AND $column LIKE '$colfilter[0]' " ;
218         }
219         $strsth2 .=" GROUP BY $colfield";
220         $strsth2 .=" ORDER BY $colorder";
221
222         my $sth2 = $dbh->prepare($strsth2);
223         $sth2->execute;
224         while (my @row = $sth2->fetchrow) {
225                         $columns{($row[0] ||'NULL')}++;
226             push @loopcol, { coltitle => $row[0] || 'NULL' };
227         }
228
229                 $strsth2 =~ s/old_issues/issues/g;
230                 $sth2 = $dbh->prepare($strsth2);
231         $sth2->execute;
232         while (my @row = $sth2->fetchrow) {
233                         $columns{($row[0] ||'NULL')}++;
234             push @loopcol, { coltitle => $row[0] || 'NULL' };
235         }
236     }else{
237         $columns{''} = 1;
238     }
239
240     my $strcalc ;
241
242 # Processing average loanperiods
243     $strcalc .= "SELECT  CONCAT_WS('', borrowers.surname , \",\\t\", borrowers.firstname),  COUNT(*) AS `RANK`, borrowers.borrowernumber AS ID";
244     $strcalc .= " , $colfield " if ($colfield);
245     $strcalc .= " FROM `old_issues`
246                   LEFT JOIN  borrowers  USING(borrowernumber)
247                   LEFT JOIN    items    USING(itemnumber)
248                   LEFT JOIN biblioitems USING(biblioitemnumber)
249                   WHERE old_issues.borrowernumber IS NOT NULL
250                   ";
251         my @filterterms = (
252                 'old_issues.issuedate >',
253                 'old_issues.issuedate <',
254                 'old_issues.returndate >',
255                 'old_issues.returndate <',
256                 'old_issues.branchcode  like',
257                 'biblioitems.itemtype   like',
258                 'borrowers.categorycode like',
259         );
260     foreach ((@$filters)[0..9]) {
261                 my $term = shift @filterterms;  # go through both arrays in step
262                 ($_) or next;
263                 s/\*/%/g;
264                 $strcalc .= " AND $term '$_' ";
265         }
266     $strcalc .= " GROUP BY borrowers.borrowernumber";
267     $strcalc .= ", $colfield" if ($column);
268     $strcalc .= " ORDER BY `RANK` DESC";
269     $strcalc .= ",$colfield " if ($colfield);
270     $strcalc .= " LIMIT $limit" if ($limit);
271
272     my $dbcalc = $dbh->prepare($strcalc);
273     $dbcalc->execute;
274         my %patrons = ();
275         # DATA STRUCTURE is going to look like this:
276         #       (2253=> {name=>"John Doe",
277         #                               allcols=>{MAIN=>12, MEDIA_LIB=>3}
278         #                       },
279         #       )
280     while (my @data = $dbcalc->fetchrow) {
281         my ($row, $rank, $id, $col) = @data;
282         $col = "zzEMPTY" if (!defined($col));
283                 unless ($patrons{$id}) {
284                         $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}};
285                 }
286                 $patrons{$id}->{oldcols}->{$col} = $rank;
287     }
288
289         use Data::Dumper;
290
291         $strcalc =~ s/old_issues/issues/g;
292     $dbcalc = $dbh->prepare($strcalc);
293     $dbcalc->execute;
294     while (my @data = $dbcalc->fetchrow) {
295         my ($row, $rank, $id, $col) = @data;
296         $col = "zzEMPTY" if (!defined($col));
297                 unless ($patrons{$id}) {
298                         $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}};
299                 }
300                 $patrons{$id}->{newcols}->{$col} = $rank;
301     }
302
303         foreach my $id (keys %patrons) {
304                 my @uniq = keys %{{ %{$patrons{$id}->{newcols}}, %{$patrons{$id}->{oldcols}} }};                # get uniq keys, see perlfaq4
305                 foreach (@uniq) {
306                         my $count = ($patrons{$id}->{newcols}->{$_} || 0) +
307                                                 ($patrons{$id}->{oldcols}->{$_} || 0);
308                         $patrons{$id}->{allcols}->{$_} = $count;
309                         $patrons{$id}->{total} += $count;
310                 }
311         }
312     
313         my $i = 1;
314         my @cols_in_order = sort keys %columns;         # if you want to order the columns, do something here
315         my @ranked_ids = sort {
316                                                    $patrons{$b}->{total} <=> $patrons{$a}->{total}
317                                                 || $patrons{$a}->{name}  cmp $patrons{$b}->{name}
318                                                 } keys %patrons;
319     foreach my $id (@ranked_ids) {
320         my @loopcell;
321
322         foreach my $key (@cols_in_order) {
323                         if($column){
324                       push @loopcell, {
325                                 value => $patrons{$id}->{name},
326                                 reference => $id,
327                                 count => $patrons{$id}->{allcols}->{$key},
328                           };
329                         }else{
330                           push @loopcell, {
331                                 value => $patrons{$id}->{name},
332                                 reference => $id,
333                                 count => $patrons{$id}->{total},
334                           };  
335                         }
336         }
337         push @looprow,{ 'rowtitle' => $i++ ,
338                         'loopcell' => \@loopcell,
339                         'hilighted' => ($i%2),
340                     };
341         # use a limit, if a limit is defined
342         last if $i > $limit and $limit
343     }
344
345     # the header of the table
346     $globalline{loopfilter}=\@loopfilter;
347     # the core of the table
348     $globalline{looprow} = \@looprow;
349     $globalline{loopcol} = [ map {{coltitle=>$_}} @cols_in_order ];
350         # the foot (totals by borrower type)
351     $globalline{loopfooter} = [];
352     $globalline{total}= $grantotal;             # FIXME: useless
353     $globalline{column} = $column;
354     return [\%globalline];      # reference to a 1 element array: that element is a hashref
355 }
356
357 1;
358 __END__