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