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