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