Bug 16653: Display number of checkouts when exporting 'Most-circulated items' as CSV
[koha.git] / reports / cat_issues_top.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use Modern::Perl;
22 use C4::Auth;
23 use CGI qw ( -utf8 );
24 use C4::Context;
25 use C4::Output;
26 use C4::Koha;
27 use C4::Circulation;
28 use C4::Reports;
29 use C4::Members;
30 use Koha::DateUtils;
31 use Koha::ItemTypes;
32
33 =head1 NAME
34
35 plugin that shows a stats on borrowers
36
37 =head1 DESCRIPTION
38
39 =cut
40
41 my $input = new CGI;
42 my $do_it=$input->param('do_it');
43 my $fullreportname = "reports/cat_issues_top.tt";
44 my $limit = $input->param("Limit");
45 my $column = $input->param("Criteria");
46 my @filters = $input->multi_param("Filter");
47 foreach ( @filters[0..3] ) {
48     $_ and $_ = eval { output_pref( { dt => dt_from_string ( $_ ), dateonly => 1, dateformat => 'iso' } ); };
49 }
50
51 my $output = $input->param("output");
52 my $basename = $input->param("basename");
53 #warn "calcul : ".$calc;
54 my ($template, $borrowernumber, $cookie)
55     = get_template_and_user({template_name => $fullreportname,
56                 query => $input,
57                 type => "intranet",
58                 authnotrequired => 0,
59                 flagsrequired => { reports => '*'},
60                 debug => 1,
61                 });
62 our $sep     = $input->param("sep");
63 $sep = "\t" if ($sep eq 'tabulation');
64 $template->param(do_it => $do_it,
65         );
66 if ($do_it) {
67 # Displaying results
68     my $results = calculate($limit, $column, \@filters);
69     if ($output eq "screen"){
70 # Printing results to screen
71         $template->param(mainloop => $results,
72                         limit => $limit);
73         output_html_with_http_headers $input, $cookie, $template->output;
74         exit;
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         foreach my $col ( @$cols ) {
87             print $col->{coltitle}.$sep;
88         }
89         print "Total\n";
90 # Table
91         foreach my $line ( @$lines ) {
92             my $x = $line->{loopcell};
93             print $line->{rowtitle}.$sep;
94             foreach my $cell (@$x) {
95                 print $cell->{value}.$sep;
96                 print $cell->{count};
97             }
98             print "\n";
99         }
100         exit;
101     }
102 # Displaying choices
103 } else {
104     my $dbh = C4::Context->dbh;
105     my @values;
106     my %labels;
107     my %select;
108     my $req;
109     
110     my $CGIextChoice = ( 'CSV' ); # FIXME translation
111     my $CGIsepChoice=GetDelimiterChoices;
112
113     #doctype
114     my $itemtypes = Koha::ItemTypes->search_with_localization;
115
116     #ccode
117     my $ccodes = GetAuthorisedValues('CCODE');
118     my @ccodeloop;
119     for my $thisccode (@$ccodes) {
120             my %row = (value => $thisccode->{authorised_value},
121                        description => $thisccode->{lib},
122                             );
123             push @ccodeloop, \%row;
124     }
125
126     @ccodeloop = sort {$a->{value} cmp $b->{value}} @ccodeloop;
127
128     #shelvingloc
129     my $shelvinglocs = GetAuthorisedValues('LOC');
130     my @shelvinglocloop;
131     for my $thisloc (@$shelvinglocs) {
132             my %row = (value => $thisloc->{authorised_value},
133                        description => $thisloc->{lib},
134                             );
135             push @shelvinglocloop, \%row;
136     }
137
138     @shelvinglocloop = sort {$a->{value} cmp $b->{value}} @shelvinglocloop;
139
140     my $patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['categorycode']});
141
142     $template->param(
143                     CGIextChoice => $CGIextChoice,
144                     CGIsepChoice => $CGIsepChoice,
145                     itemtypes => $itemtypes,
146                     ccodeloop =>\@ccodeloop,
147                     shelvinglocloop =>\@shelvinglocloop,
148                     patron_categories => $patron_categories,
149                     );
150 output_html_with_http_headers $input, $cookie, $template->output;
151 }
152
153
154
155
156 sub calculate {
157     my ($line, $column, $filters) = @_;
158     my @mainloop;
159     my @loopcol;
160     my @loopline;
161     my @looprow;
162     my %globalline;
163     my $grantotal =0;
164 # extract parameters
165     my $dbh = C4::Context->dbh;
166
167 # Filters
168 # Checking filters
169 #
170     my @loopfilter;
171     for (my $i=0;$i<=12;$i++) {
172         my %cell;
173         if ( @$filters[$i] ) {
174             if (($i==1) and (@$filters[$i-1])) {
175                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
176             }
177             # format the dates filters, otherwise just fill as is
178             if ($i>=2) {
179                 $cell{filter} .= @$filters[$i];
180             } else {
181                 $cell{filter} .= eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
182                    if ( @$filters[$i] );
183             }
184             $cell{crit} .="Issue From" if ($i==0);
185             $cell{crit} .="Issue To" if ($i==1);
186             $cell{crit} .="Return From" if ($i==2);
187             $cell{crit} .="Return To" if ($i==3);
188             $cell{crit} .="Branch" if ($i==4);
189             $cell{crit} .="Doc Type" if ($i==5);
190             $cell{crit} .="Call number" if ($i==6);
191             $cell{crit} .="Collection code" if ($i==7);
192             $cell{crit} .="Shelving location" if ($i==8);
193             $cell{crit} .="Bor Cat" if ($i==9);
194             $cell{crit} .="Day" if ($i==10);
195             $cell{crit} .="Month" if ($i==11);
196             $cell{crit} .="Year" if ($i==12);
197             push @loopfilter, \%cell;
198         }
199     }
200     my $colfield;
201     my $colorder;
202     if ($column){
203         $column = "old_issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/));
204         if($column=~/itemtype/){
205             $column = C4::Context->preference('item-level_itypes') ? "items.itype": "biblioitems.itemtype";
206         }
207         $column = "borrowers.".$column if $column=~/categorycode/;
208         my @colfilter ;
209         $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ )  ;
210         $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ )  ;
211         $colfilter[0] = @$filters[2] if ($column =~ /returndate/ )  ;
212         $colfilter[1] = @$filters[3] if ($column =~ /returndate/ )  ;
213         $colfilter[0] = @$filters[4] if ($column =~ /branch/ )  ;
214         $colfilter[0] = @$filters[5] if ($column =~ /itemtype/ )  ;
215       # These limits does not currently exist, maybe later?
216       # $colfilter[0] = @$filters[6] if ($column =~ /ccode/ )  ;
217       # $colfilter[0] = @$filters[7] if ($column =~ /location/ )  ;
218         $colfilter[0] = @$filters[8] if ($column =~ /category/ )  ;
219       # This commented out row (sort2) was not removed when adding new filters for ccode, shelving location and call number
220       # $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
221         $colfilter[0] = @$filters[9] if ($column =~ /timestamp/ ) ;
222         $colfilter[0] = @$filters[10] if ($column =~ /timestamp/ ) ;
223         $colfilter[0] = @$filters[11] if ($column =~ /timestamp/ ) ;
224     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
225                                                 
226     # loop cols.
227         if ($column eq "Day") {
228             #Display by day
229             $column = "old_issues.timestamp";
230             $colfield .="dayname($column)";  
231             $colorder .="weekday($column)";
232         } elsif ($column eq "Month") {
233             #Display by Month
234             $column = "old_issues.timestamp";
235             $colfield .="monthname($column)";  
236             $colorder .="month($column)";  
237         } elsif ($column eq "Year") {
238             #Display by Year
239             $column = "old_issues.timestamp";
240             $colfield .="Year($column)";
241             $colorder .= $column;
242         } else {
243             $colfield .= $column;
244             $colorder .= $column;
245         }  
246         
247         my $strsth2;
248         $strsth2 .= "SELECT distinctrow $colfield 
249                      FROM `old_issues` 
250                      LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber 
251                      LEFT JOIN items ON old_issues.itemnumber=items.itemnumber 
252                      LEFT JOIN biblioitems  ON biblioitems.biblioitemnumber=items.biblioitemnumber 
253                      WHERE 1";
254         if (($column=~/timestamp/) or ($column=~/returndate/)){
255             if ($colfilter[1] and ($colfilter[0])){
256                 $strsth2 .= " and $column between '$colfilter[0]' and '$colfilter[1]' " ;
257             } elsif ($colfilter[1]) {
258                     $strsth2 .= " and $column < '$colfilter[1]' " ;
259             } elsif ($colfilter[0]) {
260                 $strsth2 .= " and $column > '$colfilter[0]' " ;
261             }
262         } elsif ($colfilter[0]) {
263             $colfilter[0] =~ s/\*/%/g;
264             $strsth2 .= " and $column LIKE '$colfilter[0]' " ;
265         }
266         $strsth2 .=" group by $colfield";
267         $strsth2 .=" order by $colorder";
268         
269         my $sth2 = $dbh->prepare( $strsth2 );
270         if (( @colfilter ) and ($colfilter[1])){
271             $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'");
272         } elsif ($colfilter[0]) {
273             $sth2->execute($colfilter[0]);
274         } else {
275             $sth2->execute;
276         }
277         
278     
279         while (my ($celvalue) = $sth2->fetchrow) {
280             my %cell;
281             $cell{coltitle} = ($celvalue?$celvalue:"NULL");
282             push @loopcol, \%cell;
283         }
284     #   warn "fin des titres colonnes";
285     }
286     
287     my $i=0;
288 #       my @totalcol;
289     my $hilighted=-1;
290     
291     #Initialization of cell values.....
292     my @table;
293     
294 #       warn "init table";
295     for (my $i=1;$i<=$line;$i++) {
296         foreach my $col ( @loopcol ) {
297 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
298             $table[$i]->{($col->{coltitle})?$col->{coltitle}:"total"}->{'name'}=0;
299         }
300     }
301
302
303 # preparing calculation
304     my $strcalc ;
305     
306 # Processing average loanperiods
307     $strcalc .= "SELECT DISTINCT biblio.title, COUNT(biblio.biblionumber) AS RANK, biblio.biblionumber AS ID";
308     $strcalc .= ", itemcallnumber as CALLNUM";
309     $strcalc .= ", ccode as CCODE";
310     $strcalc .= ", location as LOC";
311     $strcalc .= " , $colfield " if ($colfield);
312     $strcalc .= " FROM `old_issues` 
313                   LEFT JOIN items USING(itemnumber) 
314                   LEFT JOIN biblio USING(biblionumber) 
315                   LEFT JOIN biblioitems USING(biblionumber)
316                   LEFT JOIN borrowers USING(borrowernumber)
317                   WHERE 1";
318
319     @$filters[0]=~ s/\*/%/g if (@$filters[0]);
320     $strcalc .= " AND old_issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
321     @$filters[1]=~ s/\*/%/g if (@$filters[1]);
322     $strcalc .= " AND old_issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] );
323     @$filters[2]=~ s/\*/%/g if (@$filters[2]);
324     $strcalc .= " AND old_issues.returndate > '" . @$filters[2] ."'" if ( @$filters[2] );
325     @$filters[3]=~ s/\*/%/g if (@$filters[3]);
326     $strcalc .= " AND old_issues.returndate < '" . @$filters[3] ."'" if ( @$filters[3] );
327     @$filters[4]=~ s/\*/%/g if (@$filters[4]);
328     $strcalc .= " AND old_issues.branchcode like '" . @$filters[4] ."'" if ( @$filters[4] );
329     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
330     if ( @$filters[5] ){
331         if(C4::Context->preference('item-level_itypes') ){
332             $strcalc .= " AND items.itype like "
333         }else{
334             $strcalc .= " AND biblioitems.itemtype like "
335         } 
336         $strcalc .= "'" . @$filters[5] ."'" ;
337     }
338     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
339     $strcalc .= " AND itemcallnumber like '" . @$filters[6] ."'" if ( @$filters[6] );
340     @$filters[7]=~ s/\*/%/g if (@$filters[7]);
341     $strcalc .= " AND ccode like '" . @$filters[7] ."'" if ( @$filters[7] );
342     @$filters[8]=~ s/\*/%/g if (@$filters[8]);
343     $strcalc .= " AND location like '" . @$filters[8] ."'" if ( @$filters[8] );
344     @$filters[9]=~ s/\*/%/g if (@$filters[9]);
345     $strcalc .= " AND borrowers.categorycode like '" . @$filters[9] ."'" if ( @$filters[9] );
346     @$filters[10]=~ s/\*/%/g if (@$filters[10]);
347     $strcalc .= " AND dayname(old_issues.timestamp) like '" . @$filters[10]."'" if (@$filters[10]);
348     @$filters[11]=~ s/\*/%/g if (@$filters[11]);
349     $strcalc .= " AND monthname(old_issues.timestamp) like '" . @$filters[11]."'" if (@$filters[11]);
350     @$filters[12]=~ s/\*/%/g if (@$filters[12]);
351     $strcalc .= " AND year(old_issues.timestamp) like '" . @$filters[12] ."'" if ( @$filters[12] );
352     
353     $strcalc .= " group by biblio.biblionumber";
354     $strcalc .= ", $colfield" if ($column);
355     $strcalc .= " order by RANK DESC";
356     $strcalc .= ", $colfield " if ($colfield);
357     
358     my $dbcalc = $dbh->prepare($strcalc);
359     $dbcalc->execute;
360     my $previous_col;
361     my %indice;
362     while (my  @data = $dbcalc->fetchrow) {
363         my ($row, $rank, $id, $callnum, $ccode, $loc, $col )=@data;
364         $col = "zzEMPTY" if (!defined($col));
365         $indice{$col}=1 if (not($indice{$col}));
366         $table[$indice{$col}]->{$col}->{'name'}=$row;
367         $table[$indice{$col}]->{$col}->{'count'}=$rank;
368         $table[$indice{$col}]->{$col}->{'link'}=$id;
369         $indice{$col}++;
370     }
371     
372     push @loopcol,{coltitle => "Global"} if not($column);
373     
374     for ($i=1; $i<=$line;$i++) {
375         my @loopcell;
376         #@loopcol ensures the order for columns is common with column titles
377         # and the number matches the number of columns
378         my $colcount=0;
379         foreach my $col ( @loopcol ) {
380             my $value;
381             my $count=0;
382             my $link;
383             if (@loopcol){
384                 $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'name'};
385                 $count =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'count'};
386                 $link =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'link'};
387             } else {
388                 $value =$table[$i]->{"zzEMPTY"}->{'name'};
389                 $count =$table[$i]->{"zzEMPTY"}->{'count'};
390                 $link =$table[$i]->{"zzEMPTY"}->{'link'};
391             }
392             push @loopcell, {value => $value, count =>$count, reference => $link} ;
393         }
394         #my $total = $table[$i]->{totalrow}/$colcount if ($colcount>0);
395         push @looprow,{ 'rowtitle' => $i ,
396                         'loopcell' => \@loopcell,
397                         'hilighted' => ($hilighted >0),
398                     };
399         $hilighted = -$hilighted;
400     }
401 #       
402             
403
404     # the header of the table
405     $globalline{loopfilter}=\@loopfilter;
406     # the core of the table
407     $globalline{looprow} = \@looprow;
408     $globalline{loopcol} = \@loopcol;
409 #       # the foot (totals by borrower type)
410     $globalline{total}= $grantotal;
411     $globalline{line} = $line;
412     $globalline{column} = $column;
413     push @mainloop,\%globalline;
414     return \@mainloop;
415 }
416
417 1;