Bug 15407: Koha::Patron::Categories - replace GetborCatFromCatType
[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 strict;
22 #use warnings; FIXME - Bug 2505
23 use C4::Auth;
24 use CGI qw ( -utf8 );
25 use C4::Context;
26 use C4::Branch; # GetBranches
27 use C4::Output;
28 use C4::Koha;
29 use C4::Circulation;
30 use C4::Reports;
31 use C4::Members;
32 use Koha::DateUtils;
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 my $input = new CGI;
45 my $do_it=$input->param('do_it');
46 my $fullreportname = "reports/cat_issues_top.tt";
47 my $limit = $input->param("Limit");
48 my $column = $input->param("Criteria");
49 my @filters = $input->multi_param("Filter");
50 foreach ( @filters[0..3] ) {
51     $_ and $_ = eval { output_pref( { dt => dt_from_string ( $_ ), dateonly => 1, dateformat => 'iso' } ); };
52 }
53
54 my $output = $input->param("output");
55 my $basename = $input->param("basename");
56 #warn "calcul : ".$calc;
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,
75                         limit => $limit);
76         output_html_with_http_headers $input, $cookie, $template->output;
77         exit;
78     } else {
79 # Printing to a csv file
80         print $input->header(-type => 'application/vnd.sun.xml.calc',
81                             -encoding    => 'utf-8',
82                             -attachment=>"$basename.csv",
83                             -filename=>"$basename.csv" );
84         my $cols = @$results[0]->{loopcol};
85         my $lines = @$results[0]->{looprow};
86 # header top-right
87         print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
88 # Other header
89         foreach my $col ( @$cols ) {
90             print $col->{coltitle}.$sep;
91         }
92         print "Total\n";
93 # Table
94         foreach my $line ( @$lines ) {
95             my $x = $line->{loopcell};
96             print $line->{rowtitle}.$sep;
97             foreach my $cell (@$x) {
98                 print $cell->{value}.$sep;
99             }
100             print $line->{totalrow};
101             print "\n";
102         }
103 # footer
104         print "TOTAL";
105         $cols = @$results[0]->{loopfooter};
106         foreach my $col ( @$cols ) {
107             print $sep.$col->{totalcol};
108         }
109         print $sep.@$results[0]->{total};
110         exit;
111     }
112 # Displaying choices
113 } else {
114     my $dbh = C4::Context->dbh;
115     my @values;
116     my %labels;
117     my %select;
118     my $req;
119     
120     my $CGIextChoice = ( 'CSV' ); # FIXME translation
121     my $CGIsepChoice=GetDelimiterChoices;
122
123     #doctype
124     my $itemtypes = GetItemTypes;
125     my @itemtypeloop;
126     foreach my $thisitemtype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description}} keys %$itemtypes) {
127             my %row =(value => $thisitemtype,
128                       description => $itemtypes->{$thisitemtype}->{translated_description},
129                             );
130             push @itemtypeloop, \%row;
131     }
132
133     #ccode
134     my $ccodes = GetAuthorisedValues('CCODE');
135     my @ccodeloop;
136     for my $thisccode (@$ccodes) {
137             my %row = (value => $thisccode->{authorised_value},
138                        description => $thisccode->{lib},
139                             );
140             push @ccodeloop, \%row;
141     }
142
143     @ccodeloop = sort {$a->{value} cmp $b->{value}} @ccodeloop;
144
145     #shelvingloc
146     my $shelvinglocs = GetAuthorisedValues('LOC');
147     my @shelvinglocloop;
148     for my $thisloc (@$shelvinglocs) {
149             my %row = (value => $thisloc->{authorised_value},
150                        description => $thisloc->{lib},
151                             );
152             push @shelvinglocloop, \%row;
153     }
154
155     @shelvinglocloop = sort {$a->{value} cmp $b->{value}} @shelvinglocloop;
156
157     my $patron_categories = Koha::Patron::Categories->search_limited({}, {order_by => ['categorycode']});
158
159     $template->param(
160                     CGIextChoice => $CGIextChoice,
161                     CGIsepChoice => $CGIsepChoice,
162                     branchloop => GetBranchesLoop(C4::Context->userenv->{'branch'}),
163                     itemtypeloop =>\@itemtypeloop,
164                     ccodeloop =>\@ccodeloop,
165                     shelvinglocloop =>\@shelvinglocloop,
166                     patron_categories => $patron_categories,
167                     );
168 output_html_with_http_headers $input, $cookie, $template->output;
169 }
170
171
172
173
174 sub calculate {
175     my ($line, $column, $filters) = @_;
176     my @mainloop;
177     my @loopfooter;
178     my @loopcol;
179     my @loopline;
180     my @looprow;
181     my %globalline;
182     my $grantotal =0;
183 # extract parameters
184     my $dbh = C4::Context->dbh;
185
186 # Filters
187 # Checking filters
188 #
189     my @loopfilter;
190     for (my $i=0;$i<=12;$i++) {
191         my %cell;
192         if ( @$filters[$i] ) {
193             if (($i==1) and (@$filters[$i-1])) {
194                 $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
195             }
196             # format the dates filters, otherwise just fill as is
197             if ($i>=2) {
198                 $cell{filter} .= @$filters[$i];
199             } else {
200                 $cell{filter} .= eval { output_pref( { dt => dt_from_string( @$filters[$i] ), dateonly => 1 }); }
201                    if ( @$filters[$i] );
202             }
203             $cell{crit} .="Issue From" if ($i==0);
204             $cell{crit} .="Issue To" if ($i==1);
205             $cell{crit} .="Return From" if ($i==2);
206             $cell{crit} .="Return To" if ($i==3);
207             $cell{crit} .="Branch" if ($i==4);
208             $cell{crit} .="Doc Type" if ($i==5);
209             $cell{crit} .="Call number" if ($i==6);
210             $cell{crit} .="Collection code" if ($i==7);
211             $cell{crit} .="Shelving location" if ($i==8);
212             $cell{crit} .="Bor Cat" if ($i==9);
213             $cell{crit} .="Day" if ($i==10);
214             $cell{crit} .="Month" if ($i==11);
215             $cell{crit} .="Year" if ($i==12);
216             push @loopfilter, \%cell;
217         }
218     }
219     my $colfield;
220     my $colorder;
221     if ($column){
222         $column = "old_issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/));
223         if($column=~/itemtype/){
224             $column = C4::Context->preference('item-level_itypes') ? "items.itype": "biblioitems.itemtype";
225         }
226         $column = "borrowers.".$column if $column=~/categorycode/;
227         my @colfilter ;
228         $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ )  ;
229         $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ )  ;
230         $colfilter[0] = @$filters[2] if ($column =~ /returndate/ )  ;
231         $colfilter[1] = @$filters[3] if ($column =~ /returndate/ )  ;
232         $colfilter[0] = @$filters[4] if ($column =~ /branch/ )  ;
233         $colfilter[0] = @$filters[5] if ($column =~ /itemtype/ )  ;
234       # These limits does not currently exist, maybe later?
235       # $colfilter[0] = @$filters[6] if ($column =~ /ccode/ )  ;
236       # $colfilter[0] = @$filters[7] if ($column =~ /location/ )  ;
237         $colfilter[0] = @$filters[8] if ($column =~ /category/ )  ;
238       # This commented out row (sort2) was not removed when adding new filters for ccode, shelving location and call number
239       # $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ;
240         $colfilter[0] = @$filters[9] if ($column =~ /timestamp/ ) ;
241         $colfilter[0] = @$filters[10] if ($column =~ /timestamp/ ) ;
242         $colfilter[0] = @$filters[11] if ($column =~ /timestamp/ ) ;
243     #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
244                                                 
245     # loop cols.
246         if ($column eq "Day") {
247             #Display by day
248             $column = "old_issues.timestamp";
249             $colfield .="dayname($column)";  
250             $colorder .="weekday($column)";
251         } elsif ($column eq "Month") {
252             #Display by Month
253             $column = "old_issues.timestamp";
254             $colfield .="monthname($column)";  
255             $colorder .="month($column)";  
256         } elsif ($column eq "Year") {
257             #Display by Year
258             $column = "old_issues.timestamp";
259             $colfield .="Year($column)";
260             $colorder .= $column;
261         } else {
262             $colfield .= $column;
263             $colorder .= $column;
264         }  
265         
266         my $strsth2;
267         $strsth2 .= "SELECT distinctrow $colfield 
268                      FROM `old_issues` 
269                      LEFT JOIN borrowers ON borrowers.borrowernumber=old_issues.borrowernumber 
270                      LEFT JOIN items ON old_issues.itemnumber=items.itemnumber 
271                      LEFT JOIN biblioitems  ON biblioitems.biblioitemnumber=items.biblioitemnumber 
272                      WHERE 1";
273         if (($column=~/timestamp/) or ($column=~/returndate/)){
274             if ($colfilter[1] and ($colfilter[0])){
275                 $strsth2 .= " and $column between '$colfilter[0]' and '$colfilter[1]' " ;
276             } elsif ($colfilter[1]) {
277                     $strsth2 .= " and $column < '$colfilter[1]' " ;
278             } elsif ($colfilter[0]) {
279                 $strsth2 .= " and $column > '$colfilter[0]' " ;
280             }
281         } elsif ($colfilter[0]) {
282             $colfilter[0] =~ s/\*/%/g;
283             $strsth2 .= " and $column LIKE '$colfilter[0]' " ;
284         }
285         $strsth2 .=" group by $colfield";
286         $strsth2 .=" order by $colorder";
287         
288         my $sth2 = $dbh->prepare( $strsth2 );
289         if (( @colfilter ) and ($colfilter[1])){
290             $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'");
291         } elsif ($colfilter[0]) {
292             $sth2->execute($colfilter[0]);
293         } else {
294             $sth2->execute;
295         }
296         
297     
298         while (my ($celvalue) = $sth2->fetchrow) {
299             my %cell;
300             $cell{coltitle} = ($celvalue?$celvalue:"NULL");
301             push @loopcol, \%cell;
302         }
303     #   warn "fin des titres colonnes";
304     }
305     
306     my $i=0;
307 #       my @totalcol;
308     my $hilighted=-1;
309     
310     #Initialization of cell values.....
311     my @table;
312     
313 #       warn "init table";
314     for (my $i=1;$i<=$line;$i++) {
315         foreach my $col ( @loopcol ) {
316 #                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
317             $table[$i]->{($col->{coltitle})?$col->{coltitle}:"total"}->{'name'}=0;
318         }
319     }
320
321
322 # preparing calculation
323     my $strcalc ;
324     
325 # Processing average loanperiods
326     $strcalc .= "SELECT DISTINCT biblio.title, COUNT(biblio.biblionumber) AS RANK, biblio.biblionumber AS ID";
327     $strcalc .= ", itemcallnumber as CALLNUM";
328     $strcalc .= ", ccode as CCODE";
329     $strcalc .= ", location as LOC";
330     $strcalc .= " , $colfield " if ($colfield);
331     $strcalc .= " FROM `old_issues` 
332                   LEFT JOIN items USING(itemnumber) 
333                   LEFT JOIN biblio USING(biblionumber) 
334                   LEFT JOIN biblioitems USING(biblionumber)
335                   LEFT JOIN borrowers USING(borrowernumber)
336                   WHERE 1";
337
338     @$filters[0]=~ s/\*/%/g if (@$filters[0]);
339     $strcalc .= " AND old_issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
340     @$filters[1]=~ s/\*/%/g if (@$filters[1]);
341     $strcalc .= " AND old_issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] );
342     @$filters[2]=~ s/\*/%/g if (@$filters[2]);
343     $strcalc .= " AND old_issues.returndate > '" . @$filters[2] ."'" if ( @$filters[2] );
344     @$filters[3]=~ s/\*/%/g if (@$filters[3]);
345     $strcalc .= " AND old_issues.returndate < '" . @$filters[3] ."'" if ( @$filters[3] );
346     @$filters[4]=~ s/\*/%/g if (@$filters[4]);
347     $strcalc .= " AND old_issues.branchcode like '" . @$filters[4] ."'" if ( @$filters[4] );
348     @$filters[5]=~ s/\*/%/g if (@$filters[5]);
349     if ( @$filters[5] ){
350         if(C4::Context->preference('item-level_itypes') ){
351             $strcalc .= " AND items.itype like "
352         }else{
353             $strcalc .= " AND biblioitems.itemtype like "
354         } 
355         $strcalc .= "'" . @$filters[5] ."'" ;
356     }
357     @$filters[6]=~ s/\*/%/g if (@$filters[6]);
358     $strcalc .= " AND itemcallnumber like '" . @$filters[6] ."'" if ( @$filters[6] );
359     @$filters[7]=~ s/\*/%/g if (@$filters[7]);
360     $strcalc .= " AND ccode like '" . @$filters[7] ."'" if ( @$filters[7] );
361     @$filters[8]=~ s/\*/%/g if (@$filters[8]);
362     $strcalc .= " AND location like '" . @$filters[8] ."'" if ( @$filters[8] );
363     @$filters[9]=~ s/\*/%/g if (@$filters[9]);
364     $strcalc .= " AND borrowers.categorycode like '" . @$filters[9] ."'" if ( @$filters[9] );
365     @$filters[10]=~ s/\*/%/g if (@$filters[10]);
366     $strcalc .= " AND dayname(old_issues.timestamp) like '" . @$filters[10]."'" if (@$filters[10]);
367     @$filters[11]=~ s/\*/%/g if (@$filters[11]);
368     $strcalc .= " AND monthname(old_issues.timestamp) like '" . @$filters[11]."'" if (@$filters[11]);
369     @$filters[12]=~ s/\*/%/g if (@$filters[12]);
370     $strcalc .= " AND year(old_issues.timestamp) like '" . @$filters[12] ."'" if ( @$filters[12] );
371     
372     $strcalc .= " group by biblio.biblionumber";
373     $strcalc .= ", $colfield" if ($column);
374     $strcalc .= " order by RANK DESC";
375     $strcalc .= ", $colfield " if ($colfield);
376     
377     my $dbcalc = $dbh->prepare($strcalc);
378     $dbcalc->execute;
379     my $previous_col;
380     my %indice;
381     while (my  @data = $dbcalc->fetchrow) {
382         my ($row, $rank, $id, $callnum, $ccode, $loc, $col )=@data;
383         $col = "zzEMPTY" if (!defined($col));
384         $indice{$col}=1 if (not($indice{$col}));
385         $table[$indice{$col}]->{$col}->{'name'}=$row;
386         $table[$indice{$col}]->{$col}->{'count'}=$rank;
387         $table[$indice{$col}]->{$col}->{'link'}=$id;
388         $indice{$col}++;
389     }
390     
391     push @loopcol,{coltitle => "Global"} if not($column);
392     
393     for ($i=1; $i<=$line;$i++) {
394         my @loopcell;
395         #@loopcol ensures the order for columns is common with column titles
396         # and the number matches the number of columns
397         my $colcount=0;
398         foreach my $col ( @loopcol ) {
399             my $value;
400             my $count=0;
401             my $link;
402             if (@loopcol){
403                 $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'name'};
404                 $count =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'count'};
405                 $link =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'link'};
406             } else {
407                 $value =$table[$i]->{"zzEMPTY"}->{'name'};
408                 $count =$table[$i]->{"zzEMPTY"}->{'count'};
409                 $link =$table[$i]->{"zzEMPTY"}->{'link'};
410             }
411             push @loopcell, {value => $value, count =>$count, reference => $link} ;
412         }
413         #my $total = $table[$i]->{totalrow}/$colcount if ($colcount>0);
414         push @looprow,{ 'rowtitle' => $i ,
415                         'loopcell' => \@loopcell,
416                         'hilighted' => ($hilighted >0),
417                     };
418         $hilighted = -$hilighted;
419     }
420 #       
421             
422
423     # the header of the table
424     $globalline{loopfilter}=\@loopfilter;
425     # the core of the table
426     $globalline{looprow} = \@looprow;
427     $globalline{loopcol} = \@loopcol;
428 #       # the foot (totals by borrower type)
429     $globalline{loopfooter} = \@loopfooter;
430     $globalline{total}= $grantotal;
431     $globalline{line} = $line;
432     $globalline{column} = $column;
433     push @mainloop,\%globalline;
434     return \@mainloop;
435 }
436
437 1;