fix step to install Indexdata apt key
[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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22 use CGI;
23 use C4::Auth;
24 use C4::Output;
25 use C4::Context;
26 use C4::Branch; # GetBranches
27 use C4::Koha;
28 use C4::Circulation;
29 use C4::Members;
30 use C4::Reports;
31 use C4::Debug;
32 use C4::Dates qw(format_date format_date_in_iso);
33
34 =head1 NAME
35
36 plugin that shows a stats on borrowers
37
38 =head1 DESCRIPTION
39
40 =over 2
41
42 =cut
43
44 $debug = 1;
45 $debug and open DEBUG, ">/tmp/bor_issues_top.debug.log";
46
47 my $input = new CGI;
48 my $fullreportname = "reports/bor_issues_top.tmpl";
49 my $do_it   = $input->param('do_it');
50 my $limit   = $input->param("Limit");
51 my $column  = $input->param("Criteria");
52 my @filters = $input->param("Filter");
53 foreach ( @filters[0..3] ) {
54         $_ and $_ = format_date_in_iso($_);     
55 }
56 my $output   = $input->param("output");
57 my $basename = $input->param("basename");
58 # my $mime     = $input->param("MIME");
59 my ($template, $borrowernumber, $cookie)
60     = get_template_and_user({template_name => $fullreportname,
61                 query => $input,
62                 type => "intranet",
63                 authnotrequired => 0,
64                 flagsrequired => {reports => '*'},
65                 debug => 1,
66                 });
67 our $sep     = $input->param("sep");
68 $sep = "\t" if ($sep eq 'tabulation');
69 $template->param(do_it => $do_it,
70         DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
71         );
72 if ($do_it) {
73 # Displaying results
74     my $results = calculate($limit, $column, \@filters);
75     if ($output eq "screen"){
76 # Printing results to screen
77         $template->param(mainloop => $results, limit=>$limit);
78         output_html_with_http_headers $input, $cookie, $template->output;
79     } else {
80 # Printing to a csv file
81         print $input->header(-type => 'application/vnd.sun.xml.calc',
82                             -encoding    => 'utf-8',
83                             -attachment=>"$basename.csv",
84                             -filename=>"$basename.csv" );
85         my $cols  = @$results[0]->{loopcol};
86         my $lines = @$results[0]->{looprow};
87 # header top-right
88         print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
89 # Other header
90                 print join($sep, map {$_->{coltitle}} @$cols);
91         print $sep . "Total\n";
92 # Table
93         foreach my $line ( @$lines ) {
94             my $x = $line->{loopcell};
95             print $line->{rowtitle}.$sep;
96                         print join($sep, map {$_->{value}} @$x);
97             print $sep,$line->{totalrow};
98             print "\n";
99         }
100 # footer
101         print "TOTAL";
102         $cols = @$results[0]->{loopfooter};
103                 print join($sep, map {$_->{totalcol}} @$cols);
104         print $sep.@$results[0]->{total};
105     }
106     exit(1);
107 }
108
109 my $dbh = C4::Context->dbh;
110 my @values;
111
112 # here each element returned by map is a hashref, get it?
113 my @mime  = ( map { {type =>$_} } (split /[;:]/,C4::Context->preference("MIME")) );
114 my $delims = GetDelimiterChoices;
115 my $branches = GetBranches;
116 my @branchloop;
117 foreach (sort keys %$branches) {
118 #       my $selected = 1 if $thisbranch eq $branch;
119         my %row = ( value => $_,
120 #                               selected => $selected,
121                                 branchname => $branches->{$_}->{branchname},
122                         );
123         push @branchloop, \%row;
124 }
125
126 my $itemtypes = GetItemTypes;
127 my @itemtypeloop;
128 foreach (sort {$itemtypes->{$a}->{description} cmp $itemtypes->{$b}->{description}} keys %$itemtypes) {
129         my %row = (value => $_,
130                description => $itemtypes->{$_}->{description},
131               );
132     push @itemtypeloop, \%row;
133 }
134     
135 my ($codes,$labels) = GetborCatFromCatType(undef,undef);
136 my @borcatloop;
137 foreach (sort keys %$labels) {
138         my %row =(value => $_,
139               description => $labels->{$_},
140              );
141     push @borcatloop, \%row;
142 }
143     
144 $template->param(
145             mimeloop => \@mime,
146           CGIseplist => $delims,
147           branchloop => \@branchloop,
148         itemtypeloop => \@itemtypeloop,
149           borcatloop => \@borcatloop,
150 );
151 output_html_with_http_headers $input, $cookie, $template->output;
152
153
154 sub calculate {
155     my ($line, $column, $filters) = @_;
156     my @loopcol;
157     my @loopline;
158     my @looprow;
159     my %globalline;
160         my %columns;
161     my $grantotal =0;
162     my $dbh = C4::Context->dbh;
163
164 # Checking filters
165     my @loopfilter;
166         my @cellmap = (
167                 "Issue From",
168                 "Issue To",
169                 "Return From",
170                 "Return To",
171                 "Branch",
172                 "Doc Type",
173                 "Bor Cat",
174                 "Day",
175                 "Month",
176                 "Year"
177         );
178     for (my $i=0;$i<=6;$i++) {
179         my %cell;
180         if ( @$filters[$i] ) {
181             if (($i==1) and (@$filters[$i-1])) {
182                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
183             }
184             # format the dates filters, otherwise just fill as is
185             $cell{filter} .= ($i>=4) ? @$filters[$i] : format_date(@$filters[$i]);
186                         defined ($cellmap[$i]) and
187                                 $cell{crit} .= $cellmap[$i];
188             push @loopfilter, \%cell;
189         }
190     }
191     my $colfield;
192     my $colorder;
193     if ($column){
194         $column = "old_issues." .$column if (($column=~/branchcode/) or ($column=~/timestamp/));
195         $column = "biblioitems.".$column if $column=~/itemtype/;
196         $column = "borrowers."  .$column if $column=~/categorycode/;
197         my @colfilter ;
198                 if ($column =~ /timestamp/) {
199                 $colfilter[0] = @$filters[0];
200                 $colfilter[1] = @$filters[1];
201                 } elsif ($column =~ /returndate/) {
202                 $colfilter[0] = @$filters[2];
203                 $colfilter[1] = @$filters[3];
204                 } elsif ($column =~ /branchcode/) {
205                         $colfilter[0] = @$filters[4];
206                 } elsif ($column =~ /itemtype/) {
207                         $colfilter[0] = @$filters[5];
208                 } elsif ($column =~ /category/) {
209                         $colfilter[0] = @$filters[6];
210                 } elsif ($column =~ /sort2/   ) {
211                         # $colfilter[0] = @$filters[11];
212                 }
213         # $colfilter[0] = @$filters[7] if ($column =~ /timestamp/ ) ; FIXME This can't be right.
214         # $colfilter[0] = @$filters[8] if ($column =~ /timestamp/ ) ; FIXME 
215         # $colfilter[0] = @$filters[9] if ($column =~ /timestamp/ ) ; FIXME Only this line would have effect.
216
217     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
218                                                 
219     # loop cols.
220         if ($column eq "Day") {
221             #Display by day
222             $column = "old_issues.timestamp";
223             $colfield .="dayname($column)";  
224             $colorder .="weekday($column)";
225         } elsif ($column eq "Month") {
226             #Display by Month
227             $column = "old_issues.timestamp";
228             $colfield .="monthname($column)";  
229             $colorder .="month($column)";  
230         } elsif ($column eq "Year") {
231             #Display by Year
232             $column = "old_issues.timestamp";
233             $colfield .="Year($column)";
234             $colorder .= $column;
235         } else {
236             $colfield .= $column;
237             $colorder .= $column;
238         }  
239
240         my $strsth2;
241         $strsth2 .= "SELECT DISTINCTROW $colfield 
242                      FROM `old_issues` 
243                      LEFT JOIN borrowers   ON old_issues.borrowernumber=borrowers.borrowernumber 
244                      LEFT JOIN items       ON old_issues.itemnumber=items.itemnumber 
245                      LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
246                      WHERE 1";
247         if (($column=~/timestamp/) or ($column=~/returndate/)){
248             if ($colfilter[1] and $colfilter[0]){
249                 $strsth2 .= " AND $column between '$colfilter[0]' AND '$colfilter[1]' " ;
250             } elsif ($colfilter[1]) {
251                 $strsth2 .= " AND $column < '$colfilter[1]' " ;
252             } elsif ($colfilter[0]) {
253                 $strsth2 .= " AND $column > '$colfilter[0]' " ;
254             }
255         } elsif ($colfilter[0]) {
256             $colfilter[0] =~ s/\*/%/g;
257             $strsth2 .= " AND $column LIKE '$colfilter[0]' " ;
258         }
259         $strsth2 .=" GROUP BY $colfield";
260         $strsth2 .=" ORDER BY $colorder";
261
262         $debug and print DEBUG "bor_issues_top (old_issues) SQL: $strsth2\n";
263         my $sth2 = $dbh->prepare($strsth2);
264         $sth2->execute;
265         print DEBUG "rows: ", $sth2->rows, "\n";
266         while (my @row = $sth2->fetchrow) {
267                         $columns{($row[0] ||'NULL')}++;
268             push @loopcol, { coltitle => $row[0] || 'NULL' };
269         }
270
271                 $strsth2 =~ s/old_issues/issues/g;
272         $debug and print DEBUG "bor_issues_top (issues) SQL: $strsth2\n";
273                 $sth2 = $dbh->prepare($strsth2);
274         $sth2->execute;
275         $debug and print DEBUG "rows: ", $sth2->rows, "\n";
276         while (my @row = $sth2->fetchrow) {
277                         $columns{($row[0] ||'NULL')}++;
278             push @loopcol, { coltitle => $row[0] || 'NULL' };
279         }
280                 $debug and print DEBUG "full array: ", Dumper(\%columns), "\n";
281     }else{
282         $columns{''} = 1;
283     }
284
285     #Initialization of cell values.....
286     my @table;
287     for (my $i=1;$i<=$line;$i++) {
288         foreach (keys %columns) {
289 #                       warn " init table : $row->{rowtitle} / $_ ";
290             $table[$i]->{ $_ || "total" }->{'name'}=0;
291         }
292     }
293
294     my $strcalc ;
295
296 # Processing average loanperiods
297     $strcalc .= "SELECT  CONCAT(borrowers.surname , \",\\t\",borrowers.firstname),  COUNT(*) AS RANK, borrowers.borrowernumber AS ID";
298     $strcalc .= " , $colfield " if ($colfield);
299     $strcalc .= " FROM `old_issues`
300                   LEFT JOIN  borrowers  ON old_issues.borrowernumber=borrowers.borrowernumber
301                   LEFT JOIN    items    ON items.itemnumber=old_issues.itemnumber
302                   LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
303                   WHERE 1";
304         my @filterterms = (
305                 'old_issues.timestamp  >',
306                 'old_issues.timestamp  <',
307                 'old_issues.returndate >',
308                 'old_issues.returndate <',
309                 'old_issues.branchcode  like',
310                 'biblioitems.itemtype   like',
311                 'borrowers.categorycode like',
312                 'dayname(old_issues.timestamp) like',
313                 'monthname(old_issues.timestamp) like',
314                 'monthname(old_issues.timestamp) like',
315                 'year(old_issues.timestamp) like',
316         );
317     foreach ((@$filters)[0..9]) {
318                 my $term = shift @filterterms;  # go through both arrays in step
319                 ($_) or next;
320                 s/\*/%/g;
321                 $strcalc .= " AND $term '$_' ";
322         }
323     
324     $strcalc .= " GROUP BY borrowers.borrowernumber";
325     $strcalc .= ", $colfield" if ($column);
326     $strcalc .= " ORDER BY RANK DESC";
327     $strcalc .= ",$colfield " if ($colfield);
328 #       my $max;
329 #       if (@loopcol) {
330 #               $max = $line*@loopcol;
331 #       } else { $max=$line;}
332 #       $strcalc .= " LIMIT 0,$max";
333
334     $debug and print DEBUG "(old_issues) SQL : $strcalc\n";
335     my $dbcalc = $dbh->prepare($strcalc);
336     $dbcalc->execute;
337     $debug and print DEBUG "rows: ", $dbcalc->rows, "\n";
338         my %patrons = ();
339         # DATA STRUCTURE is going to look like this:
340         #       (2253=> {name=>"John Doe",
341         #                               allcols=>{MAIN=>12, MEDIA_LIB=>3}
342         #                       },
343         #       )
344     while (my @data = $dbcalc->fetchrow) {
345         my ($row, $rank, $id, $col) = @data;
346         $col = "zzEMPTY" if (!defined($col));
347                 unless ($patrons{$id}) {
348                         $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}};
349                 }
350                 $patrons{$id}->{oldcols}->{$col} = $rank;
351     }
352
353         use Data::Dumper;
354
355         $strcalc =~ s/old_issues/issues/g;
356     $debug and print DEBUG "(issues) SQL : $strcalc\n";
357     $dbcalc = $dbh->prepare($strcalc);
358     $dbcalc->execute;
359     $debug and print DEBUG "rows: ", $dbcalc->rows, "\n";
360     while (my @data = $dbcalc->fetchrow) {
361         my ($row, $rank, $id, $col) = @data;
362         $col = "zzEMPTY" if (!defined($col));
363                 unless ($patrons{$id}) {
364                         $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}};
365                 }
366                 $patrons{$id}->{newcols}->{$col} = $rank;
367     }
368
369         foreach my $id (keys %patrons) {
370                 my @uniq = keys %{{ %{$patrons{$id}->{newcols}}, %{$patrons{$id}->{oldcols}} }};                # get uniq keys, see perlfaq4
371                 foreach (@uniq) {
372                         my $count = ($patrons{$id}->{newcols}->{$_} || 0) +
373                                                 ($patrons{$id}->{oldcols}->{$_} || 0);
374                         $patrons{$id}->{allcols}->{$_} = $count;
375                         $patrons{$id}->{total} += $count;
376                 }
377         }
378     $debug and print DEBUG "\n\npatrons: ", Dumper(\%patrons);
379     
380         my $i = 1;
381         my @cols_in_order = sort keys %columns;         # if you want to order the columns, do something here
382         my @ranked_ids = sort {
383                                                    $patrons{$b}->{total} <=> $patrons{$a}->{total}
384                                                 || $patrons{$a}->{name}  cmp $patrons{$b}->{name}
385                                                 } keys %patrons;
386     foreach my $id (@ranked_ids) {
387         my @loopcell;
388         foreach my $key (@cols_in_order) {
389                         if($column){
390                       push @loopcell, {
391                                 value => $patrons{$id}->{name},
392                                 reference => $id,
393                                 count => $patrons{$id}->{allcols}->{$key},
394                           };
395                         }else{
396                           push @loopcell, {
397                                 value => $patrons{$id}->{name},
398                                 reference => $id,
399                                 count => $patrons{$id}->{total},
400                           };  
401                         }
402         }
403         push @looprow,{ 'rowtitle' => $i++ ,
404                         'loopcell' => \@loopcell,
405                         'hilighted' => ($i%2),
406                     };
407     }
408         
409     # the header of the table
410     $globalline{loopfilter}=\@loopfilter;
411     # the core of the table
412     $globalline{looprow} = \@looprow;
413     $globalline{loopcol} = [ map {{coltitle=>$_}} @cols_in_order ];
414         # the foot (totals by borrower type)
415     $globalline{loopfooter} = [];
416     $globalline{total}= $grantotal;             # FIXME: useless
417     $globalline{line} = $line;
418     $globalline{column} = $column;
419     return [\%globalline];      # reference to a 1 element array: that element is a hashref
420 }
421
422 $debug and close DEBUG;
423 1;
424 __END__