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