Bug 22770: DBRev 19.05.00.003
[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     
106     my $CGIextChoice = ( 'CSV' ); # FIXME translation
107     my $CGIsepChoice=GetDelimiterChoices;
108
109     #doctype
110     my $itemtypes = Koha::ItemTypes->search_with_localization;
111
112     #ccode
113     my $ccodes = GetAuthorisedValues('CCODE');
114     my @ccodeloop;
115     for my $thisccode (@$ccodes) {
116             my %row = (value => $thisccode->{authorised_value},
117                        description => $thisccode->{lib},
118                             );
119             push @ccodeloop, \%row;
120     }
121
122     @ccodeloop = sort {$a->{value} cmp $b->{value}} @ccodeloop;
123
124     #shelvingloc
125     my $shelvinglocs = GetAuthorisedValues('LOC');
126     my @shelvinglocloop;
127     for my $thisloc (@$shelvinglocs) {
128             my %row = (value => $thisloc->{authorised_value},
129                        description => $thisloc->{lib},
130                             );
131             push @shelvinglocloop, \%row;
132     }
133
134     @shelvinglocloop = sort {$a->{value} cmp $b->{value}} @shelvinglocloop;
135
136     my $patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['categorycode']});
137
138     $template->param(
139                     CGIextChoice => $CGIextChoice,
140                     CGIsepChoice => $CGIsepChoice,
141                     itemtypes => $itemtypes,
142                     ccodeloop =>\@ccodeloop,
143                     shelvinglocloop =>\@shelvinglocloop,
144                     patron_categories => $patron_categories,
145                     );
146 output_html_with_http_headers $input, $cookie, $template->output;
147 }
148
149
150
151
152 sub calculate {
153     my ($line, $column, $filters) = @_;
154     my @mainloop;
155     my @loopcol;
156     my @looprow;
157     my %globalline;
158     my $grantotal =0;
159 # extract parameters
160     my $dbh = C4::Context->dbh;
161
162 # Filters
163 # Checking filters
164 #
165     my @loopfilter;
166     for (my $i=0;$i<=12;$i++) {
167         my %cell;
168         if ( @$filters[$i] ) {
169             if (($i==1) and (@$filters[$i-1])) {
170                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
171             }
172             # format the dates filters, otherwise just fill as is
173             if ($i>=2) {
174                 $cell{filter} .= @$filters[$i];
175             } else {
176                 $cell{filter} .= eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
177                    if ( @$filters[$i] );
178             }
179             $cell{crit} .="Issue From" if ($i==0);
180             $cell{crit} .="Issue To" if ($i==1);
181             $cell{crit} .="Return From" if ($i==2);
182             $cell{crit} .="Return To" if ($i==3);
183             $cell{crit} .="Branch" if ($i==4);
184             $cell{crit} .="Doc Type" if ($i==5);
185             $cell{crit} .="Call number" if ($i==6);
186             $cell{crit} .="Collection code" if ($i==7);
187             $cell{crit} .="Shelving location" if ($i==8);
188             $cell{crit} .="Bor Cat" if ($i==9);
189             $cell{crit} .="Day" if ($i==10);
190             $cell{crit} .="Month" if ($i==11);
191             $cell{crit} .="Year" if ($i==12);
192             push @loopfilter, \%cell;
193         }
194     }
195     my $colfield;
196     my $colorder;
197     if ($column){
198         $column = "old_issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/));
199         if($column=~/itemtype/){
200             $column = C4::Context->preference('item-level_itypes') ? "items.itype": "biblioitems.itemtype";
201         }
202         $column = "borrowers.".$column if $column=~/categorycode/;
203         my @colfilter ;
204         $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ )  ;
205         $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ )  ;
206         $colfilter[0] = @$filters[2] if ($column =~ /returndate/ )  ;
207         $colfilter[1] = @$filters[3] if ($column =~ /returndate/ )  ;
208         $colfilter[0] = @$filters[4] if ($column =~ /branch/ )  ;
209         $colfilter[0] = @$filters[5] if ($column =~ /itemtype/ )  ;
210       # These limits does not currently exist, maybe later?
211       # $colfilter[0] = @$filters[6] if ($column =~ /ccode/ )  ;
212       # $colfilter[0] = @$filters[7] if ($column =~ /location/ )  ;
213         $colfilter[0] = @$filters[8] if ($column =~ /category/ )  ;
214       # This commented out row (sort2) was not removed when adding new filters for ccode, shelving location and call number
215       # $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
216         $colfilter[0] = @$filters[9] if ($column =~ /timestamp/ ) ;
217         $colfilter[0] = @$filters[10] if ($column =~ /timestamp/ ) ;
218         $colfilter[0] = @$filters[11] if ($column =~ /timestamp/ ) ;
219     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
220                                                 
221     # loop cols.
222         if ($column eq "Day") {
223             #Display by day
224             $column = "old_issues.timestamp";
225             $colfield .="dayname($column)";  
226             $colorder .="weekday($column)";
227         } elsif ($column eq "Month") {
228             #Display by Month
229             $column = "old_issues.timestamp";
230             $colfield .="monthname($column)";  
231             $colorder .="month($column)";  
232         } elsif ($column eq "Year") {
233             #Display by Year
234             $column = "old_issues.timestamp";
235             $colfield .="Year($column)";
236             $colorder .= $column;
237         } else {
238             $colfield .= $column;
239             $colorder .= $column;
240         }  
241         
242         my $strsth2;
243         $strsth2 .= "SELECT distinctrow $colfield 
244                      FROM `old_issues` 
245                      LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber 
246                      LEFT JOIN items ON old_issues.itemnumber=items.itemnumber 
247                      LEFT JOIN biblioitems  ON biblioitems.biblioitemnumber=items.biblioitemnumber 
248                      WHERE 1";
249         if (($column=~/timestamp/) or ($column=~/returndate/)){
250             if ($colfilter[1] and ($colfilter[0])){
251                 $strsth2 .= " and $column between '$colfilter[0]' and '$colfilter[1]' " ;
252             } elsif ($colfilter[1]) {
253                     $strsth2 .= " and $column < '$colfilter[1]' " ;
254             } elsif ($colfilter[0]) {
255                 $strsth2 .= " and $column > '$colfilter[0]' " ;
256             }
257         } elsif ($colfilter[0]) {
258             $colfilter[0] =~ s/\*/%/g;
259             $strsth2 .= " and $column LIKE '$colfilter[0]' " ;
260         }
261         $strsth2 .=" group by $colfield";
262         $strsth2 .=" order by $colorder";
263         
264         my $sth2 = $dbh->prepare( $strsth2 );
265         if (( @colfilter ) and ($colfilter[1])){
266             $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'");
267         } elsif ($colfilter[0]) {
268             $sth2->execute($colfilter[0]);
269         } else {
270             $sth2->execute;
271         }
272         
273     
274         while (my ($celvalue) = $sth2->fetchrow) {
275             my %cell;
276             $cell{coltitle} = ($celvalue?$celvalue:"NULL");
277             push @loopcol, \%cell;
278         }
279     #   warn "fin des titres colonnes";
280     }
281     
282     my $i=0;
283 #       my @totalcol;
284     my $hilighted=-1;
285     
286     #Initialization of cell values.....
287     my @table;
288     
289 #       warn "init table";
290     for (my $i=1;$i<=$line;$i++) {
291         foreach my $col ( @loopcol ) {
292 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
293             $table[$i]->{($col->{coltitle})?$col->{coltitle}:"total"}->{'name'}=0;
294         }
295     }
296
297
298 # preparing calculation
299     my $strcalc ;
300     
301 # Processing average loanperiods
302     $strcalc .= "SELECT DISTINCT biblio.title, COUNT(biblio.biblionumber) AS RANK, biblio.biblionumber AS ID";
303     $strcalc .= ", itemcallnumber as CALLNUM";
304     $strcalc .= ", ccode as CCODE";
305     $strcalc .= ", location as LOC";
306     $strcalc .= " , $colfield " if ($colfield);
307     $strcalc .= " FROM `old_issues` 
308                   LEFT JOIN items USING(itemnumber) 
309                   LEFT JOIN biblio USING(biblionumber) 
310                   LEFT JOIN biblioitems USING(biblionumber)
311                   LEFT JOIN borrowers USING(borrowernumber)
312                   WHERE 1";
313
314     @$filters[0]=~ s/\*/%/g if (@$filters[0]);
315     $strcalc .= " AND old_issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
316     @$filters[1]=~ s/\*/%/g if (@$filters[1]);
317     $strcalc .= " AND old_issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] );
318     @$filters[2]=~ s/\*/%/g if (@$filters[2]);
319     $strcalc .= " AND old_issues.returndate > '" . @$filters[2] ."'" if ( @$filters[2] );
320     @$filters[3]=~ s/\*/%/g if (@$filters[3]);
321     $strcalc .= " AND old_issues.returndate < '" . @$filters[3] ."'" if ( @$filters[3] );
322     @$filters[4]=~ s/\*/%/g if (@$filters[4]);
323     $strcalc .= " AND old_issues.branchcode like '" . @$filters[4] ."'" if ( @$filters[4] );
324     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
325     if ( @$filters[5] ){
326         if(C4::Context->preference('item-level_itypes') ){
327             $strcalc .= " AND items.itype like "
328         }else{
329             $strcalc .= " AND biblioitems.itemtype like "
330         } 
331         $strcalc .= "'" . @$filters[5] ."'" ;
332     }
333     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
334     $strcalc .= " AND itemcallnumber like '" . @$filters[6] ."'" if ( @$filters[6] );
335     @$filters[7]=~ s/\*/%/g if (@$filters[7]);
336     $strcalc .= " AND ccode like '" . @$filters[7] ."'" if ( @$filters[7] );
337     @$filters[8]=~ s/\*/%/g if (@$filters[8]);
338     $strcalc .= " AND location like '" . @$filters[8] ."'" if ( @$filters[8] );
339     @$filters[9]=~ s/\*/%/g if (@$filters[9]);
340     $strcalc .= " AND borrowers.categorycode like '" . @$filters[9] ."'" if ( @$filters[9] );
341     @$filters[10]=~ s/\*/%/g if (@$filters[10]);
342     $strcalc .= " AND dayname(old_issues.timestamp) like '" . @$filters[10]."'" if (@$filters[10]);
343     @$filters[11]=~ s/\*/%/g if (@$filters[11]);
344     $strcalc .= " AND monthname(old_issues.timestamp) like '" . @$filters[11]."'" if (@$filters[11]);
345     @$filters[12]=~ s/\*/%/g if (@$filters[12]);
346     $strcalc .= " AND year(old_issues.timestamp) like '" . @$filters[12] ."'" if ( @$filters[12] );
347     
348     $strcalc .= " group by biblio.biblionumber";
349     $strcalc .= ", $colfield" if ($column);
350     $strcalc .= " order by RANK DESC";
351     $strcalc .= ", $colfield " if ($colfield);
352     
353     my $dbcalc = $dbh->prepare($strcalc);
354     $dbcalc->execute;
355     my %indice;
356     while (my  @data = $dbcalc->fetchrow) {
357         my ($row, $rank, $id, $callnum, $ccode, $loc, $col )=@data;
358         $col = "zzEMPTY" if (!defined($col));
359         $indice{$col}=1 if (not($indice{$col}));
360         $table[$indice{$col}]->{$col}->{'name'}=$row;
361         $table[$indice{$col}]->{$col}->{'count'}=$rank;
362         $table[$indice{$col}]->{$col}->{'link'}=$id;
363         $indice{$col}++;
364     }
365     
366     push @loopcol,{coltitle => "Global"} if not($column);
367     
368     for ($i=1; $i<=$line;$i++) {
369         my @loopcell;
370         #@loopcol ensures the order for columns is common with column titles
371         # and the number matches the number of columns
372         my $colcount=0;
373         foreach my $col ( @loopcol ) {
374             my $value;
375             my $count=0;
376             my $link;
377             if (@loopcol){
378                 $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'name'};
379                 $count =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'count'};
380                 $link =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'link'};
381             } else {
382                 $value =$table[$i]->{"zzEMPTY"}->{'name'};
383                 $count =$table[$i]->{"zzEMPTY"}->{'count'};
384                 $link =$table[$i]->{"zzEMPTY"}->{'link'};
385             }
386             push @loopcell, {value => $value, count =>$count, reference => $link} ;
387         }
388         #my $total = $table[$i]->{totalrow}/$colcount if ($colcount>0);
389         push @looprow,{ 'rowtitle' => $i ,
390                         'loopcell' => \@loopcell,
391                         'hilighted' => ($hilighted >0),
392                     };
393         $hilighted = -$hilighted;
394     }
395 #       
396             
397
398     # the header of the table
399     $globalline{loopfilter}=\@loopfilter;
400     # the core of the table
401     $globalline{looprow} = \@looprow;
402     $globalline{loopcol} = \@loopcol;
403 #       # the foot (totals by borrower type)
404     $globalline{total}= $grantotal;
405     $globalline{line} = $line;
406     $globalline{column} = $column;
407     push @mainloop,\%globalline;
408     return \@mainloop;
409 }
410
411 1;